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
[CHOO-3906] Organization member removal, org admins on the roster, audited operator access
Petr Bauche53485f279b9
diff --git a/core/switch_core/db/audit.py b/core/switch_core/db/audit.pyindex eceaa3f46..de81cd4f4 100644--- a/core/switch_core/db/audit.py+++ b/core/switch_core/db/audit.py@@ -29,6 +29,10 @@ class AuditAction(StrEnum):MEMBER_ROLE_CHANGED = "member.role_changed"MEMBER_REMOVED = "member.removed"ORGANIZATION_ROLE_CHANGED = "organization.role_changed"+ ORGANIZATION_MEMBER_REMOVED = "organization.member_removed"+ # The platform operator acting in a workspace on the operator flag alone:+ # entering it, and every write while there.+ PLATFORM_ACCESS = "platform.access"ACCOUNT_DELETED = "account.deleted"JOIN_DOMAIN_ADDED = "join_domain.added"JOIN_DOMAIN_REMOVED = "join_domain.removed"diff --git a/core/switch_core/db/stores/organization_store.py b/core/switch_core/db/stores/organization_store.pyindex 5cd70b54d..fe7266cf4 100644--- a/core/switch_core/db/stores/organization_store.py+++ b/core/switch_core/db/stores/organization_store.py@@ -66,22 +66,26 @@ class OrganizationStore:return member.role if member is not None else Noneasync def list_members(- self, session: AsyncSession+ self, session: AsyncSession, organization_id: str) -> list[tuple[User, OrganizationMember]]:- """Every member of the bound organization, with their user row."""+ """Every member of `organization_id`, with their user row."""result = await session.execute(select(User, OrganizationMember).join(OrganizationMember, OrganizationMember.user_id == User.id)+ .where(OrganizationMember.organization_id == organization_id).order_by(User.name, User.id))return [(row[0], row[1]) for row in result.all()]- async def count_admins(self, session: AsyncSession) -> int:- """How many `org_admin`s the bound organization has."""+ async def count_admins(self, session: AsyncSession, organization_id: str) -> int:+ """How many `org_admin`s `organization_id` has."""return (await session.execute(select(func.count()).select_from(OrganizationMember)- .where(OrganizationMember.role == "org_admin")+ .where(+ OrganizationMember.organization_id == organization_id,+ OrganizationMember.role == "org_admin",+ ))).scalar_one()diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex 014d9a25e..d586f632b 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -523,6 +523,19 @@ class UserStore:)return member.role if member is not None else None+ async def administers_by_role(+ self, session: AsyncSession, tenant_id: str, user_id: str+ ) -> bool:+ """Whether `user_id` administers `tenant_id` through a role they hold+ (a workspace admin or owner membership, or `org_admin` of its+ organization), leaving the operator flag out. An operator who does+ not is there on `platform_access`."""+ return administers_tenant(+ is_operator=False,+ tenant_role=await self.tenant_role(session, tenant_id, user_id),+ organization_role=await self.organization_role(session, tenant_id, user_id),+ )+async def effective_tenant_role(self, session: AsyncSession, tenant_id: str, user_id: str) -> str | None:diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 7f10c3018..14fd49605 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -16,11 +16,13 @@ from starlette.requests import HTTPConnectionfrom switch_core.authz import Action, Principal, requirefrom switch_core.config import SwitchConfig+from switch_core.db.audit import AuditAction, record_audit_eventfrom switch_core.db.models import Room, Tenant, Userfrom switch_core.db.session_scope import tenant_sessionfrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import (+ all_tenant_ids,tenant_of_invitation,tenants_administered_through_organization,tenants_inviting_email,@@ -44,6 +46,8 @@ from switch_core.tenant_context import tenant_scopelogger = logging.getLogger(__name__)+_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})+JWT_ALGORITHM = "HS256"JWT_EXPIRY_HOURS = 24@@ -361,17 +365,94 @@ async def tenants_bindable_by()+async def workspaces_in_organization(+ session_factory: async_sessionmaker[AsyncSession],+ user_id: str,+ organization_id: str,+) -> list[Tenant]:+ """The workspaces of `organization_id` that `user_id` holds a membership+ row in. Each workspace is read on its own short session, one after+ another, so the caller holds no other connection while this runs."""+ found: list[Tenant] = []+ for tenant_id in await tenants_of_user(session_factory, user_id):+ 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 _operator_may_enter(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user_id: str,+ tenant_id: str,+) -> bool:+ """Whether `user_id` is the platform operator and `tenant_id` exists: the+ operator may bind any workspace, on `platform_access`."""+ async with session_factory() as system_session:+ user = await user_store.get(system_session, user_id)+ if user is None or user.role != "admin":+ return False+ async with tenant_session(session_factory, tenant_id) as session:+ return await session.get(Tenant, tenant_id) is not None+++async def record_operator_entry(+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user_id: str,+ tenant_id: str,+) -> None:+ """Record the operator entering `tenant_id`, when they hold no role that+ administers it: `platform_access` in the workspace's own audit log, where+ its admins read it."""+ async with tenant_session(session_factory, tenant_id) as session:+ if await user_store.administers_by_role(session, tenant_id, user_id):+ return+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=user_id,+ action=AuditAction.PLATFORM_ACCESS,+ target_type="tenant",+ target_id=tenant_id,+ details={"event": "entered"},+ )+ await session.commit()+++async def all_workspaces(+ session_factory: async_sessionmaker[AsyncSession],+) -> list[Tenant]:+ """Every workspace on the server, oldest first, each read on its own short+ session. For the platform operator's list only."""+ found: list[Tenant] = []+ for tenant_id in await all_tenant_ids(session_factory):+ async with tenant_session(session_factory, tenant_id) as session:+ tenant = await session.get(Tenant, tenant_id)+ if tenant is not None:+ found.append(tenant)+ return found++async def may_bind_tenant(- session_factory: async_sessionmaker[AsyncSession], user_id: str, tenant_id: str+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user_id: str,+ tenant_id: str,) -> bool:- """Whether `user_id` may bind `tenant_id` (`tenants_bindable_by`).+ """Whether `user_id` may bind `tenant_id`: one of `tenants_bindable_by`,+ or any workspace for the platform operator.Backs `POST /tenants/{id}/switch`: the claim it goes on to mint neverauthorises by itself (`_resolve_tenant_id` re-checks it on every requestregardless), but switching still must not let someone select a tenantthey may not bind."""- return tenant_id in await tenants_bindable_by(session_factory, user_id)+ if tenant_id in await tenants_bindable_by(session_factory, user_id):+ return True+ return await _operator_may_enter(session_factory, user_store, user_id, tenant_id)async def _describe_memberships(@@ -605,6 +686,10 @@ async def _resolve_tenant_id(if tenant_claim is not None:if tenant_claim in memberships:return tenant_claim+ if await _operator_may_enter(+ session_factory, user_store, user_id, tenant_claim+ ):+ return tenant_claimlogger.warning("Tenant claim %s for user %s names no membership", tenant_claim, user_id)@@ -677,6 +762,28 @@ async def _bound_user(if user is None:# Deleted between the two reads; rare, and still not a 500.raise HTTPException(status_code=401, detail="User not found")+ request.state.platform_access = (+ user.role == "admin"+ and not await user_store.administers_by_role(session, tenant_id, user_id)+ )+ if request.state.platform_access and request.method not in _SAFE_METHODS:+ route = request.scope.get("route")+ await record_audit_event(+ session,+ tenant_id=tenant_id,+ actor_user_id=user_id,+ action=AuditAction.PLATFORM_ACCESS,+ target_type="tenant",+ target_id=tenant_id,+ details={+ "event": "write",+ "method": request.method,+ "route": getattr(route, "path", request.url.path),+ },+ )+ # Committed before the route runs, so the attempt is recorded+ # whether or not the write succeeds.+ await session.commit()yield userdiff --git a/core/switch_core/gateway/organizations.py b/core/switch_core/gateway/organizations.pyindex 88d29bffa..7e7c338a8 100644--- a/core/switch_core/gateway/organizations.py+++ b/core/switch_core/gateway/organizations.py@@ -2,8 +2,12 @@Every route acts on the organization the request's workspace belongs to(`current`), which the policy on `organization_members` derives from the bound-workspace, and only its `org_admin`s may use them. Creating organizations and-workspaces in them comes later; see `docs/design/organizations-v1.md`.+workspace, and only its `org_admin`s may use them. The one exception is an+organization with no `org_admin` left: the platform operator may list its+members and make one of them `org_admin`, and being there on the operator+flag alone, does so on `platform_access`, recorded as every operator write+is (`gateway/auth.py`). Creating organizations and workspaces in them comes+later; see `docs/design/organizations-v1.md`."""from __future__ import annotations@@ -11,17 +15,19 @@ from __future__ import annotationsfrom typing import Annotatedfrom fastapi import APIRouter, Depends, HTTPException-from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy import delete+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.authz import ORGANIZATION_ADMIN_ROLEfrom switch_core.db.audit import AuditAction, record_audit_eventfrom switch_core.db.models import OrganizationMember, Tenant, User, require_tenant_idfrom switch_core.db.stores.organization_store import OrganizationStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.gateway.auth import get_current_user+from switch_core.gateway.auth import get_current_user, workspaces_in_organizationfrom switch_core.gateway.dependencies import (get_organization_store,get_session,+ get_session_factory,get_user_store,)from switch_core.gateway.schemas import (@@ -43,10 +49,19 @@ def _member_detail(user: User, member: OrganizationMember) -> OrganizationMemberasync def _require_organization_admin(- session: AsyncSession, user_store: UserStore, user: User+ session: AsyncSession,+ user_store: UserStore,+ organization_store: OrganizationStore,+ user: User,+ *,+ operator_restores: bool,) -> str:"""The bound workspace's organization id; 403 unless `user` is its- `org_admin`, 404 when the workspace belongs to no organization."""+ `org_admin`, 404 when the workspace belongs to no organization.++ With `operator_restores`, the platform operator passes too while the+ organization has no `org_admin`, so that someone can be made one.+ """tenant_id = require_tenant_id()tenant = await session.get(Tenant, tenant_id)if tenant is None or tenant.organization_id is None:@@ -55,12 +70,18 @@ async def _require_organization_admin()if (await user_store.organization_role(session, tenant_id, user.id)- != ORGANIZATION_ADMIN_ROLE+ == ORGANIZATION_ADMIN_ROLE):- raise HTTPException(- status_code=403, detail="Only an organization admin may do this"- )- return tenant.organization_id+ return tenant.organization_id+ if (+ operator_restores+ and user.role == "admin"+ and await organization_store.count_admins(session, tenant.organization_id) == 0+ ):+ return tenant.organization_id+ raise HTTPException(+ status_code=403, detail="Only an organization admin may do this"+ )@router.get("/organizations/current/members")@@ -72,8 +93,10 @@ async def list_organization_members() -> list[OrganizationMemberDetail]:"""Every member of the organization and their role in it. `org_admin` only:the list spans every workspace of the organization, not only this one."""- await _require_organization_admin(session, user_store, user)- members = await organization_store.list_members(session)+ organization_id = await _require_organization_admin(+ session, user_store, organization_store, user, operator_restores=True+ )+ members = await organization_store.list_members(session, organization_id)return [_member_detail(member_user, member) for member_user, member in members]@@ -92,14 +115,16 @@ async def update_organization_member_role(Refuses to demote the last `org_admin`: nobody else could grant the roleagain. Recorded in the bound workspace's audit log."""- organization_id = await _require_organization_admin(session, user_store, user)+ organization_id = await _require_organization_admin(+ session, user_store, organization_store, user, operator_restores=True+ )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")if (member.role == ORGANIZATION_ADMIN_ROLEand req.role != ORGANIZATION_ADMIN_ROLE- and await organization_store.count_admins(session) <= 1+ and await organization_store.count_admins(session, organization_id) <= 1):raise HTTPException(status_code=409, detail="Cannot demote the last organization admin"@@ -125,3 +150,69 @@ async def update_organization_member_role(target = await user_store.get(session, user_id)assert target is not Nonereturn _member_detail(target, member)++[email protected]("/organizations/current/members/{user_id}")+async def remove_organization_member(+ user_id: str,+ 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)],+ user: Annotated[User, Depends(get_current_user)],+) -> dict[str, bool]:+ """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 refuses+ while 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 bound workspace's audit log.+ """+ organization_id = await _require_organization_admin(+ session, user_store, organization_store, user, operator_restores=False+ )+ 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")+ if (+ member.role == ORGANIZATION_ADMIN_ROLE+ and await organization_store.count_admins(session, organization_id) <= 1+ ):+ raise HTTPException(+ status_code=409, detail="Cannot remove the last organization admin"+ )+ role = member.role+ # Let go of the request's connection while each workspace is read on a+ # session of its own.+ await session.commit()++ workspaces = await workspaces_in_organization(+ session_factory, user_id, organization_id+ )+ if workspaces:+ names = ", ".join(sorted(tenant.name for tenant in workspaces))+ raise HTTPException(+ status_code=409,+ detail=(f"Remove them from the organization's workspaces first: {names}"),+ )++ await session.execute(+ delete(OrganizationMember).where(+ OrganizationMember.organization_id == organization_id,+ OrganizationMember.user_id == user_id,+ )+ )+ await record_audit_event(+ session,+ tenant_id=require_tenant_id(),+ actor_user_id=user.id,+ action=AuditAction.ORGANIZATION_MEMBER_REMOVED,+ target_type="user",+ target_id=user_id,+ details={"organization_id": organization_id, "role": role},+ )+ await session.commit()+ return {"ok": True}diff --git a/core/switch_core/gateway/schemas.py b/core/switch_core/gateway/schemas.pyindex 1ebfd7d42..4fb139bbd 100644--- a/core/switch_core/gateway/schemas.py+++ b/core/switch_core/gateway/schemas.py@@ -913,6 +913,15 @@ class TenantMembershipResponse(BaseModel):organization_role: str | None+class OperatorWorkspaceResponse(BaseModel):+ """One workspace on the server, as the platform operator's list shows it."""++ id: str+ slug: str+ name: str+ organization_id: str | None++class CurrentTenantResponse(TenantMembershipResponse):"""The tenant this request is bound to. `administers` is whether thecaller may manage it — an `owner` or `admin` membership, or the operator@@ -1094,6 +1103,13 @@ class InvitationCreateResponse(InvitationDetail):class MemberDetail(BaseModel):+ """One person in a workspace's roster.++ `via_organization` marks an organization's `org_admin` who holds no+ membership row here: listed as `admin`, because that is what they act+ as, and changed or removed only through the organization's members.+ """+user_id: strname: stremail: str@@ -1102,6 +1118,8 @@ class MemberDetail(BaseModel):# The agent-registration bootstrap owner: kept in the roster, never a# person to add to a chat.service_account: bool+ organization_role: str | None+ via_organization: boolclass UsageTotalResponse(BaseModel):diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex d8099d6c8..bcd44a86b 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -14,7 +14,7 @@ from sqlalchemy import selectfrom sqlalchemy.exc import DBAPIError, IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.authz import ORGANIZATION_ADMIN_ROLE+from switch_core.authz import ORGANIZATION_ADMIN_ROLE, ORGANIZATION_ADMIN_TENANT_ROLEfrom switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.registration_bootstrap import is_bootstrap_ownerfrom switch_core.clients.client_lifecycle_service import (@@ -31,6 +31,7 @@ from switch_core.db.audit import AuditAction, list_audit_events, record_audit_evfrom switch_core.db.models import (Invitation,Organization,+ OrganizationMember,Tenant,TenantJoinDomain,TenantMember,@@ -63,6 +64,7 @@ from switch_core.db.stores.usage_store import UsageStorefrom switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import (AuthenticatedCaller,+ all_workspaces,get_authenticated_caller,get_authenticated_user_id,get_current_user,@@ -70,6 +72,7 @@ from switch_core.gateway.auth import (get_tenant_is_owner,list_tenant_memberships,may_bind_tenant,+ record_operator_entry,require_tenant_admin,set_session_cookie,tenant_of_invitation_token,@@ -121,6 +124,7 @@ from switch_core.gateway.schemas import (JoinDomainsResponse,MemberDetail,MemberUpdateRequest,+ OperatorWorkspaceResponse,SessionUserResponse,TenantCreateRequest,TenantMembershipResponse,@@ -195,7 +199,9 @@ def _invitation_detail(invitation: Invitation) -> InvitationDetail:return InvitationDetail(**_invitation_fields(invitation))-def _member_detail(user: User, membership: TenantMember) -> MemberDetail:+def _member_detail(+ user: User, membership: TenantMember, organization_role: str | None+) -> MemberDetail:return MemberDetail(user_id=user.id,name=user.name,@@ -203,6 +209,8 @@ def _member_detail(user: User, membership: TenantMember) -> MemberDetail:role=membership.role,created_at=str(membership.created_at),service_account=is_bootstrap_owner(user),+ organization_role=organization_role,+ via_organization=False,)@@ -301,6 +309,7 @@ async def list_tenants(@router.get("/tenants/current")async def current_tenant(+ request: Request,session: Annotated[AsyncSession, Depends(get_session)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],@@ -315,6 +324,10 @@ async def current_tenant(tenant_id = require_tenant_id()tenant = await session.get(Tenant, tenant_id)role = await user_store.effective_tenant_role(session, tenant_id, user.id)+ if role is None and request.state.platform_access:+ # The platform operator, there on the operator flag alone, acts as+ # an admin and holds no role to report.+ role = ORGANIZATION_ADMIN_TENANT_ROLEif tenant is None or role is None:raise HTTPException(status_code=404, detail="Tenant not found")return CurrentTenantResponse(@@ -602,14 +615,21 @@ async def switch_tenant(cookie says, so a forged or stale claim already buys nothing — but thisroute is the one place a *caller* picks the value that goes into it, andit must not let them pick a tenant they may not bind: one they are a- member of, or one their organization's `org_admin` role covers.+ member of, one their organization's `org_admin` role covers, or, for the+ platform operator, any.++ The platform operator entering a workspace on the operator flag alone is+ recorded in that workspace's audit log. Signing in never selects such a+ workspace (`initial_tenant_claim`), so every visit starts here."""- if not await may_bind_tenant(session_factory, user_id, tenant_id):+ if not await may_bind_tenant(session_factory, user_store, user_id, tenant_id):raise HTTPException(status_code=403, detail="Not a member of this tenant")user = await user_store.get(session, user_id)if user is None:raise HTTPException(status_code=401, detail="User not found")+ if user.role == "admin":+ await record_operator_entry(session_factory, user_store, user_id, tenant_id)await user_store.record_last_tenant(session, user, tenant_id)await session.commit()@@ -619,6 +639,30 @@ async def switch_tenant(return _session_response(user)[email protected]("/operator/workspaces")+async def list_every_workspace(+ caller: Annotated[AuthenticatedCaller, Depends(get_authenticated_caller)],+ session_factory: Annotated[+ async_sessionmaker[AsyncSession], Depends(get_session_factory)+ ],+) -> list[OperatorWorkspaceResponse]:+ """Every workspace on the server, for the platform operator to enter one+ with `POST /tenants/{id}/switch`. Kept apart from `GET /tenants`, which+ stays the caller's own, so the ordinary picker never lists customers'+ workspaces. Listing records nothing; entering does."""+ if not caller.is_operator:+ raise HTTPException(status_code=403, detail="Admin access required")+ return [+ OperatorWorkspaceResponse(+ id=tenant.id,+ slug=tenant.slug,+ name=tenant.name,+ organization_id=tenant.organization_id,+ )+ for tenant in await all_workspaces(session_factory)+ ]++# ── Invitations ───────────────────────────────────────────────────────────────@@ -1425,13 +1469,45 @@ async def list_members(tenant_id: str,session: Annotated[AsyncSession, Depends(get_session)],user_store: Annotated[UserStore, Depends(get_user_store)],+ organization_store: Annotated[OrganizationStore, Depends(get_organization_store)],_user: Annotated[User, Depends(get_current_user)],) -> list[MemberDetail]:- """Every member of the bound tenant. Any member may list their own- workspace's roster; changing or removing one is admin-gated below."""+ """Every member of the bound tenant, then every `org_admin` of its+ organization who is not one, as `admin` via the organization. Any member+ may list their own workspace's roster; changing or removing one is+ admin-gated below."""_require_bound_tenant(tenant_id)+ tenant = await session.get(Tenant, tenant_id)+ organization_roles: dict[str, str] = {}+ organization_admins: list[tuple[User, OrganizationMember]] = []+ if tenant is not None and tenant.organization_id is not None:+ for user, member in await organization_store.list_members(+ session, tenant.organization_id+ ):+ organization_roles[user.id] = member.role+ if member.role == ORGANIZATION_ADMIN_ROLE:+ organization_admins.append((user, member))members = await user_store.list_tenant_members(session)- return [_member_detail(user, membership) for user, membership in members]+ roster = [+ _member_detail(user, membership, organization_roles.get(user.id))+ for user, membership in members+ ]+ listed = {user.id for user, _ in members}+ roster.extend(+ MemberDetail(+ user_id=user.id,+ name=user.name,+ email=user.email,+ role=ORGANIZATION_ADMIN_TENANT_ROLE,+ created_at=str(member.created_at),+ service_account=is_bootstrap_owner(user),+ organization_role=member.role,+ via_organization=True,+ )+ for user, member in organization_admins+ if user.id not in listed+ )+ return roster@router.patch("/tenants/{tenant_id}/members/{user_id}")@@ -1487,7 +1563,11 @@ async def update_member_role(user = await user_store.get(session, user_id)assert user is not None- return _member_detail(user, membership)+ return _member_detail(+ user,+ membership,+ await user_store.organization_role(session, tenant_id, user_id),+ )@router.delete("/tenants/{tenant_id}/members/{user_id}", response_model=None)diff --git a/core/tests/switch_core/gateway/test_organization_routes.py b/core/tests/switch_core/gateway/test_organization_routes.pyindex 0105dfb53..bfb16c7ae 100644--- a/core/tests/switch_core/gateway/test_organization_routes.py+++ b/core/tests/switch_core/gateway/test_organization_routes.py@@ -1,5 +1,7 @@"""`/organizations/current/members`: an organization's `org_admin`s list its-members and grant or take back `org_admin`, never below one."""+members, grant or take back `org_admin` and remove members, never below one+`org_admin`. Also the workspace roster's organization admins, and the+platform operator's access, which every workspace it enters records."""from __future__ import annotations@@ -43,6 +45,7 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:app.include_router(organizations_router)app.include_router(tenants_router)app.dependency_overrides[gw_deps.get_session] = _session_dep+ app.dependency_overrides[gw_deps.get_system_session] = _session_depapp.dependency_overrides[gw_deps.get_session_factory] = lambda: session_factoryapp.dependency_overrides[gw_deps.get_user_store] = lambda: UserStore()app.dependency_overrides[gw_deps.get_organization_store] = lambda: (@@ -56,7 +59,7 @@ def _app(session_factory: async_sessionmaker[AsyncSession]) -> FastAPI:return app-def _client(app: FastAPI, user_id: str, tenant_id: str) -> httpx.AsyncClient:+def _client(app: FastAPI, user_id: str, tenant_id: str | None) -> httpx.AsyncClient:token = create_jwt(user_id, f"{user_id}@example.invalid", "user", _KEYRING, tenant_id)@@ -234,3 +237,229 @@ class TestChangingRoles:assert in_organization.status_code == 200, in_organization.textassert in_workspace.status_code == 200, in_workspace.textassert in_workspace.json()["role"] == "member"+++async def _operator(session_factory: async_sessionmaker[AsyncSession]) -> str:+ operator_id = _name("operator")+ async with session_factory() as session:+ session.add(+ User(+ id=operator_id,+ name=operator_id,+ email=f"{operator_id}@example.invalid",+ role="admin",+ )+ )+ await session.commit()+ return operator_id+++async def _events(+ session_factory: async_sessionmaker[AsyncSession],+ tenant_id: str,+ action: AuditAction,+) -> list[AuditEvent]:+ async with tenant_session(session_factory, tenant_id) as session:+ return list(+ await session.scalars(select(AuditEvent).where(AuditEvent.action == action))+ )+++class TestRemoving:+ async def test_someone_still_in_a_workspace_of_it_is_refused_by_name(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}+ )++ async with _client(_app(session_factory), ada, tenant_id) as client:+ response = await client.delete(f"/organizations/current/members/{bob}")++ assert response.status_code == 409+ assert "Acme" in response.json()["detail"]++ async def test_someone_in_none_of_its_workspaces_is_removed_and_it_is_audited(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("member", "member")}+ )+ async with tenant_session(session_factory, tenant_id) as session:+ await session.delete(await session.get(TenantMember, (tenant_id, bob)))+ await session.commit()++ async with _client(_app(session_factory), ada, tenant_id) as client:+ response = await client.delete(f"/organizations/current/members/{bob}")+ listed = await client.get("/organizations/current/members")++ assert response.status_code == 200, response.text+ assert [row["user_id"] for row in listed.json()] == [ada]+ [event] = await _events(+ session_factory, tenant_id, AuditAction.ORGANIZATION_MEMBER_REMOVED+ )+ assert event.target_id == bob++ async def test_the_last_org_admin_cannot_be_removed(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada = _name("ada")+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})++ async with _client(_app(session_factory), ada, tenant_id) as client:+ response = await client.delete(f"/organizations/current/members/{ada}")++ assert response.status_code == 409+ assert "last organization admin" in response.json()["detail"]+++class TestTheWorkspaceRoster:+ async def test_lists_org_admins_with_no_membership_as_admin_via_the_organization(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob, cy = _name("ada"), _name("bob"), _name("cy")+ tenant_id = await _workspace(+ session_factory,+ {+ ada: ("owner", "org_admin"),+ bob: ("member", "member"),+ cy: ("member", "org_admin"),+ },+ )+ async with tenant_session(session_factory, tenant_id) as session:+ await session.delete(await session.get(TenantMember, (tenant_id, cy)))+ await session.commit()++ async with _client(_app(session_factory), bob, tenant_id) as client:+ response = await client.get(f"/tenants/{tenant_id}/members")++ assert response.status_code == 200, response.text+ rows = {+ row["user_id"]: (+ row["role"],+ row["organization_role"],+ row["via_organization"],+ )+ for row in response.json()+ }+ assert rows == {+ ada: ("owner", "org_admin", False),+ bob: ("member", "member", False),+ cy: ("admin", "org_admin", True),+ }+++class TestThePlatformOperator:+ async def test_entering_a_workspace_is_recorded_there(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada = _name("ada")+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})+ operator_id = await _operator(session_factory)++ async with _client(_app(session_factory), operator_id, None) as client:+ switched = await client.post(f"/tenants/{tenant_id}/switch")++ assert switched.status_code == 200, switched.text+ [event] = await _events(session_factory, tenant_id, AuditAction.PLATFORM_ACCESS)+ assert event.actor_user_id == operator_id+ assert event.details == {"event": "entered"}++ async def test_reads_are_not_recorded_and_every_write_is(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada, bob = _name("ada"), _name("bob")+ tenant_id = await _workspace(+ session_factory, {ada: ("owner", "org_admin"), bob: ("admin", "member")}+ )+ operator_id = await _operator(session_factory)++ async with _client(_app(session_factory), operator_id, tenant_id) as client:+ current = await client.get("/tenants/current")+ write = await client.patch(+ f"/tenants/{tenant_id}/members/{bob}", json={"role": "member"}+ )++ assert current.status_code == 200, current.text+ assert current.json()["administers"] is True+ assert write.status_code == 200, write.text+ [event] = await _events(session_factory, tenant_id, AuditAction.PLATFORM_ACCESS)+ assert event.details == {+ "event": "write",+ "method": "PATCH",+ "route": "/tenants/{tenant_id}/members/{user_id}",+ }++ async def test_an_operator_there_through_a_role_is_not_marked(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """A self-hosted server's operator is its first organization's+ `org_admin`, and is there as that."""+ operator_id = await _operator(session_factory)+ bob = _name("bob")+ tenant_id = await _workspace(session_factory, {bob: ("admin", "member")})+ async with session_factory() as session:+ tenant = await session.get(Tenant, tenant_id)+ assert tenant is not None and tenant.organization_id is not None+ session.add(+ OrganizationMember(+ organization_id=tenant.organization_id,+ user_id=operator_id,+ role="org_admin",+ )+ )+ await session.commit()++ async with _client(_app(session_factory), operator_id, None) as client:+ await client.post(f"/tenants/{tenant_id}/switch")+ async with _client(_app(session_factory), operator_id, tenant_id) as client:+ write = await client.patch(+ f"/tenants/{tenant_id}/members/{bob}", json={"role": "member"}+ )++ assert write.status_code == 200, write.text+ assert (+ await _events(session_factory, tenant_id, AuditAction.PLATFORM_ACCESS) == []+ )++ async def test_only_the_operator_lists_every_workspace(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ ada = _name("ada")+ tenant_id = await _workspace(session_factory, {ada: ("owner", "org_admin")})+ operator_id = await _operator(session_factory)++ async with _client(_app(session_factory), operator_id, None) as client:+ listed = await client.get("/operator/workspaces")+ async with _client(_app(session_factory), ada, tenant_id) as client:+ refused = await client.get("/operator/workspaces")++ assert listed.status_code == 200, listed.text+ assert tenant_id in {row["id"] for row in listed.json()}+ assert refused.status_code == 403++ async def test_restores_an_org_admin_only_where_there_is_none(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ bob, cy = _name("bob"), _name("cy")+ orphaned = await _workspace(session_factory, {bob: ("owner", "member")})+ governed = await _workspace(+ session_factory,+ {cy: ("owner", "org_admin"), _name("dee"): ("member", "member")},+ )+ operator_id = await _operator(session_factory)++ async with _client(_app(session_factory), operator_id, orphaned) as client:+ restored = await client.patch(+ f"/organizations/current/members/{bob}", json={"role": "org_admin"}+ )+ async with _client(_app(session_factory), operator_id, governed) as client:+ refused = await client.get("/organizations/current/members")++ assert restored.status_code == 200, restored.text+ assert restored.json()["role"] == "org_admin"+ assert refused.status_code == 403+ [event] = await _events(session_factory, orphaned, AuditAction.PLATFORM_ACCESS)+ assert event.details is not None and event.details["method"] == "PATCH"diff --git a/core/tests/switch_core/gateway/test_session_requires_authentication.py b/core/tests/switch_core/gateway/test_session_requires_authentication.pyindex e74ad62df..c6a0e606a 100644--- a/core/tests/switch_core/gateway/test_session_requires_authentication.py+++ b/core/tests/switch_core/gateway/test_session_requires_authentication.py@@ -134,6 +134,10 @@ _ROUTES_THAT_NEVER_BIND_A_TENANT = {# Feature flags belong to the deployment and come from its config, so# there is no workspace to scope them to and no session is opened.("GET", "/feature-flags"),+ # The platform operator's list of every workspace, to enter one from.+ # It opens a `tenant_session` per tenant `all_tenant_ids` names, and+ # answers 403 to anyone but the operator — see `list_every_workspace`.+ ("GET", "/operator/workspaces"),}diff --git a/core/tests/switch_core/gateway/test_workspace_services.py b/core/tests/switch_core/gateway/test_workspace_services.pyindex de7dd45ef..28641c9e0 100644--- a/core/tests/switch_core/gateway/test_workspace_services.py+++ b/core/tests/switch_core/gateway/test_workspace_services.py@@ -181,10 +181,9 @@ class TestWhoMayCall:("admin", "user", 200),("owner", "user", 200),("member", "admin", 200),- # The gateway binds only a workspace the caller belongs to, the- # operator included: the operator bit lifts a member, it does not- # reach into a workspace from outside.- (None, "admin", 403),+ # The operator may enter any workspace, on `platform_access`,+ # which the workspace's audit log records.+ (None, "admin", 200),],ids=["member", "admin", "owner", "operator-as-member", "operator-not-a-member"],)