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
Take away what an org_admin holds where they stand only as one, and keep the last org_admin under concurrent requests
Petr Bauchc850b74ce2e7
diff --git a/core/switch_core/accounts/deletion.py b/core/switch_core/accounts/deletion.pyindex 20db3fc2c..9a1b80c27 100644--- a/core/switch_core/accounts/deletion.py+++ b/core/switch_core/accounts/deletion.py@@ -31,6 +31,7 @@ a user cannot be added without saying what happens to it here.from __future__ import annotationsimport logging+from contextlib import AsyncExitStackfrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Literal, Protocol@@ -70,7 +71,7 @@ from switch_core.db.models import (User,WorkspaceServiceSetting,)-from switch_core.db.session_scope import tenant_session+from switch_core.db.session_scope import organization_session, tenant_sessionfrom switch_core.tenant_context import tenant_scopeif TYPE_CHECKING:@@ -82,6 +83,7 @@ if TYPE_CHECKING:from switch_core.connections.sign_in_flows import SignInFlowsfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStore+ from switch_core.db.stores.organization_store import OrganizationStorefrom switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.room_service import RoomService@@ -172,6 +174,7 @@ class AccountDeletion:rooms: RoomServicesign_in_flows: SignInFlowsusers: UserStore+ organizations: OrganizationStoreagents: AgentStoreapi_keys: ApiKeyStoretemplates: TemplateStore@@ -269,8 +272,11 @@ class AccountDeletion:) -> 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."""+ checked `refusal` first, and `AccountDeletionRefused` is raised before+ anything is changed if an organization's last `org_admin` check no+ longer holds."""user_id = user.id+ await 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)@@ -286,6 +292,66 @@ class AccountDeletion: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]+ ) -> None:+ """Take the person's `org_admin` rows away, each under the lock every+ write that could leave an organization without an `org_admin` takes+ (`OrganizationStore.lock_admins`), so `refusal` holds against another+ admin stepping down at the same moment. Every check runs before any+ row goes."""+ organizations: dict[str, str] = {}+ for workspace in workspaces:+ async with tenant_session(self.session_factory, workspace.id) as session:+ tenant = await session.get(Tenant, workspace.id)+ if (+ tenant is not None+ and tenant.organization_id is not None+ and await self.users.organization_role(+ session, workspace.id, user.id+ )+ == ORGANIZATION_ADMIN_ROLE+ ):+ organizations[tenant.organization_id] = workspace.name+ if not organizations:+ return+ async with AsyncExitStack() as stack:+ held = []+ for organization_id in sorted(organizations):+ session = await stack.enter_async_context(+ organization_session(self.session_factory, organization_id)+ )+ held.append((organization_id, session))+ admins = await self.organizations.lock_admins(session, organization_id)+ still_admin = (+ await self.organizations.role(session, organization_id, user.id)+ == ORGANIZATION_ADMIN_ROLE+ )+ others = await session.scalar(+ select(func.count())+ .select_from(OrganizationMember)+ .where(+ OrganizationMember.organization_id == organization_id,+ OrganizationMember.user_id != user.id,+ )+ )+ if still_admin and admins <= 1 and others:+ organization = await session.get(Organization, organization_id)+ assert organization is not None+ raise AccountDeletionRefused(+ f"You're the only organization admin of {organization.name}, "+ "which has other members. Make one of them an "+ "organization admin first."+ )+ for organization_id, session in held:+ await session.execute(+ delete(OrganizationMember).where(+ OrganizationMember.organization_id == organization_id,+ OrganizationMember.user_id == user.id,+ )+ )+ await session.commit()+async def _hand_over_server_settings(self, session: AsyncSession, user_id: str) -> None:diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex 346e561a5..81e721c40 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -34,6 +34,9 @@ class AuditAction(StrEnum):MEMBER_JOINED_BY_DOMAIN = "member.joined_by_domain"MEMBER_ROLE_CHANGED = "member.role_changed"MEMBER_REMOVED = "member.removed"+ # Someone in the workspace only as their organization's `org_admin` stopped+ # being one, and their keys and connections here were removed.+ ORGANIZATION_ADMIN_ACCESS_ENDED = "organization_admin.access_ended"# The platform operator acting in a workspace on the operator flag alone:# entering it, and every write while there.PLATFORM_ACCESS = "platform.access"diff --git a/core/switch_core/db/stores/api_key_store.py b/core/switch_core/db/stores/api_key_store.pyindex 8f59d7849..a7f10cc38 100644--- a/core/switch_core/db/stores/api_key_store.py+++ b/core/switch_core/db/stores/api_key_store.py@@ -1,7 +1,7 @@from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession-from switch_core.db.models import Agent, ApiKey+from switch_core.db.models import Agent, ApiKey, require_tenant_idclass ApiKeyStore:@@ -39,7 +39,12 @@ class ApiKeyStore:return row[0], row[1]async def get_by_user(self, session: AsyncSession, user_id: str) -> list[ApiKey]:- result = await session.execute(select(ApiKey).where(ApiKey.user_id == user_id))+ """`user_id`'s keys in the bound tenant."""+ result = await session.execute(+ select(ApiKey).where(+ ApiKey.tenant_id == require_tenant_id(), ApiKey.user_id == user_id+ )+ )return list(result.scalars().all())async def get_by_user_and_type(diff --git a/core/switch_core/db/stores/organization_store.py b/core/switch_core/db/stores/organization_store.pyindex fe7266cf4..8b6157cba 100644--- a/core/switch_core/db/stores/organization_store.py+++ b/core/switch_core/db/stores/organization_store.py@@ -89,3 +89,22 @@ class OrganizationStore:))).scalar_one()++ async def lock_admins(self, session: AsyncSession, organization_id: str) -> int:+ """Lock `organization_id`'s `org_admin` rows to the end of the caller's+ transaction, and count them.++ Every write that could leave the organization without an `org_admin`+ counts through this and writes in the same transaction. Two admins+ demoting each other at once then queue on the same rows, and the+ second counts after the first has committed.+ """+ rows = await session.execute(+ select(OrganizationMember.user_id)+ .where(+ OrganizationMember.organization_id == organization_id,+ OrganizationMember.role == "org_admin",+ )+ .with_for_update()+ )+ return len(rows.all())diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 987238ee3..cbf4a3379 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -389,6 +389,29 @@ async def workspaces_in_organization(return found+async def workspaces_reached_through_organization(+ session_factory: async_sessionmaker[AsyncSession],+ user_id: str,+ organization_id: str,+) -> list[Tenant]:+ """The workspaces of `organization_id` that `user_id` stands in only as+ its `org_admin`, holding no membership row there: what they lose on being+ demoted or removed. Each read on its own short session, as+ `workspaces_in_organization` does."""+ members_of = set(await tenants_of_user(session_factory, user_id))+ found: list[Tenant] = []+ for tenant_id in await tenants_administered_through_organization(+ session_factory, user_id+ ):+ if tenant_id in members_of:+ continue+ async with tenant_session(session_factory, tenant_id) as session:+ tenant = await session.get(Tenant, tenant_id)+ if tenant is not None and tenant.organization_id == organization_id:+ found.append(tenant)+ return found++async def organizations_bindable_by(session_factory: async_sessionmaker[AsyncSession],user_store: UserStore,diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.pyindex 5a7a542c9..7251786d4 100644--- a/core/switch_core/gateway/auth_routes.py+++ b/core/switch_core/gateway/auth_routes.py@@ -9,7 +9,11 @@ from sqlalchemy import textfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.accounts.deletion import AccountDeletion, Workspace+from switch_core.accounts.deletion import (+ AccountDeletion,+ AccountDeletionRefused,+ Workspace,+)from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.resource.service import ResourceServicefrom switch_core.clients.client_lifecycle_service import ClientLifecycleService@@ -25,6 +29,7 @@ from switch_core.db.stores.hosted_machine_store import (claim_conflict,owner_stopped,)+from switch_core.db.stores.organization_store import OrganizationStorefrom switch_core.db.stores.template_store import TemplateStorefrom switch_core.db.stores.user_store import UserStore, email_takenfrom switch_core.gateway.auth import (@@ -48,6 +53,7 @@ from switch_core.gateway.dependencies import (get_client_lifecycle,get_config,get_external_user_store,+ get_organization_store,get_protocol,get_resource_service,get_room_service,@@ -415,6 +421,7 @@ async def delete_my_account(],caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],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)],@@ -454,6 +461,7 @@ async def delete_my_account(rooms=room_service,sign_in_flows=request.app.state.sign_in_flows,users=user_store,+ organizations=organization_store,agents=agent_store,api_keys=api_key_store,templates=template_store,@@ -462,7 +470,10 @@ async def delete_my_account(reason = await deletion.refusal(session, user, workspaces)if reason is not None:raise HTTPException(status_code=409, detail=reason)- await deletion.delete(session, user, workspaces)+ try:+ await deletion.delete(session, user, workspaces)+ except AccountDeletionRefused as refused:+ raise HTTPException(status_code=409, detail=str(refused)) from Noneresponse.delete_cookie("switch_auth", path="/")return {"ok": True}diff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex 75fc26688..5c5d4c8a3 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -20,16 +20,26 @@ from __future__ import annotationsfrom datetime import datetimefrom typing import Annotated, NamedTuple-from fastapi import APIRouter, Depends, HTTPException, Query, Response+from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response+from fastapi.responses import JSONResponsefrom sqlalchemy import deletefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.authz import ORGANIZATION_ADMIN_ROLE+from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.clients.client_lifecycle_service import ClientLifecycleServicefrom switch_core.config import SwitchConfig+from switch_core.connections.broker import (+ ServiceBroker,+ ServiceError,+ get_service_broker,+)+from switch_core.connections.sign_in_flows import SignInFlowsfrom switch_core.db.audit import (+ AuditAction,OrganizationAuditAction,list_organization_audit_events,+ record_audit_event,record_organization_audit_event,)from switch_core.db.models import (@@ -39,6 +49,9 @@ from switch_core.db.models import (User,require_tenant_id,)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.organization_store import OrganizationStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import (@@ -49,11 +62,15 @@ from switch_core.gateway.auth import (organization_workspaces_bindable_by,organizations_bindable_by,workspaces_in_organization,+ workspaces_reached_through_organization,)from switch_core.gateway.dependencies import (+ get_agent_store,+ get_api_key_store,get_client_lifecycle,get_config,get_organization_store,+ get_protocol,get_session,get_session_factory,get_system_session,@@ -70,6 +87,11 @@ from switch_core.gateway.schemas import (TenantMembershipResponse,WorkspaceCreateRequest,)+from switch_core.gateway.service_connections import service_refusal+from switch_core.gateway.workspace_access import (+ finish_revocation,+ revoke_workspace_access,+)from switch_core.gateway.workspace_creation import (create_organization_for,create_workspace,@@ -79,13 +101,16 @@ from switch_core.gateway.workspace_creation import (router = APIRouter()-def _member_detail(user: User, member: OrganizationMember) -> OrganizationMemberDetail:+def _member_detail(+ user: User, member: OrganizationMember, warning: str | None+) -> OrganizationMemberDetail:return OrganizationMemberDetail(user_id=user.id,name=user.name,email=user.email,role=member.role,created_at=str(member.created_at),+ warning=warning,)@@ -373,23 +398,107 @@ async def list_organization_members()organization_id = access.organization_idmembers = await organization_store.list_members(session, organization_id)- return [_member_detail(member_user, member) for member_user, member in members]+ return [+ _member_detail(member_user, member, None) for member_user, member in members+ ][email protected]("/organizations/current/members/{user_id}")+async def _end_access_through_organization(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ user_id: str,+ organization_id: str,+ actor_id: str,+ reason: str,+ agent_store: AgentStore,+ api_key_store: ApiKeyStore,+ broker: ServiceBroker,+ protocol: AgentCore,+ sign_in_flows: SignInFlows,+) -> str | None:+ """Take away what `user_id` holds in the workspaces they stand in only as+ the organization's `org_admin`, before they stop being one.++ Refuses, 409 naming the workspaces, while they own agents in any of them,+ as removing a workspace member does. Otherwise removes their keys,+ service connections and sign-ins under way in each, one workspace at a+ time, each recorded in that workspace's audit log. Raises `ServiceError`+ when a connection is busy. Returns a warning naming what could not be+ revoked at a vendor, or None.+ """+ reached = await workspaces_reached_through_organization(+ session_factory, user_id, organization_id+ )+ with_agents = []+ for tenant in reached:+ async with tenant_session(session_factory, tenant.id) as session:+ if await agent_store.get_by_owner(session, user_id):+ with_agents.append(tenant.name)+ if with_agents:+ raise HTTPException(+ status_code=409,+ detail=(+ "They own agents in workspaces they're in only as an "+ "organization admin. Delete those agents first: "+ f"{', '.join(sorted(with_agents))}"+ ),+ )+ warnings = []+ for tenant in reached:+ async with tenant_session(session_factory, tenant.id) as session:+ revoked = await revoke_workspace_access(+ session,+ user_id,+ api_key_store=api_key_store,+ broker=broker,+ sign_in_flows=sign_in_flows,+ )+ await record_audit_event(+ session,+ tenant_id=tenant.id,+ actor_user_id=actor_id,+ action=AuditAction.ORGANIZATION_ADMIN_ACCESS_ENDED,+ target_type="user",+ target_id=user_id,+ details={+ "reason": reason,+ "api_keys_deleted": len(revoked.key_hashes),+ "service_connections_deleted": len(revoked.removed_services),+ },+ )+ await session.commit()+ warning = await finish_revocation(+ session, user_id, revoked, protocol=protocol, broker=broker+ )+ if warning:+ warnings.append(f"{tenant.name}: {warning}")+ return " ".join(warnings) or None++[email protected]("/organizations/current/members/{user_id}", response_model=None)async def update_organization_member_role(+ request: Request,user_id: str,req: OrganizationMemberUpdateRequest,session: Annotated[AsyncSession, Depends(get_session)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],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)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],-) -> OrganizationMemberDetail:+) -> OrganizationMemberDetail | JSONResponse:"""Make a member `org_admin`, or an `org_admin` a `member`. `org_admin` only,the one role that grants `org_admin`.Refuses to demote the last `org_admin`: nobody else could grant the role- again. Recorded in the organization's audit log.+ again. Demoting someone first takes away what they hold in the workspaces+ they were in only as `org_admin` (`_end_access_through_organization`).+ Recorded in the organization's audit log."""access = await _require_organization_admin(session, user_store, organization_store, user, operator_restores=True@@ -398,14 +507,47 @@ async def update_organization_member_role(member = await session.get(OrganizationMember, (organization_id, user_id))if member is None:raise HTTPException(status_code=404, detail="Not a member of this organization")+ demoting = (+ member.role == ORGANIZATION_ADMIN_ROLE and req.role != ORGANIZATION_ADMIN_ROLE+ )+ last_admin = HTTPException(+ status_code=409, detail="Cannot demote the last organization admin"+ )if (- member.role == ORGANIZATION_ADMIN_ROLE- and req.role != ORGANIZATION_ADMIN_ROLE+ demotingand await organization_store.count_admins(session, organization_id) <= 1):- raise HTTPException(- status_code=409, detail="Cannot demote the last organization admin"+ raise last_admin++ warning = None+ if demoting:+ # Let go of the request's connection while each workspace is worked on+ # on a session of its own.+ await session.commit()+ try:+ warning = await _end_access_through_organization(+ session_factory,+ user_id=user_id,+ organization_id=organization_id,+ actor_id=user.id,+ reason="demoted",+ agent_store=agent_store,+ api_key_store=api_key_store,+ broker=broker,+ protocol=protocol,+ sign_in_flows=request.app.state.sign_in_flows,+ )+ except ServiceError as error:+ return service_refusal(error)+ if await organization_store.lock_admins(session, organization_id) <= 1:+ raise last_admin+ member = await session.get(+ OrganizationMember, (organization_id, user_id), populate_existing=True)+ if member is None:+ raise HTTPException(+ status_code=404, detail="Not a member of this organization"+ )if member.role != req.role:await record_organization_audit_event(@@ -426,11 +568,12 @@ async def update_organization_member_role(target = await user_store.get(session, user_id)assert target is not None- return _member_detail(target, member)+ return _member_detail(target, member, warning)[email protected]("/organizations/current/members/{user_id}")[email protected]("/organizations/current/members/{user_id}", response_model=None)async def remove_organization_member(+ request: Request,user_id: str,session: Annotated[AsyncSession, Depends(get_session)],session_factory: Annotated[@@ -438,15 +581,21 @@ async def remove_organization_member(],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)],+ broker: Annotated[ServiceBroker, Depends(get_service_broker)],+ protocol: Annotated[AgentCore, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],-) -> dict[str, bool]:+) -> dict | JSONResponse:"""Remove someone from the organization. `org_admin` only.Refuses while they still belong to any of its workspaces, naming them:leaving a workspace revokes their keys and connections there and refuseswhile they own agents, and that is the workspace member route's to do,- one workspace at a time. Refuses the last `org_admin` too. Recorded in- the organization's audit log.+ one workspace at a time. An `org_admin` also stands in workspaces they+ hold no membership row in, and what they hold there is taken away first+ (`_end_access_through_organization`). Refuses the last `org_admin` too.+ Recorded in the organization's audit log."""access = await _require_organization_admin(session, user_store, organization_store, user, operator_restores=False@@ -455,14 +604,15 @@ async def remove_organization_member(member = await session.get(OrganizationMember, (organization_id, user_id))if member is None:raise HTTPException(status_code=404, detail="Not a member of this organization")+ last_admin = HTTPException(+ status_code=409, detail="Cannot remove the last organization admin"+ )+ was_admin = member.role == ORGANIZATION_ADMIN_ROLEif (- member.role == ORGANIZATION_ADMIN_ROLE+ was_adminand await organization_store.count_admins(session, organization_id) <= 1):- raise HTTPException(- status_code=409, detail="Cannot remove the last organization admin"- )- role = member.role+ raise last_admin# Let go of the request's connection while each workspace is read on a# session of its own.await session.commit()@@ -477,6 +627,33 @@ async def remove_organization_member(detail=(f"Remove them from the organization's workspaces first: {names}"),)+ warning = None+ if was_admin:+ try:+ warning = await _end_access_through_organization(+ session_factory,+ user_id=user_id,+ organization_id=organization_id,+ actor_id=user.id,+ reason="removed",+ agent_store=agent_store,+ api_key_store=api_key_store,+ broker=broker,+ protocol=protocol,+ sign_in_flows=request.app.state.sign_in_flows,+ )+ except ServiceError as error:+ return service_refusal(error)++ admins = await organization_store.lock_admins(session, organization_id)+ member = await session.get(+ OrganizationMember, (organization_id, user_id), populate_existing=True+ )+ if member is None:+ raise HTTPException(status_code=404, detail="Not a member of this organization")+ if member.role == ORGANIZATION_ADMIN_ROLE and admins <= 1:+ raise last_admin+ role = member.roleawait session.execute(delete(OrganizationMember).where(OrganizationMember.organization_id == organization_id,@@ -493,4 +670,4 @@ async def remove_organization_member(details={"role": role, **_made_from(access)},)await session.commit()- return {"ok": True}+ return {"ok": True, "warning": warning}diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 149babe3f..264af0ad6 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -1210,6 +1210,9 @@ class OrganizationMemberDetail(BaseModel):email: strrole: strcreated_at: str+ # What could not be revoked at a vendor when a demotion took away what+ # they held in workspaces they were in only as `org_admin`.+ warning: str | Noneclass OrganizationMemberUpdateRequest(BaseModel):diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex d58a87f00..9ed127262 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -118,6 +118,10 @@ from switch_core.gateway.schemas import (UsageTotalResponse,)from switch_core.gateway.service_connections import service_refusal+from switch_core.gateway.workspace_access import (+ finish_revocation,+ revoke_workspace_access,+)from switch_core.gateway.workspace_creation import create_organization_forfrom switch_core.telemetry import emit_safelyfrom switch_core.telemetry.ages import age_hours@@ -1384,15 +1388,16 @@ async def remove_member()try:- removed_services = await broker.remove_connections(session, user_id)+ revoked = await revoke_workspace_access(+ session,+ user_id,+ api_key_store=api_key_store,+ broker=broker,+ sign_in_flows=request.app.state.sign_in_flows,+ )except ServiceError as error:return service_refusal(error)- keys = await api_key_store.get_by_user(session, user_id)- revoked_key_hashes = [key.key_hash for key in keys]- for key in keys:- await api_key_store.delete(session, key.id)-await record_audit_event(session,tenant_id=tenant_id,@@ -1402,17 +1407,14 @@ async def remove_member(target_id=user_id,details={"role": membership.role,- "api_keys_deleted": len(keys),- "service_connections_deleted": len(removed_services),+ "api_keys_deleted": len(revoked.key_hashes),+ "service_connections_deleted": len(revoked.removed_services),},)- # Sign-ins the member had under way in this workspace go with them.- await request.app.state.sign_in_flows.discard_for_user(session, user_id, None)await session.delete(membership)await session.commit()- for key_hash in revoked_key_hashes:- protocol.api_key_cache.invalidate(key_hash)-- warning = await broker.finish_disconnect(session, user_id, removed_services)+ warning = await finish_revocation(+ session, user_id, revoked, protocol=protocol, broker=broker+ )return {"ok": True, "warning": warning}diff --git a/core/switch_core/gateway/workspace_access.py b/core/switch_core/gateway/workspace_access.pynew file mode 100644index 000000000..ca5d484e2--- /dev/null+++ b/core/switch_core/gateway/workspace_access.py@@ -0,0 +1,63 @@+"""Taking away what someone's own credentials let them do in one workspace.++A bearer credential resolves its workspace from its own row and never+consults membership, so whoever stops standing in a workspace (removed from+it, or no longer their organization's `org_admin` where that was their only+standing) has their personal API keys, service connections and sign-ins+under way there removed, or would keep working, invisible access. Agents they+own are refused rather than removed: see `gateway/tenants.py`'s+`remove_member` for why.+"""++from __future__ import annotations++from dataclasses import dataclass, field++from sqlalchemy.ext.asyncio import AsyncSession++from switch_core.bridges.agent.protocol.agent_core import AgentCore+from switch_core.connections.adapters import ConnectionSecret+from switch_core.connections.broker import ServiceBroker+from switch_core.connections.sign_in_flows import SignInFlows+from switch_core.db.stores.api_key_store import ApiKeyStore+++@dataclass(frozen=True)+class RevokedAccess:+ key_hashes: list[str]+ removed_services: list[tuple[str, ConnectionSecret]] = field(repr=False)+++async def revoke_workspace_access(+ session: AsyncSession,+ user_id: str,+ *,+ api_key_store: ApiKeyStore,+ broker: ServiceBroker,+ sign_in_flows: SignInFlows,+) -> RevokedAccess:+ """Remove `user_id`'s keys, service connections and sign-ins under way in+ the bound workspace, in the caller's transaction. Raises `ServiceError`+ when a connection is busy, before anything is removed. The caller+ commits, then calls `finish_revocation`."""+ removed_services = await broker.remove_connections(session, user_id)+ keys = await api_key_store.get_by_user(session, user_id)+ for key in keys:+ await api_key_store.delete(session, key.id)+ await sign_in_flows.discard_for_user(session, user_id, None)+ return RevokedAccess([key.key_hash for key in keys], removed_services)+++async def finish_revocation(+ session: AsyncSession,+ user_id: str,+ revoked: RevokedAccess,+ *,+ protocol: AgentCore,+ broker: ServiceBroker,+) -> str | None:+ """After the revocation has committed: forget the keys, and revoke each+ sign-in at its vendor. A warning names what could not be."""+ for key_hash in revoked.key_hashes:+ protocol.api_key_cache.invalidate(key_hash)+ return await broker.finish_disconnect(session, user_id, revoked.removed_services)diff --git a/core/tests/switch_core/accounts/test_account_deletion.py b/core/tests/switch_core/accounts/test_account_deletion.pyindex 9a83e88be..8e693c761 100644--- a/core/tests/switch_core/accounts/test_account_deletion.py+++ b/core/tests/switch_core/accounts/test_account_deletion.py@@ -48,6 +48,7 @@ from switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.document_store import DocumentStore+from switch_core.db.stores.organization_store import OrganizationStorefrom switch_core.db.stores.package_store import PackageStorefrom switch_core.db.stores.reference_store import ReferenceStorefrom switch_core.db.stores.reference_type_store import ReferenceTypeStore@@ -130,6 +131,7 @@ def _deletion(rooms=rooms, # type: ignore[arg-type]sign_in_flows=_SignInFlows(), # type: ignore[arg-type]users=UserStore(),+ organizations=OrganizationStore(),agents=AgentStore(),api_keys=ApiKeyStore(),templates=TemplateStore(),diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.pyindex 2b172a4f0..d02d17180 100644--- a/core/tests/switch_core/gateway/test_organization_routes.py+++ b/core/tests/switch_core/gateway/test_organization_routes.py@@ -5,7 +5,9 @@ platform operator's access, which every workspace it enters records."""from __future__ import annotations+import asyncioimport uuid+from datetime import timedeltafrom types import SimpleNamespaceimport httpx@@ -13,9 +15,15 @@ from fastapi import FastAPIfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker+from switch_core.connections.broker import ServiceBroker+from switch_core.connections.loader import CATALOG+from switch_core.connections.sign_in_flows import SignInFlowsfrom switch_core.db.audit import AuditAction, OrganizationAuditActionfrom switch_core.db.models import (+ Agent,+ ApiKey,AuditEvent,+ Client,Organization,OrganizationAuditEvent,OrganizationMember,@@ -24,9 +32,13 @@ from switch_core.db.models import (User,)from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.organization_store import OrganizationStore+from switch_core.db.stores.service_connection_store import ServiceConnectionStorefrom switch_core.db.stores.tenant_store import TenantStorefrom switch_core.db.stores.user_store import UserStore+from switch_core.db.stores.workspace_service_store import WorkspaceServiceStorefrom switch_core.gateway import dependencies as gw_depsfrom switch_core.gateway.auth import create_jwt, decode_jwtfrom switch_core.gateway.organizations import router as organizations_router@@ -78,6 +90,24 @@ def _app(app.dependency_overrides[gw_deps.get_client_lifecycle] = lambda: (_FakeClientLifecycle(session_factory))+ app.dependency_overrides[gw_deps.get_agent_store] = lambda: AgentStore()+ app.dependency_overrides[gw_deps.get_api_key_store] = lambda: ApiKeyStore()+ app.dependency_overrides[gw_deps.get_protocol] = lambda: SimpleNamespace(+ api_key_cache=SimpleNamespace(invalidate=lambda key_hash: None)+ )+ app.state.sign_in_flows = SignInFlows(session_factory, _KEYRING)+ app.state.service_broker = ServiceBroker(+ session_factory=session_factory,+ keyring=_KEYRING,+ catalog=CATALOG,+ adapters={},+ disabled={},+ store=ServiceConnectionStore(),+ token_retention=timedelta(days=30),+ workspace_services=WorkspaceServiceStore(),+ workspace_gate=False,+ public_url=None,+ )app.dependency_overrides[gw_deps.get_config] = lambda: SimpleNamespace(keyring=_KEYRING,gateway_cookie_secure=False,@@ -993,3 +1023,239 @@ class TestMarkingTheOperatorsOrganizationChanges:)assert event.details is not Noneassert "platform_access" not in event.details+++async def _second_workspace(+ session_factory: async_sessionmaker[AsyncSession], beside: str+) -> str:+ """Another workspace in `beside`'s organization, with nobody in it."""+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ first = await session.get(Tenant, beside)+ assert first is not None+ session.add(+ Tenant(+ id=tenant_id,+ slug=tenant_id,+ name="Acme Two",+ organization_id=first.organization_id,+ )+ )+ await session.commit()+ return tenant_id+++async def _personal_key(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str, user_id: str+) -> str:+ key_hash = uuid.uuid4().hex+ async with session_factory() as session:+ session.add(+ ApiKey(+ tenant_id=tenant_id,+ user_id=user_id,+ key_hash=key_hash,+ encrypted_key="unused-in-tests",+ label="test-key",+ type="registration",+ )+ )+ await session.commit()+ return key_hash+++async def _agent(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str, owner_id: str+) -> None:+ async with session_factory() as session:+ client = Client(+ tenant_id=tenant_id,+ transport_user_id=f"@bot-{uuid.uuid4().hex[:8]}:test",+ display_name="bot",+ type="agent",+ )+ session.add(client)+ await session.flush()+ key = ApiKey(+ tenant_id=tenant_id,+ user_id=owner_id,+ key_hash=uuid.uuid4().hex,+ encrypted_key="unused-in-tests",+ label="agent-key",+ type="agent",+ )+ session.add(key)+ await session.flush()+ session.add(+ Agent(+ tenant_id=tenant_id,+ name=f"agent-{uuid.uuid4().hex[:6]}",+ description="test agent",+ agent_type="other",+ connector_type="claude-code",+ integration_profile={},+ client_id=client.id,+ api_key_id=key.id,+ owner_id=owner_id,+ )+ )+ await session.commit()+++async def _key_exists(+ session_factory: async_sessionmaker[AsyncSession], key_hash: str+) -> bool:+ async with session_factory() as session:+ return (+ await session.scalar(select(ApiKey.id).where(ApiKey.key_hash == key_hash))+ ) is not None+++class TestLosingOrgAdmin:+ """An `org_admin` stands in every workspace of the organization, including+ those they hold no membership row in. Demoting or removing them takes+ away what they made there, as removing a workspace member does."""++ async def test_demoting_removes_their_keys_where_they_had_no_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ first = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}+ )+ second = await _second_workspace(session_factory, first)+ kept = await _personal_key(session_factory, first, bob)+ dropped = await _personal_key(session_factory, second, bob)++ async with _client(_app(session_factory), ada, first) as client:+ response = await client.patch(+ f"/organizations/current/members/{bob}", json={"role": "member"}+ )++ assert response.status_code == 200, response.text+ assert response.json()["role"] == "member"+ assert await _key_exists(session_factory, kept)+ assert not await _key_exists(session_factory, dropped)+ ended = await _events(+ session_factory, second, AuditAction.ORGANIZATION_ADMIN_ACCESS_ENDED+ )+ assert [+ (event.target_id, (event.details or {}).get("api_keys_deleted"))+ for event in ended+ ] == [(bob, 1)]++ async def test_demoting_is_refused_while_they_own_agents_there(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ first = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "org_admin")}+ )+ second = await _second_workspace(session_factory, first)+ await _agent(session_factory, second, bob)+ key = await _personal_key(session_factory, second, bob)++ async with _client(_app(session_factory), ada, first) as client:+ response = await client.patch(+ f"/organizations/current/members/{bob}", json={"role": "member"}+ )++ assert response.status_code == 409+ assert "Acme Two" in response.json()["detail"]+ assert await _key_exists(session_factory, key)+ organization_id = await _organization_id(session_factory, first)+ async with session_factory() as session:+ member = await session.get(OrganizationMember, (organization_id, bob))+ assert member is not None and member.role == "org_admin"++ async def test_removing_removes_their_keys_where_they_had_no_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ first = await _workspace(session_factory, {ada: ("owner", "org_admin")})+ second = await _second_workspace(session_factory, first)+ organization_id = await _organization_id(session_factory, first)+ assert organization_id is not None+ async with session_factory() as session:+ session.add(+ User(id=bob, name=bob, email=f"{bob}@example.invalid", role="user")+ )+ await session.flush()+ session.add(+ OrganizationMember(+ organization_id=organization_id, user_id=bob, role="org_admin"+ )+ )+ await session.commit()+ dropped = await _personal_key(session_factory, second, bob)++ async with _client(_app(session_factory), ada, first) as client:+ response = await client.delete(f"/organizations/current/members/{bob}")++ assert response.status_code == 200, response.text+ assert not await _key_exists(session_factory, dropped)++ async def test_two_admins_demoting_each_other_at_once_leave_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("owner", "org_admin")}+ )+ app = _app(session_factory)++ async with (+ _client(app, ada, tenant_id) as as_ada,+ _client(app, bob, tenant_id) as as_bob,+ ):+ responses = await asyncio.gather(+ as_ada.patch(+ f"/organizations/current/members/{bob}", json={"role": "member"}+ ),+ as_bob.patch(+ f"/organizations/current/members/{ada}", json={"role": "member"}+ ),+ )++ assert sorted(response.status_code for response in responses) == [200, 409]+ organization_id = await _organization_id(session_factory, tenant_id)+ assert organization_id is not None+ async with session_factory() as session:+ admins = await OrganizationStore().count_admins(session, organization_id)+ assert admins == 1++ async def test_two_admins_removing_each_other_at_once_leave_one(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob, cy = _name("ada"), _name("bob"), _name("cy")+ first = await _workspace(session_factory, {cy: ("owner", "member")})+ organization_id = await _organization_id(session_factory, first)+ assert organization_id is not None+ async with session_factory() as session:+ for name in (ada, bob):+ session.add(+ User(+ id=name, name=name, email=f"{name}@example.invalid", role="user"+ )+ )+ await session.flush()+ session.add(+ OrganizationMember(+ organization_id=organization_id, user_id=name, role="org_admin"+ )+ )+ await session.commit()+ app = _app(session_factory)++ async with (+ _client(app, ada, first) as as_ada,+ _client(app, bob, first) as as_bob,+ ):+ responses = await asyncio.gather(+ as_ada.delete(f"/organizations/current/members/{bob}"),+ as_bob.delete(f"/organizations/current/members/{ada}"),+ )++ assert sorted(response.status_code for response in responses) == [200, 409]+ async with session_factory() as session:+ assert await OrganizationStore().count_admins(session, organization_id) == 1diff --git a/gateway/src/data/api.ts b/gateway/src/data/api.tsindex d5a27847b..9648a62a6 100644--- a/gateway/src/data/api.ts+++ b/gateway/src/data/api.ts@@ -1230,6 +1230,10 @@ export interface OrganizationMember {email: string;role: OrganizationRole;created_at: string;+ /** After a demotion: sign-ins Switch could not revoke at a vendor while+ * taking away what they held in workspaces they were in only as an+ * organization admin. */+ warning: string | null;}export interface OrganizationAuditEvent {@@ -1290,8 +1294,14 @@ export async function updateOrganizationRole();}-export async function removeOrganizationMember(userId: string): Promise<void> {- await jsonRequest(`/organizations/current/members/${encodeURIComponent(userId)}`, "DELETE");+/** The warning names sign-ins that could not be revoked at a vendor, if any. */+export async function removeOrganizationMember(+ userId: string,+): Promise<{ warning: string | null }> {+ return jsonRequest<{ warning: string | null }>(+ `/organizations/current/members/${encodeURIComponent(userId)}`,+ "DELETE",+ );}export const ORGANIZATION_AUDIT_PAGE = 50;diff --git a/gateway/src/pages/organization/OrganizationMembersSection.tsx b/gateway/src/pages/organization/OrganizationMembersSection.tsxindex ae3ebe9fe..ce9d1f1ec 100644--- a/gateway/src/pages/organization/OrganizationMembersSection.tsx+++ b/gateway/src/pages/organization/OrganizationMembersSection.tsx@@ -33,7 +33,9 @@ const ROLE_LABELS: Record<OrganizationRole, string> = {/** Everyone in the organization, across its workspaces, and their role in it.* The server refuses demoting or removing the last organization admin, and* removing someone still in one of its workspaces, naming them; its message- * is shown as is. */+ * is shown as is. Demoting or removing an admin also takes away their keys and+ * connections in workspaces they were in only as an admin; what could not be+ * revoked at a vendor comes back as a warning, shown too. */export default function OrganizationMembersSection({selfId,asOperator,@@ -46,15 +48,18 @@ export default function OrganizationMembersSection({const load = useCallback(() => fetchOrganizationMembers(), []);const { data: members, error, errorStatus, loading, refetch } = useLoad(load);const [actionError, setActionError] = useState<string | null>(null);+ const [actionWarning, setActionWarning] = useState<string | null>(null);const [busy, setBusy] = useState<string | null>(null);const { refresh } = useAuth();const act = useCallback(- async (userId: string, action: () => Promise<unknown>) => {+ async (userId: string, action: () => Promise<{ warning: string | null }>) => {setBusy(userId);setActionError(null);+ setActionWarning(null);try {- await action();+ const { warning } = await action();+ setActionWarning(warning);await refetch();// Your own role decides what this page offers you.if (userId === selfId) await refresh();@@ -162,6 +167,11 @@ export default function OrganizationMembersSection({{actionError}</Alert>)}+ {actionWarning && (+ <Alert severity="warning" onClose={() => setActionWarning(null)}>+ {actionWarning}+ </Alert>+ )}{loading ? (<CircularProgress />) : error ? null : (diff --git a/gateway/src/pages/organization/OrganizationPage.test.tsx b/gateway/src/pages/organization/OrganizationPage.test.tsxindex f9f7f6e8f..adb93c833 100644--- a/gateway/src/pages/organization/OrganizationPage.test.tsx+++ b/gateway/src/pages/organization/OrganizationPage.test.tsx@@ -1,4 +1,4 @@-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import type { Session } from "../../data/api";import { useAuth } from "../../data/AuthContext";@@ -117,6 +117,37 @@ describe("OrganizationPage", () => {expect(screen.getByText("Olga (platform operator)")).toBeTruthy();});+ it("shows what a demotion could not revoke at a vendor", async () => {+ signedInAs(session("org_admin", true));+ const bob = {+ user_id: "u2",+ name: "Bob",+ email: "[email protected]",+ role: "org_admin",+ created_at: "2026-01-01",+ warning: null,+ };+ answer({+ "GET /organizations/current": { id: "o1", slug: "acme", name: "Acme Inc", role: "org_admin" },+ "GET /organizations/current/workspaces": [workspace("t1", "Acme")],+ "GET /organizations/current/members": [bob],+ "GET /organizations/current/audit-events": [],+ "PATCH /organizations/current/members/u2": {+ ...bob,+ role: "member",+ warning: "Acme Two: GitHub could not be revoked.",+ },+ });++ render(<OrganizationPage />);++ const row = await screen.findByTestId("row-u2");+ fireEvent.mouseDown(within(row).getByRole("combobox"));+ fireEvent.click(await screen.findByRole("option", { name: "Member" }));++ expect(await screen.findByText("Acme Two: GitHub could not be revoked.")).toBeTruthy();+ });+it("shows a member only the workspaces, with nothing to add", async () => {signedInAs(session("member", false));answer({