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 a workspace owner delete an emptied workspace (#1002)
Abel Dantas86d592881f80
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0230d199b..3a5fd40b1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -138,6 +138,15 @@ version of their own to them without also giving them a release of their own.client is refused; any other agent gets a new API key that only the newowner can see, so it has to be reconnected. Chats and room documents are nottransferable.+- **Workspace admins can delete an empty workspace.** Workspace settings has a+ Delete workspace action that asks for the workspace's name+ (`DELETE /tenants/{id}`). It is refused, with what is left by kind and count,+ until the workspace has no rooms (archived ones included), agents, packages,+ references, reference types, documents, templates, room groups, messaging or+ service connections, machines, connectors, skills or other members. Its audit+ history is kept, and the deletion is recorded in the server audit log. The+ server's default workspace can't be deleted. Deleting your account now also+ deletes a workspace you leave empty.- **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/src/clients/switch-client.ts b/console/tooling-e2e/src/clients/switch-client.tsindex c6cc3635e..1724b8b2c 100644--- a/console/tooling-e2e/src/clients/switch-client.ts+++ b/console/tooling-e2e/src/clients/switch-client.ts@@ -1031,6 +1031,43 @@ export class SwitchClient {);}+ /**+ * `DELETE /gateway/tenants/{tenant_id}` — delete the bound workspace, once it+ * is empty, by typing its name. Its own admins only. The server re-mints the+ * session onto the caller's only other workspace, if there is exactly one,+ * so from here on this client acts there.+ */+ async deleteTenant(tenantId: string, name: string): Promise<void> {+ const { response } = await this.rawRequest(+ "DELETE",+ `/gateway/tenants/${encodeURIComponent(tenantId)}`,+ { cookie: await this.gatewayLogin(), body: { name } },+ );+ const cookie = sessionCookieFrom(response);+ if (cookie) {+ this.issued.record(cookie.slice("switch_auth=".length));+ this.gatewayCookie = cookie;+ }+ }++ /** `POST /gateway/ownership/transfer` — make another member of this workspace the owner of something. */+ async transferOwnership(params: {+ kind: "agent" | "room" | "package" | "reference" | "reference_type" | "document" | "template";+ id: string;+ newOwnerId: string;+ }): Promise<{ kind: string; id: string; owner_id: string; agent_key_reissued: boolean }> {+ return this.gateway("POST", "/ownership/transfer", {+ kind: params.kind,+ id: params.id,+ new_owner_id: params.newOwnerId,+ });+ }++ /** `DELETE /gateway/users/{user_id}` — the deployment operator deletes someone's whole account. */+ async deleteUser(userId: string): Promise<void> {+ await this.gateway<unknown>("DELETE", `/users/${encodeURIComponent(userId)}`);+ }+/** `GET /gateway/operator/workspaces` — every workspace on the server, platform operator only. */async operatorWorkspaces(): Promise<{ id: string; name: string }[]> {return this.gateway<{ id: string; name: string }[]>("GET", "/operator/workspaces");diff --git a/console/tooling-e2e/src/fast/account-lifecycle.ts b/console/tooling-e2e/src/fast/account-lifecycle.tsnew file mode 100644index 000000000..e3f40c6c8--- /dev/null+++ b/console/tooling-e2e/src/fast/account-lifecycle.ts@@ -0,0 +1,126 @@+import { expect } from "vitest";+import { SwitchHttpError, errorDetail } from "../clients/switch-client.ts";+import type { FastScenario } from "./scenario.ts";++/**+ * What ends: ownership, a workspace and an account. The harness admin hands a+ * package to a colleague, who cannot hand on what is not theirs. A second+ * person makes a workspace of their own and deletes it, once they type its+ * name right. The colleague cannot delete anyone's account; the operator+ * deletes theirs, which ends their sign-in.+ *+ * The workspace maker is a deployment operator, so they can make a+ * workspace, and an operator's account cannot be deleted, so this runs only+ * on a stack thrown away after the run.+ */+export const accountLifecycle: FastScenario = {+ header: {+ id: "account-lifecycle",+ covers: [+ "POST /gateway/ownership/transfer",+ "DELETE /gateway/tenants/{tenant_id}",+ "DELETE /gateway/users/{user_id}",+ ],+ lane: "fast",+ environments: ["ephemeral"],+ owner: "platform",+ requires: [],+ },+ async run({ names, switchClient, fixtures }) {+ const status = async (+ call: () => Promise<unknown>,+ ): Promise<[number, string]> => {+ try {+ await call();+ } catch (error) {+ if (error instanceof SwitchHttpError)+ return [error.status, errorDetail(error.body)];+ throw error;+ }+ return [200, ""];+ };++ const password = `e2e-${names.runId}-${crypto.randomUUID()}`;+ const email = `${names.name("colleague")}@e2e.invalid`;+ const { id: colleagueId } = await switchClient.createUser({+ name: "E2E colleague",+ email,+ password,+ role: "user",+ });+ const colleague = switchClient.as(email, password);+ // Signing in joins the default workspace, where the transfer happens.+ await colleague.tenantId();++ const given = await switchClient.createPackage({+ name: names.name("given"),+ description: `Switch end-to-end harness, handed over (run ${names.runId}).`,+ instructions: "",+ });+ fixtures.defer(`the handed-over package ${given.name}`, async () => {+ // Deleting the colleague's account may already have deleted it.+ const [code, detail] = await status(() =>+ switchClient.deletePackage(given.id),+ );+ if (code !== 200 && code !== 404) throw new Error(`${code}: ${detail}`);+ });+ const kept = await switchClient.createPackage({+ name: names.name("kept"),+ description: `Switch end-to-end harness, not handed over (run ${names.runId}).`,+ instructions: "",+ });+ fixtures.defer(`the kept package ${kept.name}`, () =>+ switchClient.deletePackage(kept.id),+ );++ const moved = await switchClient.transferOwnership({+ kind: "package",+ id: given.id,+ newOwnerId: colleagueId,+ });+ expect(moved, "the package handed to the colleague").toMatchObject({+ kind: "package",+ id: given.id,+ owner_id: colleagueId,+ agent_key_reissued: false,+ });+ const [notTheirs] = await status(() =>+ colleague.transferOwnership({+ kind: "package",+ id: kept.id,+ newOwnerId: colleagueId,+ }),+ );+ expect(notTheirs, "a member taking what isn't theirs").toBe(403);++ const makerEmail = `${names.name("maker")}@e2e.invalid`;+ const { id: makerId } = await switchClient.createUser({+ name: "E2E workspace maker",+ email: makerEmail,+ password,+ role: "admin",+ });+ const maker = switchClient.as(makerEmail, password);+ const spaceName = names.name("space");+ const spaceId = await maker.createTenant(spaceName);+ const [wrongName] = await status(() =>+ maker.deleteTenant(spaceId, "not its name"),+ );+ expect(wrongName, "deleting with the wrong name").toBe(400);+ await maker.deleteTenant(spaceId, spaceName);+ const everyWorkspace = await switchClient.operatorWorkspaces();+ expect(+ everyWorkspace.map((row) => row.id),+ "the deleted workspace",+ ).not.toContain(spaceId);++ const [notOperator] = await status(() => colleague.deleteUser(makerId));+ expect(notOperator, "a member deleting someone's account").toBe(403);++ await switchClient.deleteUser(colleagueId);+ const [signIn] = await status(() =>+ switchClient.as(email, password).tenantId(),+ );+ expect(signIn, "signing in to a deleted account").toBe(401);+ },+};diff --git a/console/tooling-e2e/src/fast/index.ts b/console/tooling-e2e/src/fast/index.tsindex 5fc41a473..45ed35288 100644--- a/console/tooling-e2e/src/fast/index.ts+++ b/console/tooling-e2e/src/fast/index.ts@@ -1,3 +1,4 @@+import { accountLifecycle } from "./account-lifecycle.ts";import { agentIdentity } from "./agent-identity.ts";import { attachmentNames } from "./attachments.ts";import { clientMistakes } from "./client-mistakes.ts";@@ -25,4 +26,5 @@ export const FAST_SCENARIOS: readonly FastScenario[] = [followUps,organizationMembers,organizations,+ accountLifecycle,];diff --git a/console/tooling-e2e/surface/server-surface.json b/console/tooling-e2e/surface/server-surface.jsonindex a55606160..bd5ec6a00 100644--- a/console/tooling-e2e/surface/server-surface.json+++ b/console/tooling-e2e/surface/server-surface.json@@ -276,6 +276,11 @@"auth": "session","flags": []},+ {+ "route": "DELETE /gateway/tenants/{tenant_id}",+ "auth": "session",+ "flags": []+ },{"route": "DELETE /gateway/tenants/{tenant_id}/budgets/{budget_id}","auth": "session",diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.pyindex dc95cc741..0d1e263be 100644--- a/core/switch_core/accounts/deletion.py+++ b/core/switch_core/accounts/deletion.py@@ -20,8 +20,10 @@ ahead would strand something nobody else could reach:- an active messaging app installed in a workspace nobody else is in, whichwould keep receiving messages for no one.-A workspace the person is alone in is left empty rather than deleted: the-schema cannot delete a workspace yet.+A workspace the person is alone in is deleted once it is empty+(`workspace_deletion.py`). Rooms they created stay, so a workspace with any+room left, or anything else that refuses its deletion, is left empty instead,+for the operator to see.A workspace the person has left, or been removed from, can still hold rowsthat name them: removing a member deletes their keys and connections but not@@ -43,6 +45,11 @@ from typing import TYPE_CHECKING, Literal, Protocolfrom sqlalchemy import Select, case, delete, exists, func, or_, select, update+from switch_core.accounts.workspace_deletion import (+ WorkspaceDeletionRefused,+ delete_workspace,+)+from switch_core.accounts.workspace_deletion import refusal as workspace_refusalfrom switch_core.authz import ORGANIZATION_ADMIN_ROLEfrom switch_core.bridges.resource.service import ReferenceTypeInUseErrorfrom switch_core.connections.broker import ServiceError@@ -198,6 +205,15 @@ def _reference_type_heir(slug: str, user_id: str) -> Select[tuple[str]]:)+class TenantClients(Protocol):+ """Stops the clients the server runs for a deleted workspace, here and in+ every other process. The client lifecycle's."""++ async def reconcile_tenant(self, tenant_id: str) -> None: ...++ def announce(self, tenant_id: str) -> None: ...++class ControllerRevoker(Protocol):"""Revokes a machine, as removing it in Switch Console does. Agentmanagement's, handed over by the wiring: core does not import it."""@@ -247,6 +263,7 @@ class AccountDeletion:agents: AgentStoreapi_keys: ApiKeyStoretemplates: TemplateStore+ clients: TenantClientsadmin_email: strasync def with_former_workspaces(@@ -591,6 +608,52 @@ class AccountDeletion:warning,)+ if workspace.role != FORMER_MEMBER and successor is None:+ await self._close_if_empty(user_id, tenant_id, actor_id)++ async def _close_if_empty(+ self, user_id: str, tenant_id: str, actor_id: str+ ) -> None:+ """Delete a workspace the person leaves with nobody in it, once its+ tokens are revoked; leave it, saying why, when anything is left.+ Leaving it is never a reason to fail the account's deletion: the+ person has already left it, committed."""+ async with tenant_session(self.session_factory, tenant_id) as session:+ members = await self.users.list_tenant_members(session)+ if members:+ return+ reason = await workspace_refusal(session, tenant_id, user_id)+ if reason is not None:+ logger.info(+ "Workspace %s is left empty, not deleted, with user %s: %s",+ tenant_id,+ user_id,+ reason,+ )+ return+ try:+ key_hashes = await delete_workspace(+ session, tenant_id, user_id, actor_id+ )+ except WorkspaceDeletionRefused as refused:+ # Something arrived since the check above.+ await session.rollback()+ logger.warning(+ "Workspace %s is left empty, not deleted, with user %s: %s",+ tenant_id,+ user_id,+ refused,+ )+ return+ await session.commit()+ for key_hash in key_hashes:+ self.protocol.api_key_cache.invalidate(key_hash)+ await self.clients.reconcile_tenant(tenant_id)+ self.clients.announce(tenant_id)+ logger.info(+ "Deleted workspace %s, emptied by deleting user %s", tenant_id, user_id+ )+async def _still_not_the_last_admin(self, session: AsyncSession, user_id: str, workspace: Workspace) -> None:diff --git a/core/switch_core/accounts/workspace_deletion.py b/core/switch_core/accounts/workspace_deletion.pynew file mode 100644index 000000000..6c223fab4--- /dev/null+++ b/core/switch_core/accounts/workspace_deletion.py@@ -0,0 +1,328 @@+"""Deleting a workspace that has already been emptied.++Nothing here deletes anything a person made on purpose. A workspace can be+deleted only once its owner has removed, one by one and with each in front of+them, everything in `REFUSED`: rooms (archived ones too), agents, resources,+machines, messaging and service connections and every other member, and+until every service token issued in it that can still be revoked has been.+The refusal lists what is left, by kind and count. A record kept only as+history of something already ended (`TERMINAL`: a removed machine, a+disconnected messaging app, a cloud machine since deleted) does not count, and+goes with the workspace. What remains after that is the workspace's own setup+(its settings, invitations, join domains, usage counters and the clients the+server runs for it), which goes with it, in one transaction, and the `tenants`+row last.++The workspace's audit history stays (`KEPT`): `audit_events.tenant_id`+carries no foreign key so it can outlive the tenant, and the runtime role may+not delete it anyway. No member is left to read it; the deletion itself is+also recorded in the server's audit log, which outlives every workspace, in+the same transaction, whoever asked for it.++`WORKSPACE_TABLES` says what happens to every tenant-scoped table, and a test+holds it to the schema, so a table added later cannot be swept away with a+workspace, or left to hold one back, without saying which.++Concurrent writes are shut out by locking the `tenants` row: every insert into+a scoped table checks its foreign key to it, which waits on that lock and then+fails once the row is gone.+"""++from __future__ import annotations++from collections.abc import Callable+from typing import TYPE_CHECKING, Literal++from sqlalchemy import ColumnElement, Table, delete, func, select++from switch_core.db.audit import (+ AuditAction,+ ServerAuditAction,+ record_audit_event,+ record_server_audit_event,+)+from switch_core.db.base import Base+from switch_core.db.models import (+ TENANT_ZERO_ID,+ ApiKey,+ CloudMachine,+ Room,+ ServiceTokenIssuance,+ Tenant,+)+from switch_core.db.stores.messaging_install_store import INSTALL_ACTIVE++if TYPE_CHECKING:+ from sqlalchemy.ext.asyncio import AsyncSession++Handling = Literal["refused", "deleted", "kept"]++# Every tenant-scoped table, and what deleting the workspace does with its+# rows. "refused" means a row there blocks the deletion; `REFUSED` names it.+WORKSPACE_TABLES: dict[str, Handling] = {+ "rooms": "refused",+ "agents": "refused",+ "packages": "refused",+ "references": "refused",+ "reference_types": "refused",+ "documents": "refused",+ "templates": "refused",+ "room_groups": "refused",+ "messaging_installs": "refused",+ "collaboration_bridges": "refused",+ "machine_workspaces": "refused",+ "agent_controllers": "refused",+ "server_connectors": "refused",+ "skills": "refused",+ "service_connections": "refused",+ # Refused for anyone but the person deleting it; their own row goes.+ "tenant_members": "deleted",+ "audit_events": "kept",+ "tenants": "deleted",+ # Hang off a refused table, so they are empty by the time it is.+ "agent_connection_rooms": "deleted",+ "agent_connections": "deleted",+ "agent_controller_enrollment_codes": "deleted",+ "agent_controller_operations": "deleted",+ "agent_definitions": "deleted",+ "agent_event_drops": "deleted",+ "agent_event_heads": "deleted",+ "agent_events": "deleted",+ "agent_poll_positions": "deleted",+ "agent_position_tickets": "deleted",+ "agent_room_reads": "deleted",+ "agent_runtime_states": "deleted",+ "agent_session_command_relays": "deleted",+ "agent_session_placements": "deleted",+ "agent_sessions": "deleted",+ "agent_skills": "deleted",+ "approval_request_posts": "deleted",+ "approval_requests": "deleted",+ "bridge_message_map": "deleted",+ "chat_hidden": "deleted",+ "chat_reads": "deleted",+ "chat_operations": "deleted",+ "chat_owner_grants": "deleted",+ "client_rooms": "deleted",+ "delivery_cursors": "deleted",+ "external_user_claims": "deleted",+ "external_user_link_requests": "deleted",+ "external_users": "deleted",+ "media_blobs": "deleted",+ "message_attachments": "deleted",+ "messages": "deleted",+ "messaging_event_receipts": "deleted",+ "messaging_install_states": "deleted",+ "models": "deleted",+ "package_documents": "deleted",+ "package_references": "deleted",+ "pending_attachment_groups": "deleted",+ "role_leases": "deleted",+ "room_agents": "deleted",+ "room_documents": "deleted",+ "room_links": "deleted",+ "room_packages": "deleted",+ "room_references": "deleted",+ "room_roles": "deleted",+ "room_skills": "deleted",+ "sealed_provider_logins": "deleted",+ "service_grants": "deleted",+ "service_token_issuances": "deleted",+ "session_activity_items": "deleted",+ "tasks": "deleted",+ "template_install_resources": "deleted",+ "tools": "deleted",+ "turn_status_posts": "deleted",+ # The workspace's own setup, and what the person deleting it holds in it.+ "api_keys": "deleted",+ "clients": "deleted",+ "invitations": "deleted",+ "provider_connections": "deleted",+ "sign_in_flows": "deleted",+ "template_installs": "deleted",+ "tenant_data_moves": "deleted",+ "tenant_join_domains": "deleted",+ "tenant_usage": "deleted",+ "usage_budgets": "deleted",+ "workspace_service_settings": "deleted",+}++# What a blocking table is called in the refusal: (singular, plural).+REFUSED: dict[str, tuple[str, str]] = {+ "rooms": ("room", "rooms"),+ "agents": ("agent", "agents"),+ "packages": ("package", "packages"),+ "references": ("reference", "references"),+ "reference_types": ("reference type", "reference types"),+ "documents": ("document", "documents"),+ "templates": ("template", "templates"),+ "room_groups": ("room group", "room groups"),+ "messaging_installs": ("messaging app connection", "messaging app connections"),+ "collaboration_bridges": ("messaging bridge", "messaging bridges"),+ "machine_workspaces": ("cloud machine", "cloud machines"),+ "agent_controllers": ("machine", "machines"),+ "server_connectors": ("server connector", "server connectors"),+ "skills": ("skill", "skills"),+ "service_connections": ("service connection", "service connections"),+}+++# Rows of a refused table that are kept only as the record of something that+# has ended, and so neither block the deletion nor survive it. Every other row+# of the table still blocks.+TERMINAL: dict[str, Callable[[Table], ColumnElement[bool]]] = {+ # A machine removed in Switch Console keeps its row, revoked.+ "agent_controllers": lambda table: table.c.revoked_at.is_not(None),+ # A disconnected or revoked app keeps its row, with no token.+ "messaging_installs": lambda table: table.c.status != INSTALL_ACTIVE,+ # A cloud machine's row outlives its teardown, as `deleted`.+ "machine_workspaces": lambda table: table.c.machine_id.in_(+ select(CloudMachine.id).where(CloudMachine.state == "deleted")+ ),+}+++class WorkspaceDeletionRefused(Exception):+ """The workspace still holds something; the message lists what."""+++def _table(name: str) -> Table:+ table = Base.metadata.tables[name]+ assert isinstance(table, Table)+ return table+++def _counted(count: int, names: tuple[str, str]) -> str:+ return f"{count} {names[0] if count == 1 else names[1]}"+++async def remaining(session: AsyncSession, tenant_id: str, owner_id: str) -> list[str]:+ """What still has to go before the workspace can be deleted, by kind and+ count, in words; empty when nothing does. `session` is bound to it."""+ left: list[str] = []+ for name, names in REFUSED.items():+ table = _table(name)+ counted = select(func.count()).select_from(table)+ counted = counted.where(table.c.tenant_id == tenant_id)+ if name in TERMINAL:+ counted = counted.where(~TERMINAL[name](table))+ count = await session.scalar(counted)+ if not count:+ continue+ entry = _counted(count, names)+ if name == "rooms":+ archived = await session.scalar(+ select(func.count())+ .select_from(Room)+ .where(Room.tenant_id == tenant_id, Room.archived_at.is_not(None))+ )+ if archived:+ entry += f" ({archived} archived)"+ left.append(entry)+ # A token issued to an agent is revoked at its vendor from this row, after+ # the access it came from is gone; deleting the row first would leave it+ # live there until it expires.+ revocable = await session.scalar(+ select(func.count())+ .select_from(ServiceTokenIssuance)+ .where(+ ServiceTokenIssuance.tenant_id == tenant_id,+ ServiceTokenIssuance.encrypted_token.is_not(None),+ ServiceTokenIssuance.expires_at > func.now(),+ )+ )+ if revocable:+ left.append(+ _counted(+ revocable,+ (+ "service token still to be revoked (try again shortly)",+ "service tokens still to be revoked (try again shortly)",+ ),+ )+ )+ members = _table("tenant_members")+ others = await session.scalar(+ select(func.count())+ .select_from(members)+ .where(members.c.tenant_id == tenant_id, members.c.user_id != owner_id)+ )+ if others:+ left.append(_counted(others, ("other member", "other members")))+ return left+++async def refusal(session: AsyncSession, tenant_id: str, owner_id: str) -> str | None:+ """Why the workspace cannot be deleted now, or None when it can."""+ if tenant_id == TENANT_ZERO_ID:+ return (+ "This is the server's default workspace, where new accounts start. "+ "It can't be deleted."+ )+ left = await remaining(session, tenant_id, owner_id)+ if left:+ return (+ "Empty the workspace before deleting it. Still in it: "+ + ", ".join(left)+ + "."+ )+ return None+++async def delete_workspace(+ session: AsyncSession, tenant_id: str, owner_id: str, actor_user_id: str | None+) -> list[str]:+ """Delete the workspace on `session`, which is bound to it; the caller+ commits. Raises `WorkspaceDeletionRefused`, having deleted nothing, unless+ it is empty. Records the deletion in the workspace's audit log and the+ server's, naming `actor_user_id`. Returns the hashes of the API keys+ deleted with it, for the caller to drop from its cache once this has+ committed."""+ tenant = await session.scalar(+ select(Tenant).where(Tenant.id == tenant_id).with_for_update()+ )+ if tenant is None:+ raise WorkspaceDeletionRefused("That workspace doesn't exist.")+ reason = await refusal(session, tenant_id, owner_id)+ if reason is not None:+ raise WorkspaceDeletionRefused(reason)+ key_hashes = list(+ await session.scalars(+ select(ApiKey.key_hash).where(ApiKey.tenant_id == tenant_id)+ )+ )+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=actor_user_id,+ action=AuditAction.TENANT_DELETED,+ target_type="tenant",+ target_id=tenant_id,+ details={"slug": tenant.slug},+ )+ await record_server_audit_event(+ session,+ actor_user_id=actor_user_id,+ action=ServerAuditAction.WORKSPACE_DELETED,+ target_type="tenant",+ target_id=tenant_id,+ details={"slug": tenant.slug},+ )+ # Children before parents, so no foreign key between two of these tables+ # holds a delete back.+ for table in reversed(Base.metadata.sorted_tables):+ if table.name in TERMINAL:+ # The refusal found only ended rows; a live one fails the+ # `tenants` delete below on its foreign key.+ await session.execute(+ delete(table).where(+ table.c.tenant_id == tenant_id, TERMINAL[table.name](table)+ )+ )+ continue+ if WORKSPACE_TABLES.get(table.name) != "deleted" or table.name == "tenants":+ continue+ await session.execute(delete(table).where(table.c.tenant_id == tenant_id))+ await session.execute(delete(Tenant).where(Tenant.id == tenant_id))+ await session.flush()+ return key_hashesdiff --git a/core/switch_core/clients/client_lifecycle_service.py b/core/switch_core/clients/client_lifecycle_service.pyindex 245e91cac..4c78d67e1 100644--- a/core/switch_core/clients/client_lifecycle_service.py+++ b/core/switch_core/clients/client_lifecycle_service.py@@ -364,8 +364,12 @@ class ClientLifecycleService:self._agent_seen(record.id, agent.id)async def reconcile_all(self) -> None:- """`reconcile_tenant` for every tenant."""- for tenant_id in await all_tenant_ids(self._session_factory):+ """`reconcile_tenant` for every tenant, and for every tenant a client+ runs here for: a workspace deleted elsewhere has no row left to list,+ and its clients here stop on the re-read finding none of theirs."""+ tenant_ids = set(await all_tenant_ids(self._session_factory))+ tenant_ids |= set(self._client_tenants.values())+ for tenant_id in sorted(tenant_ids):await self.reconcile_tenant(tenant_id)async def recheck_all(self) -> None:diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex d99660ba4..5f9de0ff0 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -28,6 +28,7 @@ from switch_core.db.models import (class AuditAction(StrEnum):TENANT_CREATED = "tenant.created"+ TENANT_DELETED = "tenant.deleted"INVITATION_CREATED = "invitation.created"INVITATION_REVOKED = "invitation.revoked"INVITATION_ACCEPTED = "invitation.accepted"@@ -117,6 +118,7 @@ class ServerAuditAction(StrEnum):USER_DELETED = "user.deleted"USER_DELETION_REFUSED = "user.deletion_refused"USER_DELETION_FAILED = "user.deletion_failed"+ WORKSPACE_DELETED = "workspace.deleted"# 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/db/models.py b/core/switch_core/db/models.pyindex f8e828a09..e017b32ba 100644--- a/core/switch_core/db/models.py+++ b/core/switch_core/db/models.py@@ -175,9 +175,10 @@ class OrganizationMember(Base):class Tenant(Base):"""The top-level customer boundary every scoped table hangs off.- Deliberately minimal: no `plan`, `status` or `deleted_at`. A later phase- adds plans and deletion; a `deleted_at` that nothing honours yet would- read as a guarantee the code does not make.+ Deliberately minimal: no `plan`, `status` or `deleted_at`. Deleting a+ workspace deletes this row (`accounts/workspace_deletion.py`); a+ `deleted_at` that nothing honours would read as a guarantee the code does+ not make."""__tablename__ = "tenants"@@ -691,7 +692,7 @@ class TenantJoinDomain(TenantScoped, Base):)-class AuditEvent(TenantScoped, Base):+class AuditEvent(Base):"""One security-relevant change in a tenant: who did what, to what, when.Written in the same transaction as the change it records wherever that@@ -713,6 +714,11 @@ class AuditEvent(TenantScoped, Base):`occurred_at` defaults to `clock_timestamp()`, not `now()`: two events inone transaction would otherwise share a timestamp, and the read pages backby it.++ `tenant_id` carries no foreign key either, for the same reason: deleting a+ workspace leaves its history behind, readable by no member since none is+ left, and the runtime role could not delete it anyway. It is still scoped+ by the policy (`rls_ddl.HISTORY_TABLES`)."""__tablename__ = "audit_events"@@ -720,6 +726,9 @@ class AuditEvent(TenantScoped, Base):Index("ix_audit_events_tenant_occurred_at", "tenant_id", "occurred_at"),)+ tenant_id: Mapped[str] = mapped_column(+ Text, nullable=False, default=require_tenant_id+ )id: Mapped[str] = mapped_column(Text, primary_key=True, default=_uuid)occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.clock_timestamp(), nullable=Falsediff --git a/core/switch_core/db/rls_ddl.py b/core/switch_core/db/rls_ddl.pyindex b2f551470..ea5bffa7a 100644--- a/core/switch_core/db/rls_ddl.py+++ b/core/switch_core/db/rls_ddl.py@@ -205,6 +205,14 @@ GLOBAL_TABLES = frozenset()+# Scoped tables whose `tenant_id` deliberately carries no foreign key, so their+# rows outlive the tenant: a workspace's audit history stays after the+# workspace is deleted, as it stays after an account is. The policy compares+# `tenant_id` the same as everywhere else; only the constraint is missing, and+# `tests/switch_core/db/test_tenant_schema_catalogue.py` pins this list too.+HISTORY_TABLES = frozenset({"audit_events"})++class UnscopedTableError(RuntimeError):"""A table is neither tenant-scoped nor named in `GLOBAL_TABLES`.@@ -318,13 +326,16 @@ def _tenant_column(table: Table) -> str | None:`tenants` is the one table compared on `id`, because a tenant *is* theboundary rather than belonging to one. Every other table qualifies by- carrying a `tenant_id` column whose foreign key targets `tenants.id`.+ carrying a `tenant_id` column whose foreign key targets `tenants.id`, or,+ for one of `HISTORY_TABLES`, a `tenant_id` column alone."""if table.name == "tenants":return "id"tenant_id_col = table.columns.get("tenant_id")if tenant_id_col is None:return None+ if table.name in HISTORY_TABLES:+ return "tenant_id"if any(fk.column.table.name == "tenants" and fk.column.name == "id"for fk in tenant_id_col.foreign_keysdiff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex ef04a2c3f..c6a612f61 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -494,6 +494,7 @@ async def delete_my_account(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_service: Annotated[RoomService, Depends(get_room_service)],broker: Annotated[ServiceBroker, Depends(get_service_broker)],+ client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],config: Annotated[SwitchConfig, Depends(get_config)],) -> dict[str, bool]:"""Delete the caller's own account, everywhere on this server.@@ -524,6 +525,7 @@ async def delete_my_account(agent_store,api_key_store,template_store,+ client_lifecycle,config,)workspaces = await _workspaces_to_delete(@@ -552,6 +554,7 @@ def _account_deletion(agent_store: AgentStore,api_key_store: ApiKeyStore,template_store: TemplateStore,+ client_lifecycle: ClientLifecycleService,config: SwitchConfig,) -> AccountDeletion:return AccountDeletion(@@ -568,6 +571,7 @@ def _account_deletion(agents=agent_store,api_keys=api_key_store,templates=template_store,+ clients=client_lifecycle,admin_email=config.gateway_admin_email,)@@ -709,6 +713,7 @@ async def delete_user(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_service: Annotated[RoomService, Depends(get_room_service)],broker: Annotated[ServiceBroker, Depends(get_service_broker)],+ client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],config: Annotated[SwitchConfig, Depends(get_config)],) -> dict[str, bool]:"""The deployment operator deletes someone's whole account.@@ -747,6 +752,7 @@ async def delete_user(agent_store,api_key_store,template_store,+ client_lifecycle,config,)workspaces = await _workspaces_to_delete(diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 60f338e1d..2d2397127 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -1126,6 +1126,11 @@ class WorkspaceCreateRequest(BaseModel):name: str+class TenantDeleteRequest(BaseModel):+ # The workspace's name, typed by the person deleting it.+ name: str++class SessionStateUser(BaseModel):id: strname: strdiff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 36dbab64b..bf3bff72d 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -10,6 +10,10 @@ from fastapi.responses import JSONResponsefrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.accounts.workspace_deletion import (+ WorkspaceDeletionRefused,+ delete_workspace,+)from switch_core.authz import (ORGANIZATION_ADMIN_ROLE,ORGANIZATION_ADMIN_TENANT_ROLE,@@ -18,14 +22,20 @@ from switch_core.authz import ()from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.registration_bootstrap import is_bootstrap_owner-from switch_core.clients.client_lifecycle_service import ClientLifecycleService+from switch_core.clients.client_lifecycle_service import (+ ClientLifecycleService,+)from switch_core.config import SwitchConfigfrom switch_core.connections.broker import (ServiceBroker,ServiceError,get_service_broker,)-from switch_core.db.audit import AuditAction, list_audit_events, record_audit_event+from switch_core.db.audit import (+ AuditAction,+ list_audit_events,+ record_audit_event,+)from switch_core.db.models import (Invitation,Organization,@@ -62,6 +72,7 @@ from switch_core.gateway.auth import (get_authenticated_caller,get_authenticated_user_id,get_current_user,+ initial_tenant_claim,list_tenant_memberships,may_bind_tenant,record_operator_entry,@@ -119,6 +130,7 @@ from switch_core.gateway.schemas import (OperatorWorkspaceResponse,SessionUserResponse,TenantCreateRequest,+ TenantDeleteRequest,TenantMembershipResponse,UsageTotalResponse,)@@ -356,6 +368,70 @@ async def create_tenant(return created.workspace[email protected]("/tenants/{tenant_id}")+async def delete_tenant(+ tenant_id: str,+ req: TenantDeleteRequest,+ response: Response,+ session: Annotated[AsyncSession, Depends(get_session)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+ user_store: Annotated[UserStore, Depends(get_user_store)],+ user: Annotated[User, Depends(get_current_user)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],+ client_lifecycle: Annotated[ClientLifecycleService, Depends(get_client_lifecycle)],+ config: Annotated[SwitchConfig, Depends(get_config)],+) -> dict[str, bool]:+ """Delete the bound workspace, once it has been emptied.++ Its admins only, by their own admin membership: not the deployment+ operator's bypass, and not an organization admin acting as one, since+ deleting a workspace is the one act that cannot be undone by anyone. The+ caller confirms by typing its name.+ A workspace that still holds anything is refused, 409, with what is left+ by kind and count (`accounts/workspace_deletion.py`). The session cookie+ is re-minted without it, onto the caller's only other workspace if there+ is exactly one.+ """+ _require_bound_tenant(tenant_id)+ if await user_store.tenant_role(session, tenant_id, user.id) != "admin":+ raise HTTPException(+ status_code=403, detail="Only a workspace admin may delete the workspace"+ )+ tenant = await session.get(Tenant, tenant_id)+ if tenant is None:+ # Deleted by a request that got here first.+ raise HTTPException(status_code=404, detail="That workspace doesn't exist.")+ if req.name.strip() != tenant.name:+ raise HTTPException(+ status_code=400, detail="That name doesn't match this workspace."+ )+ try:+ key_hashes = await delete_workspace(session, tenant_id, user.id, user.id)+ except WorkspaceDeletionRefused as refused:+ await session.rollback()+ raise HTTPException(status_code=409, detail=str(refused)) from None+ await session.commit()+ logger.info("Admin %s deleted workspace %s", user.id, tenant_id)++ for key_hash in key_hashes:+ protocol.api_key_cache.invalidate(key_hash)+ # The clients the server ran for it stop here, and everywhere else on the+ # announcement.+ await client_lifecycle.reconcile_tenant(tenant_id)+ client_lifecycle.announce(tenant_id)++ set_session_cookie(+ response,+ user,+ config.keyring,+ config.gateway_cookie_secure,+ await initial_tenant_claim(session_factory, user_store, user),+ )+ return {"ok": True}++@router.post("/tenants/{tenant_id}/switch")async def switch_tenant(tenant_id: str,diff --git a/core/switch_core/migrations/versions/a3d9f6c2b871_audit_events_outlive_their_tenant.py b/core/switch_core/migrations/versions/a3d9f6c2b871_audit_events_outlive_their_tenant.pynew file mode 100644index 000000000..4cd33e50d--- /dev/null+++ b/core/switch_core/migrations/versions/a3d9f6c2b871_audit_events_outlive_their_tenant.py@@ -0,0 +1,41 @@+"""audit events outlive their tenant: drop fk_audit_events_tenant++Deleting a workspace deletes its `tenants` row, and a foreign key from+`audit_events` would hold that back. The runtime role may not delete audit+events (`grant_runtime_role`), and the history is kept on purpose, as it is+kept after an account is deleted. So the key goes; the `tenant_isolation`+policy on the table is unchanged and still compares `tenant_id`+(`db/rls_ddl.py`, HISTORY_TABLES).++Marked `expand_only`: dropping the key only relaxes the schema, and no+release reads or relies on it, so an older pod keeps serving through a+rolling upgrade. The downgrade puts the key back `NOT VALID`, so it does not+fail on the history of a workspace deleted in between, and checks every new+row.++Revision ID: a3d9f6c2b871+Revises: a3c5e7f9b1d2+Create Date: 2026-10-21 00:00:00.000000++"""++from collections.abc import Sequence++from alembic import op++revision: str = "a3d9f6c2b871"+down_revision: str | Sequence[str] | None = "a3c5e7f9b1d2"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None+expand_only: bool = True+++def upgrade() -> None:+ op.drop_constraint("fk_audit_events_tenant", "audit_events", type_="foreignkey")+++def downgrade() -> None:+ op.execute(+ "ALTER TABLE audit_events ADD CONSTRAINT fk_audit_events_tenant "+ "FOREIGN KEY (tenant_id) REFERENCES tenants (id) NOT VALID"+ )diff --git a/core/tests/switch_core/accounts/test_account_deletion.py b/core/tests/switch_core/accounts/test_account_deletion.pyindex c875aa45e..35baeef09 100644--- a/core/tests/switch_core/accounts/test_account_deletion.py+++ b/core/tests/switch_core/accounts/test_account_deletion.py@@ -18,6 +18,7 @@ import pytestfrom sqlalchemy import delete, select, textfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.accounts import deletion as deletion_modulefrom switch_core.accounts.deletion import (USER_REFERENCES,AccountDeletion,@@ -39,6 +40,7 @@ from switch_core.db.models import (Reference,ReferenceType,Room,+ ServerAuditEvent,Template,Tenant,TenantMember,@@ -106,6 +108,17 @@ class _Rooms:self.archived.append(room_id)+class _Clients:+ def __init__(self) -> None:+ self.reconciled: list[str] = []++ async def reconcile_tenant(self, tenant_id: str) -> None:+ self.reconciled.append(tenant_id)++ def announce(self, tenant_id: str) -> None:+ pass++class _SignInFlows:async def discard_for_user(self, *_args: Any) -> None:pass@@ -136,6 +149,7 @@ def _deletion(agents=AgentStore(),api_keys=ApiKeyStore(),templates=TemplateStore(),+ clients=_Clients(),admin_email=ADMIN_EMAIL,)return deletion, protocol, rooms@@ -523,7 +537,7 @@ async def test_deleting_a_member_hands_over_and_clears_what_others_need() == "account.deleted"-async def test_a_workspace_left_empty_stays_with_nothing_pointing_at_the_person(+async def test_a_workspace_left_empty_is_deleted_with_its_setup(session_factory: async_sessionmaker[AsyncSession],) -> None:deletion, _, _ = _deletion(session_factory)@@ -546,11 +560,105 @@ async def test_a_workspace_left_empty_stays_with_nothing_pointing_at_the_person(assert await deletion.refusal(session, user, workspaces) is Noneawait deletion.delete(session, user, workspaces, actor_id=user.id)+ assert deletion.clients.reconciled == [solo] # type: ignore[attr-defined]async with session_factory() as session:assert await session.get(User, user_id) is None- assert await session.get(Tenant, solo) is not None+ assert await session.get(Tenant, solo) is Noneasync with tenant_session(session_factory, solo) as session:assert await session.scalar(select(Invitation.id)) is None+ actions = set(+ await session.scalars(+ select(AuditEvent.action).where(AuditEvent.tenant_id == solo)+ )+ )+ assert actions == {"account.deleted", "tenant.deleted"}+ async with session_factory() as session:+ server_event = await session.scalar(+ select(ServerAuditEvent).where(ServerAuditEvent.target_id == solo)+ )+ assert server_event is not None+ assert server_event.action == "workspace.deleted"+ assert server_event.actor_user_id == user_id+++async def test_a_workspace_that_gains_something_meanwhile_stays_and_the_account_goes(+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Something arrives between the check that the workspace is empty and its+ deletion. The person has already left it, committed, so the workspace is+ kept, empty, and the account's deletion still finishes."""+ deletion, _, _ = _deletion(session_factory)+ solo = f"solo-{uuid.uuid4().hex[:6]}"+ async with session_factory() as session:+ session.add(Tenant(id=solo, slug=solo, name="Solo"))+ await session.flush()+ alone = await _user(session, "alone")+ user_id = alone.id+ await session.commit()+ async with tenant_session(session_factory, solo) as session:+ await _member(session, solo, alone, "admin")+ session.add(+ Room(+ tenant_id=solo,+ transport_room_id=f"!{uuid.uuid4().hex}:test",+ name="arrived",+ description="",+ )+ )+ await session.commit()++ async def found_empty(*_args: Any) -> None:+ return None++ monkeypatch.setattr(deletion_module, "workspace_refusal", found_empty)+ workspaces = [Workspace(solo, "Solo", "admin")]+ async with session_factory() as session:+ user = await session.get(User, user_id)+ assert user is not None+ 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+ assert await session.get(Tenant, solo) is not None+++async def test_a_workspace_left_with_a_room_stays_empty(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """Rooms outlive the person who made them, so a workspace still holding+ one is left, with nobody in it, rather than deleted."""+ deletion, _, _ = _deletion(session_factory)+ solo = f"solo-{uuid.uuid4().hex[:6]}"+ async with session_factory() as session:+ session.add(Tenant(id=solo, slug=solo, name="Solo"))+ await session.flush()+ alone = await _user(session, "alone")+ user_id = alone.id+ await session.commit()+ async with tenant_session(session_factory, solo) as session:+ await _member(session, solo, alone, "admin")+ session.add(+ Room(+ tenant_id=solo,+ transport_room_id=f"!{uuid.uuid4().hex}:test",+ name="kept",+ description="",+ created_by=alone.id,+ owner_id=alone.id,+ )+ )+ await session.commit()++ workspaces = [Workspace(solo, "Solo", "admin")]+ async with session_factory() as session:+ user = await session.get(User, user_id)+ assert user is not None+ await deletion.delete(session, user, workspaces, actor_id=user.id)++ async with session_factory() as session:+ assert await session.get(Tenant, solo) is not None+ async with tenant_session(session_factory, solo) as session:assert await session.scalar(select(TenantMember.user_id)) is Nonediff --git a/core/tests/switch_core/accounts/test_workspace_deletion.py b/core/tests/switch_core/accounts/test_workspace_deletion.pynew file mode 100644index 000000000..126457bac--- /dev/null+++ b/core/tests/switch_core/accounts/test_workspace_deletion.py@@ -0,0 +1,356 @@+"""Deleting an emptied workspace, and the route its owner calls.++Against a real database where it matters: the refusals count rows, and the+deletion only works if every foreign key into `tenants` is gone first.+"""++from __future__ import annotations++import uuid+from datetime import UTC, datetime++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++import switch_core.db.models # noqa: F401+from switch_core.accounts.workspace_deletion import (+ REFUSED,+ WORKSPACE_TABLES,+ WorkspaceDeletionRefused,+ delete_workspace,+ refusal,+)+from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.base import Base+from switch_core.db.models import (+ TENANT_ZERO_ID,+ AgentController,+ ApiKey,+ AuditEvent,+ Invitation,+ MessagingInstall,+ Room,+ ServerAuditEvent,+ Tenant,+ TenantJoinDomain,+ TenantMember,+)+from switch_core.db.rls_ddl import HISTORY_TABLES, scoped_tables+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.user_store import UserStore+from tests.switch_core.accounts.test_account_deletion import (+ _agent,+ _invitation,+ _member,+ _user,+)+from tests.switch_core.gateway.test_tenant_api_routes import (+ _app,+ _client,+ _make_member,+ _make_tenant,+ _token,+)+from tests.switch_core.hosted_machine_helpers import seed_machine+++def test_every_scoped_table_says_what_deleting_a_workspace_does_with_it() -> None:+ assert set(WORKSPACE_TABLES) == set(scoped_tables(Base.metadata)), (+ "accounts/workspace_deletion.py must say what happens to every "+ "tenant-scoped table when a workspace is deleted"+ )+ assert {name for name, h in WORKSPACE_TABLES.items() if h == "refused"} == set(+ REFUSED+ )+ assert {name for name, h in WORKSPACE_TABLES.items() if h == "kept"} == set(+ HISTORY_TABLES+ )+++async def _workspace(+ session_factory: async_sessionmaker[AsyncSession],+) -> tuple[str, str]:+ """A workspace with only its owner in it."""+ tenant_id = f"ws-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name="Doomed"))+ await session.flush()+ owner = await _user(session, "owner")+ await _member(session, tenant_id, owner, "admin")+ await session.commit()+ return tenant_id, owner.id+++async def test_the_refusal_lists_what_is_left_by_kind_and_count(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant_id, owner_id = await _workspace(session_factory)+ async with tenant_session(session_factory, tenant_id) as session:+ owner = await session.get(switch_core.db.models.User, owner_id)+ assert owner is not None+ for name, archived in (("live", None), ("old", datetime.now(UTC))):+ session.add(+ Room(+ tenant_id=tenant_id,+ transport_room_id=f"!{uuid.uuid4().hex}:test",+ name=name,+ description="",+ archived_at=archived,+ )+ )+ await _agent(session, tenant_id, owner, "helper")+ other = await _user(session, "other")+ await _member(session, tenant_id, other, "member")+ await session.commit()++ reason = await refusal(session, tenant_id, owner_id)+ assert reason is not None+ assert "2 rooms (1 archived)" in reason+ assert "1 agent" in reason+ assert "1 other member" in reason+++async def test_the_default_workspace_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:+ reason = await refusal(session, TENANT_ZERO_ID, "anyone")+ assert reason is not None and "default workspace" in reason+++async def test_an_emptied_workspace_goes_and_its_history_stays(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant_id, owner_id = await _workspace(session_factory)+ async with tenant_session(session_factory, tenant_id) as session:+ owner = await session.get(switch_core.db.models.User, owner_id)+ assert owner is not None+ await _invitation(session, tenant_id, owner)+ session.add(+ TenantJoinDomain(+ tenant_id=tenant_id, domain="example.test", created_by=owner_id+ )+ )+ key = ApiKey(+ tenant_id=tenant_id,+ user_id=owner_id,+ key_hash=uuid.uuid4().hex,+ encrypted_key="enc",+ label="mine",+ type="registration",+ )+ session.add(key)+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=owner_id,+ action=AuditAction.API_KEY_CREATED,+ target_type="api_key",+ target_id=key.id,+ details=None,+ )+ await session.commit()++ hashes = await delete_workspace(session, tenant_id, owner_id, owner_id)+ await session.commit()++ assert hashes == [key.key_hash]+ async with session_factory() as session:+ assert await session.get(Tenant, tenant_id) is None+ async with tenant_session(session_factory, tenant_id) as session:+ assert await session.scalar(select(Invitation.id)) is None+ assert await session.scalar(select(TenantJoinDomain.domain)) is None+ assert await session.scalar(select(TenantMember.user_id)) is None+ actions = list(+ await session.scalars(+ select(AuditEvent.action)+ .where(AuditEvent.tenant_id == tenant_id)+ .order_by(AuditEvent.occurred_at)+ )+ )+ assert sorted(actions) == ["api_key.created", "tenant.deleted"]+++async def test_a_workspace_with_something_left_is_not_touched(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant_id, owner_id = await _workspace(session_factory)+ async with tenant_session(session_factory, tenant_id) as session:+ session.add(+ Room(+ tenant_id=tenant_id,+ transport_room_id=f"!{uuid.uuid4().hex}:test",+ name="kept",+ description="",+ )+ )+ await session.commit()+ with pytest.raises(WorkspaceDeletionRefused):+ await delete_workspace(session, tenant_id, owner_id, owner_id)+ await session.rollback()+ async with session_factory() as session:+ assert await session.get(Tenant, tenant_id) is not None+++async def _ended_and_live(+ session: AsyncSession, tenant_id: str, owner_id: str, *, live: bool+) -> None:+ """A removed machine, a disconnected messaging app and a cloud machine+ since torn down; with `live`, one of each still in use as well."""+ now = datetime.now(UTC)+ for ended in (True, False) if live else (True,):+ session.add(+ AgentController(+ tenant_id=tenant_id,+ owner_id=owner_id,+ name="laptop",+ kind="console",+ revoked_at=now if ended else None,+ )+ )+ session.add(+ MessagingInstall(+ tenant_id=tenant_id,+ platform="slack",+ external_workspace_id=f"T-{uuid.uuid4().hex[:6]}",+ scopes="chat:write",+ status="disconnected" if ended else "active",+ installed_by_user_id=owner_id,+ )+ )+ await seed_machine(+ session,+ owner_id=owner_id,+ state="deleted" if ended else "ready",+ desired_state="deleted" if ended else "running",+ stop_reason=None,+ revision=1,+ )+ await session.commit()+++async def test_records_of_what_has_ended_neither_block_nor_survive(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant_id, owner_id = await _workspace(session_factory)+ async with tenant_session(session_factory, tenant_id) as session:+ await _ended_and_live(session, tenant_id, owner_id, live=False)++ assert await refusal(session, tenant_id, owner_id) is None+ await delete_workspace(session, tenant_id, owner_id, owner_id)+ await session.commit()++ async with session_factory() as session:+ assert await session.get(Tenant, tenant_id) is None+ async with tenant_session(session_factory, tenant_id) as session:+ assert await session.scalar(select(AgentController.id)) is None+ assert await session.scalar(select(MessagingInstall.id)) is None+++async def test_what_is_still_in_use_blocks_beside_what_has_ended(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ tenant_id, owner_id = await _workspace(session_factory)+ async with tenant_session(session_factory, tenant_id) as session:+ await _ended_and_live(session, tenant_id, owner_id, live=True)+ reason = await refusal(session, tenant_id, owner_id)+ assert reason is not None+ assert "1 machine" in reason+ assert "1 messaging app connection" in reason+ assert "1 cloud machine" in reason+++async def test_a_workspace_deleted_meanwhile_is_not_found(+ session_factory: async_sessionmaker[AsyncSession],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A second request for the same deletion, which the first finished while+ this one was being authorized."""+ token = await _route_people(session_factory, "admin")+ tenant_role = UserStore.tenant_role++ async def deleted_meanwhile(+ store: UserStore, session: AsyncSession, tenant_id: str, user_id: str+ ) -> str | None:+ role = await tenant_role(store, session, tenant_id, user_id)+ async with tenant_session(session_factory, tenant_id) as other:+ await delete_workspace(other, tenant_id, user_id, user_id)+ await other.commit()+ return role++ monkeypatch.setattr(UserStore, "tenant_role", deleted_meanwhile)+ async with _client(_app(session_factory, client_lifecycle=_Clients()), token) as c:+ response = await c.request(+ "DELETE", f"/tenants/{TENANT}", json={"name": TENANT}+ )+ assert response.status_code == 404, response.text+++class _Clients:+ def __init__(self) -> None:+ self.reconciled: list[str] = []++ async def reconcile_tenant(self, tenant_id: str) -> None:+ self.reconciled.append(tenant_id)++ def announce(self, tenant_id: str) -> None:+ pass+++TENANT = "workspace-deletion-route"+++async def _route_people(+ session_factory: async_sessionmaker[AsyncSession], role: str+) -> str:+ await _make_tenant(session_factory, TENANT)+ user_id = await _make_member(+ session_factory, name=f"ws-{role}", tenant_id=TENANT, role=role+ )+ return _token(user_id, f"ws-{role}@example.invalid", TENANT)+++async def test_an_admin_deletes_an_empty_workspace_by_typing_its_name(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ token = await _route_people(session_factory, "admin")+ clients = _Clients()+ async with _client(_app(session_factory, client_lifecycle=clients), token) as c:+ wrong = await c.request("DELETE", f"/tenants/{TENANT}", json={"name": "nope"})+ done = await c.request("DELETE", f"/tenants/{TENANT}", json={"name": TENANT})+ assert wrong.status_code == 400, wrong.text+ assert done.status_code == 200, done.text+ assert clients.reconciled == [TENANT]+ async with session_factory() as session:+ assert await session.get(Tenant, TENANT) is None+ event = await session.scalar(+ select(ServerAuditEvent).where(ServerAuditEvent.target_id == TENANT)+ )+ assert event is not None and event.action == "workspace.deleted"+++async def test_a_member_who_is_not_an_admin_is_refused(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ token = await _route_people(session_factory, "member")+ async with _client(_app(session_factory, client_lifecycle=_Clients()), token) as c:+ response = await c.request(+ "DELETE", f"/tenants/{TENANT}", json={"name": TENANT}+ )+ assert response.status_code == 403, response.text+ async with session_factory() as session:+ assert await session.get(Tenant, TENANT) is not None+++async def test_a_workspace_with_others_in_it_is_refused_with_what_is_left(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ token = await _route_people(session_factory, "admin")+ await _make_member(session_factory, name="stays", tenant_id=TENANT, role="member")+ async with _client(_app(session_factory, client_lifecycle=_Clients()), token) as c:+ response = await c.request(+ "DELETE", f"/tenants/{TENANT}", json={"name": TENANT}+ )+ assert response.status_code == 409, response.text+ assert "1 other member" in response.json()["detail"]diff --git a/core/tests/switch_core/clients/test_client_signals.py b/core/tests/switch_core/clients/test_client_signals.pyindex 3dfca8cd8..e79dda57d 100644--- a/core/tests/switch_core/clients/test_client_signals.py+++ b/core/tests/switch_core/clients/test_client_signals.py@@ -22,7 +22,8 @@ from sqlalchemy.pool import NullPoolfrom switch_core.chats import MEMBER_CLIENT_TYPEfrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.clients.client_signals import CLIENT_CHANGED_SIGNAL, ClientSignals-from switch_core.db.models import TENANT_ZERO_ID, Agent, Client+from switch_core.db.models import TENANT_ZERO_ID, Agent, ApiKey, Client, Tenant+from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.client_store import ClientStorefrom switch_core.db.stores.tenant_store import TenantStorefrom switch_core.signals import SignalBus@@ -433,3 +434,40 @@ def _count_full_reads(lifecycle: ClientLifecycleService) -> list[str]:store.get_running = counted # type: ignore[method-assign]return reads+++async def test_a_workspace_deleted_unannounced_stops_its_clients_on_the_recheck(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """The signal that would have stopped them was missed, and the workspace+ has no row left for the re-check to list: the clients running here for it+ are what name it."""+ lifecycle = _lifecycle(session_factory)+ gone = f"gone-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(Tenant(id=gone, slug=gone, name=gone))+ await session.commit()+ async with tenant_session(session_factory, gone) as session:+ agent = await _make_agent(session, f"doomed-{uuid.uuid4().hex[:8]}")+ await session.commit()+ client_id = agent.client_id+ assert client_id is not None+ await lifecycle.reconcile_tenant(gone)+ copy = lifecycle.get(client_id)+ assert copy is not None++ async with tenant_session(session_factory, gone) as session:+ await session.execute(delete(Agent).where(Agent.id == agent.id))+ await session.execute(delete(Client).where(Client.id == client_id))+ await session.execute(delete(ApiKey).where(ApiKey.tenant_id == gone))+ await session.commit()+ async with session_factory() as session:+ await session.execute(delete(Tenant).where(Tenant.id == gone))+ await session.commit()++ await lifecycle.reconcile_all()+ try:+ assert lifecycle.get(client_id) is None+ assert isinstance(copy, _Consumer) and copy.stopped+ finally:+ await lifecycle.stop_all()diff --git a/core/tests/switch_core/db/test_tenant_schema_catalogue.py b/core/tests/switch_core/db/test_tenant_schema_catalogue.pyindex 0bc8a0a98..fb8e897d3 100644--- a/core/tests/switch_core/db/test_tenant_schema_catalogue.py+++ b/core/tests/switch_core/db/test_tenant_schema_catalogue.py@@ -33,6 +33,7 @@ import switch_core.db.models # noqa: F401from switch_core.db.base import Basefrom switch_core.db.rls_ddl import (GLOBAL_TABLES,+ HISTORY_TABLES,organization_scoped_tables,scoped_tables,unscoped_tables,@@ -143,6 +144,13 @@ class TestEveryTableIsScopedUnlessItIsNamedGlobal:"server_audit_events",}+ async def test_the_history_tables_are_exactly_these(self) -> None:+ """Scoped, but with no foreign key to `tenants`, so their rows outlive+ a deleted workspace. Pinned for the same reason as the list above."""+ assert set(HISTORY_TABLES) == {"audit_events"}+ assert scoped_tables(Base.metadata)["audit_events"] == "tenant_id"+ assert not Base.metadata.tables["audit_events"].c.tenant_id.foreign_keys+async def test_scoped_is_everything_else(self) -> None:scoped = _scoped_tables()organization_scoped = set(organization_scoped_tables(Base.metadata))diff --git a/core/tests/switch_core/gateway/test_admin_delete_user.py b/core/tests/switch_core/gateway/test_admin_delete_user.pyindex ea0c2a16b..18dfa7ee0 100644--- a/core/tests/switch_core/gateway/test_admin_delete_user.py+++ b/core/tests/switch_core/gateway/test_admin_delete_user.py@@ -70,6 +70,7 @@ def _app(overrides[gw_deps.get_resource_service] = lambda: deletion.resourcesoverrides[gw_deps.get_room_service] = lambda: deletion.roomsoverrides[get_service_broker] = lambda: deletion.broker+ overrides[gw_deps.get_client_lifecycle] = lambda: deletion.clientsoverrides[gw_deps.get_config] = lambda: SimpleNamespace(keyring=TEST_KEYRING,gateway_cookie_secure=False,diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex 251ef6748..c52ea6c7e 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1216,6 +1216,12 @@ export async function fetchMembers(tenantId: string): Promise<Member[]> {return jsonRequest<Member[]>(`/tenants/${encodeURIComponent(tenantId)}/members`, "GET");}+// Owner only, and only once the workspace is empty: the server refuses+// otherwise, listing what is left.+export async function deleteWorkspace(tenantId: string, name: string): Promise<void> {+ await jsonRequest(`/tenants/${encodeURIComponent(tenantId)}`, "DELETE", { name });+}+export type OwnershipKind =| "agent"| "room"diff --git a/gateway/src/pages/workspace/DeleteWorkspaceSection.tsx b/gateway/src/pages/workspace/DeleteWorkspaceSection.tsxnew file mode 100644index 000000000..967930c8d--- /dev/null+++ b/gateway/src/pages/workspace/DeleteWorkspaceSection.tsx@@ -0,0 +1,108 @@+import DeleteOutline from "@mui/icons-material/DeleteOutline";+import {+ Alert,+ Button,+ CircularProgress,+ Dialog,+ DialogActions,+ DialogContent,+ DialogContentText,+ DialogTitle,+ Stack,+ TextField,+ Typography,+} from "@mui/material";+import { useState } from "react";+import { useNavigate } from "react-router";+import { useAuth } from "../../data/AuthContext";+import { deleteWorkspace } from "../../data/api";++interface Props {+ tenantId: string;+ tenantName: string;+}++/** An admin deletes the workspace by typing its name. The server refuses+ * one that still holds anything, and its message lists what. */+export default function DeleteWorkspaceSection({ tenantId, tenantName }: Props) {+ const [open, setOpen] = useState(false);+ const [typed, setTyped] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const { refresh } = useAuth();+ const navigate = useNavigate();++ const close = () => {+ if (submitting) return;+ setOpen(false);+ setTyped("");+ setError(null);+ };++ const submit = async () => {+ setSubmitting(true);+ setError(null);+ try {+ await deleteWorkspace(tenantId, typed);+ await refresh();+ navigate("/");+ } catch (e) {+ setError(e instanceof Error ? e.message : "Failed to delete the workspace");+ setSubmitting(false);+ }+ };++ return (+ <Stack spacing={1}>+ <Typography variant="overline" sx={{ color: "error.main", display: "block" }}>+ Danger zone+ </Typography>+ <Button+ variant="outlined"+ color="error"+ startIcon={<DeleteOutline />}+ onClick={() => setOpen(true)}+ sx={{ alignSelf: "flex-start" }}+ >+ Delete workspace+ </Button>+ <Dialog open={open} onClose={close} fullWidth maxWidth="xs">+ <DialogTitle>Delete workspace</DialogTitle>+ <DialogContent>+ <DialogContentText sx={{ mb: 2 }}>+ This deletes <b>{tenantName}</b> for good. Only an empty workspace can be+ deleted: remove its rooms, agents, resources, machines, connections and+ other members first. Type the workspace name to confirm.+ </DialogContentText>+ <TextField+ fullWidth+ size="small"+ label="Workspace name"+ value={typed}+ onChange={(e) => setTyped(e.target.value)}+ disabled={submitting}+ />+ {error && (+ <Alert severity="error" sx={{ mt: 2 }}>+ {error}+ </Alert>+ )}+ </DialogContent>+ <DialogActions>+ <Button onClick={close} disabled={submitting}>+ Cancel+ </Button>+ <Button+ color="error"+ variant="contained"+ onClick={submit}+ disabled={submitting || typed.trim() !== tenantName}+ startIcon={submitting ? <CircularProgress size={16} /> : undefined}+ >+ Delete workspace+ </Button>+ </DialogActions>+ </Dialog>+ </Stack>+ );+}diff --git a/gateway/src/pages/workspace/WorkspacePage.tsx b/gateway/src/pages/workspace/WorkspacePage.tsxindex 3f8676839..adb82f880 100644--- a/gateway/src/pages/workspace/WorkspacePage.tsx+++ b/gateway/src/pages/workspace/WorkspacePage.tsx@@ -1,5 +1,6 @@import { Alert, Box, CircularProgress, Stack, Typography } from "@mui/material";import { useAuth } from "../../data/AuthContext";+import DeleteWorkspaceSection from "./DeleteWorkspaceSection";import InvitationsSection from "./InvitationsSection";import MembersSection from "./MembersSection";@@ -33,6 +34,10 @@ export default function WorkspacePage() {Ask a workspace admin to invite someone.</Alert>)}+ {/* An admin membership, not the operator's bypass: the server checks the same. */}+ {tenant.role === "admin" && (+ <DeleteWorkspaceSection tenantId={tenant.id} tenantName={tenant.name} />+ )}</Stack></Box>);