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
feat(authz): split the deployment-operator bit from tenant-scoped admin
Wojciech Wojtyniaka1d6d26a529a
diff --git a/core/switch_core/authz.py b/core/switch_core/authz.pyindex 9c65903f8..f21eb4947 100644--- a/core/switch_core/authz.py+++ b/core/switch_core/authz.py@@ -8,8 +8,14 @@ Model:- The subject of every decision is a **user** (`Principal`). Agent-initiatedrequests resolve to the agent's owner (see the protocol service's`_resolve_acting_identity`); an agent inherits exactly its owner's- permissions.- - `User.role == "admin"` is a global bypass.+ permissions in the tenant the request is bound to — never more than the+ owner holds there.+ - `Principal.is_admin` means "may administer the tenant bound to this+ request" — the deployment operator bypass (`User.role == "admin"`, global,+ never granted by anything self-service) OR an `owner`/`admin` membership+ row for this user in the bound tenant (`tenant_members.role`, granted per+ tenant, e.g. by creating it). `administers_tenant` below computes it; a+ caller with a database session should use that rather than re-deriving it.- Owned entities carry a nullable owner plus independent `read_visibility`and `write_visibility` ("public" | "private").@@ -38,12 +44,30 @@ class Principal:`id` may be ``None`` for an agent with no owner; such a principal ownsnothing and is limited to public access.++ `is_admin` is tenant-scoped, not global — see `administers_tenant`."""id: str | Noneis_admin: bool+# `tenant_members.role` is a checked string, not an enum type (`db/models.py`).+TENANT_ADMIN_ROLES = ("owner", "admin")+++def administers_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:+ """Whether a caller may administer the tenant they hold `tenant_role` in.++ True for a deployment operator (the global bypass), regardless of+ membership — an operator administers every tenant. Otherwise true only if+ the membership role itself is `owner` or `admin`; a plain `member`, or no+ membership row at all, is false. This is the one function that should ever+ turn a role into an admin bit — see `Principal.is_admin`.+ """+ return is_operator or tenant_role in TENANT_ADMIN_ROLES++@runtime_checkableclass Authorizable(Protocol):"""Structural interface for any entity `can` arbitrates over.diff --git a/core/switch_core/bridges/agent/protocol/service.py b/core/switch_core/bridges/agent/protocol/service.pyindex cac0e1859..14d87b6c9 100644--- a/core/switch_core/bridges/agent/protocol/service.py+++ b/core/switch_core/bridges/agent/protocol/service.py@@ -2308,13 +2308,9 @@ class ProtocolService:)async with self.session_factory() as session:- agent = await self.agent_store.get(session, agent_id)- if agent is None:- raise ValueError(f"Unknown agent: {agent_id}")- owner_is_admin = False- if agent.owner_id is not None:- owner = await session.get(User, agent.owner_id)- owner_is_admin = owner is not None and owner.role == "admin"+ agent, _owner_id, owner_is_admin = await self._resolve_acting_identity(+ session, agent_id+ )group_id = await self._resolve_group_name(session, group_name)if (reference_ids or package_ids) and agent.owner_id is None:raise ValueError(@@ -2463,6 +2459,13 @@ class ProtocolService:Returns ``(agent, owner_id, owner_is_admin)``. Used by moderationmethods that perform resource-access checks on the agent's behalf.++ ``owner_is_admin`` is the owner's tenant-scoped administrative bit+ (``UserStore.administers``), not the global operator flag alone: the+ agent must not gain more than its owner holds in the tenant this+ request is bound to. `session` is already scoped there by the time an+ agent-bridge request reaches this method, so the read is the owner's+ membership in the same tenant the agent itself belongs to."""agent = await self.agent_store.get(session, agent_id)if agent is None:@@ -2470,7 +2473,9 @@ class ProtocolService:owner_is_admin = Falseif agent.owner_id is not None:owner = await session.get(User, agent.owner_id)- owner_is_admin = owner is not None and owner.role == "admin"+ owner_is_admin = owner is not None and await self.user_store.administers(+ session, owner+ )return agent, agent.owner_id, owner_is_adminasync def _require_room_action(diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex a0feea59f..d1e4f6122 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -6,12 +6,14 @@ from sqlalchemy import func, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession+from switch_core.authz import administers_tenantfrom switch_core.db.models import (OidcIdentity,TenantMember,User,require_tenant_id,)+from switch_core.tenant_context import current_tenant_idlogger = logging.getLogger(__name__)@@ -297,3 +299,33 @@ class UserStore:async def get_all(self, session: AsyncSession) -> list[User]:result = await session.execute(select(User))return list(result.scalars().all())++ async def tenant_role(+ self, session: AsyncSession, tenant_id: str, user_id: str+ ) -> str | None:+ """`user_id`'s membership role in `tenant_id`, or None if not a member.++ `TenantMember` is addressed by its whole primary key, so this is a+ plain `session.get` rather than a query — same shape as+ `ensure_membership`'s write.+ """+ membership = await session.get(TenantMember, (tenant_id, user_id))+ return membership.role if membership is not None else None++ async def administers(self, session: AsyncSession, user: User) -> bool:+ """Whether `user` may administer the tenant bound to `session`'s+ context — the operator bypass, or an owner/admin membership in it.++ See `authz.administers_tenant`, which this composes with a read of the+ one membership row that can answer "in *this* tenant". No tenant bound+ answers with the operator bit alone: every gateway request binds one+ by the time this is reachable, and nothing here should insist on a+ precondition that authentication already enforces.+ """+ tenant_id = current_tenant_id()+ role = (+ None+ if tenant_id is None+ else await self.tenant_role(session, tenant_id, user.id)+ )+ return administers_tenant(is_operator=user.role == "admin", tenant_role=role)diff --git a/core/switch_core/gateway/agents.py b/core/switch_core/gateway/agents.pyindex e5316c2e5..b2d908939 100644--- a/core/switch_core/gateway/agents.py+++ b/core/switch_core/gateway/agents.py@@ -79,7 +79,10 @@ async def delete_agent_by_name(if agent is None:raise HTTPException(status_code=404, detail=f"Agent not found: {agent_name}")try:- require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ agent.owner_id,+ )except PermissionError:raise HTTPException(status_code=403,@@ -106,7 +109,10 @@ async def delete_agent(if agent is None:raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")try:- require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ agent.owner_id,+ )except PermissionError:raise HTTPException(status_code=403,@@ -216,7 +222,10 @@ async def register_known_subagents(status_code=404, detail=f"Parent agent not found: {req.parent_agent_id}")try:- require_manage(Principal(user.id, user.role == "admin"), parent.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ parent.owner_id,+ )except PermissionError as exc:raise HTTPException(status_code=403,@@ -317,7 +326,10 @@ async def update_agent_options(raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")try:- require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ agent.owner_id,+ )except PermissionError:raise HTTPException(status_code=403,@@ -370,7 +382,10 @@ async def update_agent_icon(raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")try:- require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ agent.owner_id,+ )except PermissionError:raise HTTPException(status_code=403,@@ -420,7 +435,10 @@ async def update_agent_display_name(raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")try:- require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ agent.owner_id,+ )except PermissionError:raise HTTPException(status_code=403,@@ -509,7 +527,10 @@ async def update_addressing_policy(raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")try:- require_manage(Principal(user.id, user.role == "admin"), agent.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ agent.owner_id,+ )except PermissionError:raise HTTPException(status_code=403,diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 61e14a694..5e4b4b8f6 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -234,11 +234,53 @@ async def get_current_user(async def require_admin(user: Annotated[User, Depends(get_current_user)],) -> User:+ """Raise 403 unless `user` is a deployment operator.++ ``User.role == "admin"`` is deliberately global and deliberately not+ self-service: it names the person who runs the server, not a role any+ tenant can grant. Gate deployment-wide actions on this — creating or+ listing every user in the deployment — never a single tenant's resources.+ Those use ``require_tenant_admin``.+ """if user.role != "admin":raise HTTPException(status_code=403, detail="Admin access required")return user+async def get_tenant_is_admin(+ session: Annotated[AsyncSession, Depends(get_session)],+ user: Annotated[User, Depends(get_current_user)],+ user_store: Annotated[UserStore, Depends(get_user_store)],+) -> bool:+ """Whether `user` may administer the tenant this request is bound to.++ This is the boolean every ``Principal.is_admin`` in a gateway request+ should be built from — see ``UserStore.administers`` for what it actually+ checks.++ Also callable directly (not just as a FastAPI dependency) from any+ handler or service function that already holds a bound `session`, the+ caller's `User`, and a `UserStore`.+ """+ return await user_store.administers(session, user)+++async def require_tenant_admin(+ user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],+) -> User:+ """Raise 403 unless `user` may administer the tenant this request is bound to.++ Unlike ``require_admin``, this is granted by ``tenant_members.role`` as+ well as the operator bit — use it for routes that manage one tenant's+ resources (a collaboration bridge, a room) rather than the deployment+ itself.+ """+ if not is_admin:+ raise HTTPException(status_code=403, detail="Tenant admin access required")+ return user++async def require_room_access(session: AsyncSession,room_store: RoomStore,@@ -257,8 +299,9 @@ async def require_room_access(room = await room_store.get(session, room_id)if room is None:raise HTTPException(status_code=404, detail="Room not found")+ is_admin = await UserStore().administers(session, user)try:- require(Principal(user.id, user.role == "admin"), action, room)+ require(Principal(user.id, is_admin), action, room)except PermissionError as e:raise HTTPException(status_code=403, detail=str(e)) from ereturn roomdiff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex 243d5066c..a7ae7361f 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -21,7 +21,7 @@ from switch_core.db.stores.collaboration_bridge_store import CollaborationBridgefrom switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.gateway.auth import get_current_user, require_admin+from switch_core.gateway.auth import get_current_user, require_tenant_adminfrom switch_core.gateway.dependencies import (get_bridge_store,get_collab_lifecycle,@@ -164,7 +164,7 @@ async def create_bridge(# Admin-only: a bridge is an unowned, workspace-wide integration holding# platform secrets, so there is no owner to scope to (unlike connectors,# whose authz is owner-or-admin) — registering one is an admin action.- _user: Annotated[User, Depends(require_admin)],+ _user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:try:bridge = await collab_lifecycle.register(@@ -202,7 +202,7 @@ async def set_default_bridge(collab_lifecycle: Annotated[CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)],- _user: Annotated[User, Depends(require_admin)],+ _user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:"""Nominate a bridge as the instance default, demoting the previous one."""try:@@ -253,7 +253,7 @@ async def update_bridge(],# Admin-only for the same reason as registering one: a bridge is an unowned,# workspace-wide integration, so there is no owner to scope mutation to.- _user: Annotated[User, Depends(require_admin)],+ _user: Annotated[User, Depends(require_tenant_admin)],) -> BridgeDetail:bridge = await bridge_store.get(session, bridge_id)if bridge is None:@@ -548,7 +548,7 @@ async def claim_bridge_identity(raise HTTPException(status_code=404, detail="Bridge not found")target_user_id = payload.user_id or user.id- if target_user_id != user.id and user.role != "admin":+ if target_user_id != user.id and not await user_store.administers(session, user):raise HTTPException(status_code=403,detail="Only an admin may claim a messaging identity for another user",@@ -644,7 +644,7 @@ async def release_bridge_identity(raise HTTPException(status_code=404, detail="Identity not found")target_user_id = user_id or user.id- if target_user_id != user.id and user.role != "admin":+ if target_user_id != user.id and not await user_store.administers(session, user):raise HTTPException(status_code=403,detail="Only an admin may release another user's messaging identity",@@ -676,7 +676,7 @@ async def delete_bridge(],# Admin-only: deleting a bridge cascades into deleting every room on it, so# this is the most destructive operation on the router.- _user: Annotated[User, Depends(require_admin)],+ _user: Annotated[User, Depends(require_tenant_admin)],) -> dict[str, bool]:bridge = await bridge_store.get(session, bridge_id)if bridge is None:diff --git a/core/switch_core/gateway/connectors.py b/core/switch_core/gateway/connectors.pyindex 94b186edf..f21f7ea8f 100644--- a/core/switch_core/gateway/connectors.py+++ b/core/switch_core/gateway/connectors.py@@ -12,6 +12,7 @@ from switch_core.bridges.agent.server_connectors.lifecycle import (from switch_core.db.models import Userfrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.server_connector_store import ServerConnectorStore+from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import get_current_userfrom switch_core.gateway.dependencies import (get_api_key_store,@@ -137,10 +138,11 @@ async def delete_connector(raise HTTPException(status_code=404, detail="Connector not found")reg_key = await api_key_store.get(session, record.api_key_id)- if (reg_key is None or reg_key.user_id != user.id) and user.role != "admin":- raise HTTPException(- status_code=403, detail="Not authorized to delete this connector"- )+ if reg_key is None or reg_key.user_id != user.id:+ if not await UserStore().administers(session, user):+ raise HTTPException(+ status_code=403, detail="Not authorized to delete this connector"+ )try:await connector_lifecycle.remove(connector_id)diff --git a/core/switch_core/gateway/documents.py b/core/switch_core/gateway/documents.pyindex 8a6301244..998b7ca17 100644--- a/core/switch_core/gateway/documents.py+++ b/core/switch_core/gateway/documents.py@@ -10,7 +10,11 @@ from switch_core.db.models import Document, Userfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.room_store import RoomStorefrom switch_core.db.stores.user_store import UserStore-from switch_core.gateway.auth import get_current_user, require_room_access+from switch_core.gateway.auth import (+ get_current_user,+ get_tenant_is_admin,+ require_room_access,+)from switch_core.gateway.dependencies import (get_agent_store,get_resource_service,@@ -200,10 +204,11 @@ async def get_document(user_store: Annotated[UserStore, Depends(get_user_store)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> DocumentDetail:try:doc = await resource_service.get_document_for_user(- session, document_id, user.id, is_admin=user.role == "admin"+ session, document_id, user.id, is_admin=is_admin)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -221,13 +226,14 @@ async def patch_document(user_store: Annotated[UserStore, Depends(get_user_store)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> DocumentDetail:try:doc = await resource_service.update_document(session,document_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=is_admin,name=req.name,description=req.description,instructions=req.instructions,@@ -249,6 +255,7 @@ async def delete_document(session: Annotated[AsyncSession, Depends(get_session)],resource_service: Annotated[ResourceService, Depends(get_resource_service)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> DocumentDeleteResponse:affected_packages = await resource_service.list_packages_for_document(session, document_id@@ -258,7 +265,7 @@ async def delete_document(session,document_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -278,10 +285,11 @@ async def list_rooms_for_document(session: Annotated[AsyncSession, Depends(get_session)],resource_service: Annotated[ResourceService, Depends(get_resource_service)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[ResourceRoom]:try:await resource_service.get_document_for_user(- session, document_id, user.id, is_admin=user.role == "admin"+ session, document_id, user.id, is_admin=is_admin)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -318,6 +326,7 @@ async def attach_document_to_room(agent_store: Annotated[AgentStore, Depends(get_agent_store)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> DocumentDetail:await require_room_access(session, room_store, room_id, user, "write")try:@@ -326,7 +335,7 @@ async def attach_document_to_room(room_id,document_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -334,7 +343,7 @@ async def attach_document_to_room(raise HTTPException(status_code=403, detail=str(e)) from eawait session.commit()doc = await resource_service.get_document_for_user(- session, document_id, user.id, is_admin=user.role == "admin"+ session, document_id, user.id, is_admin=is_admin)return await _enrich_detail(session, doc, resource_service, user_store, agent_store)diff --git a/core/switch_core/gateway/packages.py b/core/switch_core/gateway/packages.pyindex 0ae22d56b..ed3cdc9b2 100644--- a/core/switch_core/gateway/packages.py+++ b/core/switch_core/gateway/packages.py@@ -143,7 +143,10 @@ async def get_package() -> PackageDetail:try:pkg = await resource_service.get_package_for_user(- session, package_id, user.id, is_admin=user.role == "admin"+ session,+ package_id,+ user.id,+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -166,7 +169,7 @@ async def patch_package(session,package_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await UserStore().administers(session, user),name=req.name,description=req.description,instructions=req.instructions,@@ -193,7 +196,7 @@ async def delete_package(session,package_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -212,7 +215,10 @@ async def list_rooms_for_package() -> list[ResourceRoom]:try:await resource_service.get_package_for_user(- session, package_id, user.id, is_admin=user.role == "admin"+ session,+ package_id,+ user.id,+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -235,7 +241,10 @@ async def list_package_references() -> list[ReferenceDetail]:try:await resource_service.get_package_for_user(- session, package_id, user.id, is_admin=user.role == "admin"+ session,+ package_id,+ user.id,+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -259,7 +268,7 @@ async def add_reference_to_package(package_id,reference_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -282,7 +291,7 @@ async def remove_reference_from_package(package_id,reference_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -308,7 +317,10 @@ async def list_package_documents() -> list[DocumentSummary]:try:await resource_service.get_package_for_user(- session, package_id, user.id, is_admin=user.role == "admin"+ session,+ package_id,+ user.id,+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -334,7 +346,7 @@ async def add_document_to_package(package_id,document_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -357,7 +369,7 @@ async def remove_document_from_package(package_id,document_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -406,7 +418,7 @@ async def attach_package_to_room(room_id,package_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await UserStore().administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -414,7 +426,10 @@ async def attach_package_to_room(raise HTTPException(status_code=403, detail=str(e)) from eawait session.commit()pkg = await resource_service.get_package_for_user(- session, package_id, user.id, is_admin=user.role == "admin"+ session,+ package_id,+ user.id,+ is_admin=await UserStore().administers(session, user),)return await _enrich_one(session, pkg, resource_service, user_store)diff --git a/core/switch_core/gateway/references.py b/core/switch_core/gateway/references.pyindex 9b5e0979a..7d80b3fa2 100644--- a/core/switch_core/gateway/references.py+++ b/core/switch_core/gateway/references.py@@ -167,7 +167,7 @@ async def list_reference_types(user: Annotated[User, Depends(get_current_user)],) -> list[ReferenceTypeInfo]:views = await resource_service.list_reference_types_for_principal(- session, user_id=user.id, is_admin=user.role == "admin"+ session, user_id=user.id, is_admin=await user_store.administers(session, user))owners = await _owner_names(session, user_store, {v.owner_id for v in views if v.owner_id is not None}@@ -186,7 +186,7 @@ async def list_owned_reference_types(user: Annotated[User, Depends(get_current_user)],) -> list[ReferenceTypeDetail]:rows = await resource_service.list_owned_reference_types(- session, user_id=user.id, is_admin=user.role == "admin"+ session, user_id=user.id, is_admin=await user_store.administers(session, user))owners = await _owner_names(session, user_store, {e.row.owner_id for e in rows})return [_type_to_detail(e, owners.get(e.row.owner_id)) for e in rows]@@ -235,7 +235,7 @@ async def patch_reference_type(session,type,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await user_store.administers(session, user),display_name=req.display_name,instructions=req.instructions,value_hint=req.value_hint,@@ -259,11 +259,15 @@ async def delete_reference_type(type: str,session: Annotated[AsyncSession, Depends(get_session)],resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],) -> ReferenceTypeDeleteResponse:try:await resource_service.delete_reference_type(- session, type, user_id=user.id, is_admin=user.role == "admin"+ session,+ type,+ user_id=user.id,+ is_admin=await user_store.administers(session, user),)except ReferenceTypeInUseError as e:raise HTTPException(status_code=409, detail=str(e)) from e@@ -298,7 +302,7 @@ async def create_reference(ref = await resource_service.create_reference(session,owner_id=user.id,- is_admin=user.role == "admin",+ is_admin=await user_store.administers(session, user),read_visibility=req.read_visibility,write_visibility=req.write_visibility,type=req.type,@@ -323,7 +327,10 @@ async def get_reference() -> ReferenceDetail:try:ref = await resource_service.get_reference_for_user(- session, reference_id, user.id, is_admin=user.role == "admin"+ session,+ reference_id,+ user.id,+ is_admin=await user_store.administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -346,7 +353,7 @@ async def patch_reference(session,reference_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await user_store.administers(session, user),name=req.name,description=req.description,instructions=req.instructions,@@ -367,6 +374,7 @@ async def delete_reference(reference_id: str,session: Annotated[AsyncSession, Depends(get_session)],resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],) -> ReferenceDeleteResponse:affected_packages = await resource_service.list_packages_for_reference(@@ -377,7 +385,7 @@ async def delete_reference(session,reference_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=await user_store.administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -396,11 +404,15 @@ async def list_rooms_for_reference(reference_id: str,session: Annotated[AsyncSession, Depends(get_session)],resource_service: Annotated[ResourceService, Depends(get_resource_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],) -> list[ResourceRoom]:try:await resource_service.get_reference_for_user(- session, reference_id, user.id, is_admin=user.role == "admin"+ session,+ reference_id,+ user.id,+ is_admin=await user_store.administers(session, user),)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -436,12 +448,13 @@ async def attach_reference_to_room() -> ReferenceDetail:await require_room_access(session, room_store, room_id, user, "write")try:+ is_admin = await user_store.administers(session, user)await resource_service.attach_reference_to_room(session,room_id,reference_id,user_id=user.id,- is_admin=user.role == "admin",+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -449,7 +462,7 @@ async def attach_reference_to_room(raise HTTPException(status_code=403, detail=str(e)) from eawait session.commit()ref = await resource_service.get_reference_for_user(- session, reference_id, user.id, is_admin=user.role == "admin"+ session, reference_id, user.id, is_admin=is_admin)return await _enrich_one(session, ref, resource_service, user_store)diff --git a/core/switch_core/gateway/room_groups.py b/core/switch_core/gateway/room_groups.pyindex 70a3ca729..6d922673b 100644--- a/core/switch_core/gateway/room_groups.py+++ b/core/switch_core/gateway/room_groups.py@@ -9,6 +9,7 @@ from switch_core.authz import Principal, requirefrom switch_core.db.models import RoomGroup, Userfrom switch_core.db.stores.room_group_store import RoomGroupStorefrom switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.auth import get_current_userfrom switch_core.gateway.dependencies import (get_room_group_store,@@ -115,7 +116,7 @@ async def assign_rooms_to_group(if await room_group_store.get(session, group_id) is None:raise HTTPException(status_code=404, detail="Room group not found")- principal = Principal(user.id, user.role == "admin")+ principal = Principal(user.id, await UserStore().administers(session, user))forbidden: list[str] = []allowed: list[str] = []for room_id in req.room_ids:diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex 061b6faeb..5cdfad042 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -72,7 +72,11 @@ async def _require_room(if room is None:raise HTTPException(status_code=404, detail="Room not found")try:- require(Principal(user.id, user.role == "admin"), action, room)+ require(+ Principal(user.id, await UserStore().administers(session, user)),+ action,+ room,+ )except PermissionError as e:raise HTTPException(status_code=403, detail=str(e)) from ereturn room@@ -244,7 +248,7 @@ async def list_rooms(rooms = await room_store.list_readable(session,user.id,- is_admin=user.role == "admin",+ is_admin=await user_store.administers(session, user),include_archived=include_archived,)@@ -371,7 +375,9 @@ async def create_room(@router.post("/from-yaml", status_code=201)async def create_room_from_yaml(request: Request,+ session: Annotated[AsyncSession, Depends(get_session)],rooms_yaml: Annotated[RoomYamlService, Depends(get_room_yaml_service)],+ user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],) -> ProvisionResult:"""Provision a single room and its attachments from a YAML spec.@@ -400,7 +406,7 @@ async def create_room_from_yaml(inputs = Nonespec = rooms_yaml.parse(text, inputs=inputs)return await rooms_yaml.provision(- spec, user_id=user.id, is_admin=user.role == "admin"+ spec, user_id=user.id, is_admin=await user_store.administers(session, user))except ValueError as e:raise HTTPException(status_code=400, detail=str(e)) from e@@ -847,9 +853,10 @@ async def bulk_delete_rooms(session: Annotated[AsyncSession, Depends(get_session)],room_service: Annotated[RoomService, Depends(get_room_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],+ user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],) -> BulkDeleteResponse:- principal = Principal(user.id, user.role == "admin")+ principal = Principal(user.id, await user_store.administers(session, user))deleted = 0for room_id in req.room_ids:room = await room_store.get(session, room_id)@@ -872,12 +879,13 @@ async def bulk_archive_rooms(session: Annotated[AsyncSession, Depends(get_session)],room_service: Annotated[RoomService, Depends(get_room_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],+ user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],) -> BulkArchiveResponse:"""Archive or unarchive many rooms at once. Each room is authorizedindividually with the same `write` check as the single archive endpoint;rooms the caller cannot write (or that no longer exist) are skipped."""- principal = Principal(user.id, user.role == "admin")+ principal = Principal(user.id, await user_store.administers(session, user))updated = 0for room_id in req.room_ids:room = await room_store.get(session, room_id)diff --git a/core/switch_core/gateway/templates.py b/core/switch_core/gateway/templates.pyindex 43ac1abd5..60c4917c9 100644--- a/core/switch_core/gateway/templates.py+++ b/core/switch_core/gateway/templates.py@@ -164,7 +164,10 @@ async def _load_for_management(status_code=404, detail=f"Template not found: {template_id}")try:- require_manage(Principal(user.id, user.role == "admin"), template.owner_id)+ require_manage(+ Principal(user.id, await UserStore().administers(session, user)),+ template.owner_id,+ )except PermissionError as e:raise HTTPException(status_code=403, detail=str(e)) from ereturn templatediff --git a/core/switch_core/migrations/versions/8ef6d4038ecc_operator_owns_tenant_zero.py b/core/switch_core/migrations/versions/8ef6d4038ecc_operator_owns_tenant_zero.pynew file mode 100644index 000000000..ac4150c07--- /dev/null+++ b/core/switch_core/migrations/versions/8ef6d4038ecc_operator_owns_tenant_zero.py@@ -0,0 +1,93 @@+"""operator/workspace-admin role split: the seeded administrator becomes an owner of tenant zero++Revision ID: 8ef6d4038ecc+Revises: a3f61c02d5be+Create Date: 2026-09-11 00:00:00.000000++Phase 2 of multi-tenancy (`docs/old/multi-tenancy-phase2-tenants.md`, §2)+starts reading `tenant_members.role` instead of leaving it inert:+`authz.Principal.is_admin` now grants tenant-scoped administrative power to a+caller whose membership role in the bound tenant is `owner`/`admin`, not only+to the deployment operator bit (`users.role == "admin"`, still global, still+an unconditional bypass, still never self-service).++That bypass is exactly why this migration is not a lockout fix. An operator+administers every tenant regardless of what `tenant_members` says about them,+before this change and after it — nothing here can strand an operator out of+their own deployment, because nothing here is what lets them in. What this+migration fixes is a *label*: a deployment whose operator's own membership+row still says `member` would show that operator as a guest of the tenant+they administer, in any future member listing or ownership check that reads+`tenant_members` instead of going through `authz`. Correcting it now, once,+means that surface can be built later without also auditing every deployment+that upgraded before it existed.++Two ways an operator's row can already disagree with `owner`:++- The Phase 1 schema migration (`8b276792ee30`) backfilled `owner` for every+ user whose `role` was `admin` at the time it ran, and `member` for everyone+ else. It cannot see a promotion that happened after.+- `UserStore.ensure_membership` writes a membership exactly once, at account+ creation, deriving its role from `users.role` at that moment. Promoting an+ account to `admin` afterwards — a direct database edit, since there is no+ gateway endpoint for it (`multi-tenancy-phase2-tenants.md` §8) — never+ revisits the row that promotion left behind.++So every user with `users.role = 'admin'` gets an `owner` row in tenant zero:+updated in place if their row there is `member`, inserted if they have no row+there at all. The `INSERT` covers a state the two paths above should not be+able to produce today (`ensure_membership` runs inside `UserStore.create`,+which never leaves an account without one) but which nothing enforces at the+database level — cheaper to close here than to assume.++Nothing else moves. A non-operator's row is left exactly as it is, matching+this phase's stated invariant that anyone with a single membership and no+operator bit sees no behavioural change from this release. Only tenant zero+is touched: it is the only tenant that can exist in a deployment old enough+to need this migration at all.++Idempotent: re-running it updates nothing the first run did not already fix,+and inserts nothing that already exists.+"""++from collections.abc import Sequence++from alembic import op++revision: str = "8ef6d4038ecc"+down_revision: str | None = "a3f61c02d5be"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++TENANT_ZERO_ID = "00000000-0000-0000-0000-000000000000"+++def upgrade() -> None:+ op.execute(+ f"""+ UPDATE tenant_members+ SET role = 'owner'+ WHERE tenant_id = '{TENANT_ZERO_ID}'+ AND role NOT IN ('owner', 'admin')+ AND user_id IN (SELECT id FROM users WHERE role = 'admin')+ """+ )+ op.execute(+ f"""+ INSERT INTO tenant_members (tenant_id, user_id, role)+ SELECT '{TENANT_ZERO_ID}', u.id, 'owner'+ FROM users u+ WHERE u.role = 'admin'+ AND NOT EXISTS (+ SELECT 1 FROM tenant_members tm+ WHERE tm.tenant_id = '{TENANT_ZERO_ID}' AND tm.user_id = u.id+ )+ """+ )+++def downgrade() -> None:+ # Not reversible: the rows this corrected were indistinguishable from an+ # ordinary `owner` row the moment it ran, and rows it inserted have no+ # prior state to restore — there was no row there before.+ passdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.pynew file mode 100644index 000000000..c684b3d6f--- /dev/null+++ b/core/tests/switch_core/bridges/agent/protocol/test_agent_tenant_scoped_admin.py@@ -0,0 +1,211 @@+"""An agent inherits exactly its owner's tenant-scoped power, never more+(CHOO-2726 role split, phase 2 design §2).++``_resolve_acting_identity`` used to compute ``owner_is_admin`` from+``owner.role == "admin"`` alone — the same global bit every other admin check+in the codebase used before this split. Once a person can hold ``owner`` in+one tenant and merely ``member`` (or nothing) in another, that global read is+wrong for an agent the same way it was wrong for a human acting directly: an+agent must not administer a tenant its owner does not administer, and must+administer one its owner does, purely because of the owner's role in *that*+tenant rather than any global bit.++``test_agent_administers_the_tenant_its_owner_owns`` is the one that actually+distinguishes old from new: the owner here holds no global admin bit at all,+so the pre-split code (`owner.role == "admin"`) denies it regardless of the+`tenant_members` row, and only reading that row grants it. The other two+tests hold under both the old and new code — they pin down that the fix does+not *overreach* (a workspace owner's agent must not gain cross-tenant power,+and a global operator's agent must not lose its bypass) rather than proving a+new grant.+"""++from __future__ import annotations++from types import SimpleNamespace++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.protocol.service import ProtocolService+from switch_core.bridges.agent.protocol.types import (+ IntegrationProfile,+ TaskProtocolConfig,+)+from switch_core.db.models import (+ TENANT_ZERO_ID,+ Client,+ Room,+ Tenant,+ TenantMember,+ User,+)+from switch_core.db.stores.agent_store import AgentStore+from switch_core.db.stores.api_key_store import ApiKeyStore+from switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.user_store import UserStore+from switch_core.tenant_context import tenant_scope++TENANT_B = "tenant-b"++_PROFILE = IntegrationProfile(+ connection_model="session_passive",+ message_exchange=True,+ pre_invocation_mediation=[],+ post_invocation_mediation=[],+ event_reporting=[],+ task_protocol=TaskProtocolConfig(can_delegate=False, can_accept=False),+)+++class _FakeClientLifecycle:+ def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:+ self._session_factory = session_factory++ async def create_client(self, *, client_type: str, display_name: str) -> Client:+ async with self._session_factory() as session:+ client = Client(+ matrix_user_id=f"@{display_name}:test",+ display_name=display_name,+ type=client_type,+ )+ session.add(client)+ await session.commit()+ return client++ def start_client(self, client: Client) -> None:+ pass+++class _NoBridges:+ def all_bridges(self) -> list[object]:+ return []+++def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolService:+ svc = object.__new__(ProtocolService)+ svc.session_factory = session_factory # type: ignore[attr-defined]+ svc.agent_store = AgentStore() # type: ignore[attr-defined]+ svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]+ svc.room_store = RoomStore() # type: ignore[attr-defined]+ svc.user_store = UserStore() # type: ignore[attr-defined]+ svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]+ svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]+ svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]+ return svc+++async def _make_user(+ session_factory: async_sessionmaker[AsyncSession], name: str, *, role: str = "user"+) -> str:+ async with session_factory() as session:+ user = User(name=name, email=f"{name}@test", role=role, password_hash="x")+ session.add(user)+ await session.commit()+ return user.id+++async def _make_tenant(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str+) -> None:+ async with session_factory() as session:+ session.add(Tenant(id=tenant_id, slug=tenant_id, name=tenant_id))+ await session.commit()+++async def _membership(+ session_factory: async_sessionmaker[AsyncSession],+ tenant_id: str,+ user_id: str,+ role: str,+) -> None:+ async with session_factory() as session:+ session.add(TenantMember(tenant_id=tenant_id, user_id=user_id, role=role))+ await session.commit()+++async def _register(svc: ProtocolService, name: str, owner_id: str) -> str:+ result = await svc.register_agent(+ name=name,+ description=f"{name} desc",+ connector_type="test",+ integration_profile=_PROFILE,+ owner_id=owner_id,+ )+ return result.agent_id+++async def _private_room(+ session_factory: async_sessionmaker[AsyncSession], tenant_id: str, owner_id: str+) -> str:+ async with session_factory() as session:+ room = Room(+ tenant_id=tenant_id,+ matrix_room_id=f"!{tenant_id}-private:test",+ name="private",+ description="",+ owner_id=owner_id,+ read_visibility="private",+ write_visibility="private",+ )+ session.add(room)+ await session.commit()+ return room.id+++class TestAgentInheritsOwnerTenantScopedAdmin:+ async def test_agent_administers_the_tenant_its_owner_owns(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The owner holds no global admin bit — only `owner` in the bound+ tenant. Only reading `tenant_members` (not `users.role`) can grant+ this, so this is the one test that fails against the pre-split code.+ """+ svc = _service(session_factory)+ owner = await _make_user(session_factory, "workspace-owner")+ await _membership(session_factory, TENANT_ZERO_ID, owner, "owner")+ someone_else = await _make_user(session_factory, "tenant-zero-room-owner")+ agent_id = await _register(svc, "owner-agent", owner)+ room_id = await _private_room(session_factory, TENANT_ZERO_ID, someone_else)++ async with session_factory() as session:+ room = await svc._require_room_action(session, agent_id, room_id, "write")+ assert room.id == room_id++ async def test_agent_cannot_administer_a_tenant_where_owner_is_only_a_member(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """Same owner, same agent: `owner` in tenant zero grants nothing in+ tenant B, where that owner only holds `member`."""+ svc = _service(session_factory)+ await _make_tenant(session_factory, TENANT_B)+ owner = await _make_user(session_factory, "cross-tenant-owner")+ await _membership(session_factory, TENANT_ZERO_ID, owner, "owner")+ await _membership(session_factory, TENANT_B, owner, "member")+ someone_else = await _make_user(session_factory, "tenant-b-room-owner")+ agent_id = await _register(svc, "cross-tenant-agent", owner)+ room_id = await _private_room(session_factory, TENANT_B, someone_else)++ async with session_factory() as session:+ with tenant_scope(TENANT_B), pytest.raises(PermissionError):+ await svc._require_room_action(session, agent_id, room_id, "write")++ async def test_operator_owned_agent_administers_every_tenant(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ """The deployment-operator bypass is unconditional and still applies+ through an agent, in a tenant the operator holds no membership in at+ all."""+ svc = _service(session_factory)+ await _make_tenant(session_factory, TENANT_B)+ operator = await _make_user(session_factory, "operator", role="admin")+ someone_else = await _make_user(session_factory, "tenant-b-room-owner-2")+ agent_id = await _register(svc, "operator-agent", operator)+ room_id = await _private_room(session_factory, TENANT_B, someone_else)++ async with session_factory() as session:+ with tenant_scope(TENANT_B):+ room = await svc._require_room_action(+ session, agent_id, room_id, "write"+ )+ assert room.id == room_iddiff --git a/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.py b/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.pyindex 592a1a080..28a9aca9e 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_list_all_references.py@@ -26,6 +26,7 @@ from switch_core.db.stores.package_store import PackageStorefrom switch_core.db.stores.reference_store import ReferenceStorefrom switch_core.db.stores.reference_type_store import ReferenceTypeStorefrom switch_core.db.stores.room_link_store import RoomLinkStore+from switch_core.db.stores.user_store import UserStoreT_OLD = datetime(2024, 1, 1, 12, 0, tzinfo=UTC)@@ -50,6 +51,7 @@ def _build_service(svc.connections = ConnectionRegistry()svc.session_factory = session_factory # type: ignore[assignment]svc.agent_store = _FakeAgentStore(owners) # type: ignore[assignment]+ svc.user_store = UserStore() # type: ignore[assignment]svc.resource_service = ResourceService(reference_store=ReferenceStore(),reference_type_store=ReferenceTypeStore(),diff --git a/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.py b/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.pyindex c79dd480e..7ed73cae0 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_reference_type_parity.py@@ -5,10 +5,10 @@ pins them to the same answer for the same principal: a filter added to one andnot the other is a drift bug that no other test would catch.`ProtocolService.__init__` takes 17 required collaborators, so the service is-built with `object.__new__` and the three attributes this method touches, per+built with `object.__new__` and the four attributes this method touches, per`test_agent_detail_mcp_tools.py`. `_resolve_acting_identity` loads the owner-with `session.get(User, ...)` on the live session rather than through-`user_store`, so no `user_store` is needed here.+with `session.get(User, ...)` on the live session, then reads+`user_store.administers` for the owner's tenant-scoped admin bit."""from __future__ import annotations@@ -52,6 +52,7 @@ def _protocol_service(svc.session_factory = session_factory # type: ignore[attr-defined]svc.agent_store = AgentStore() # type: ignore[attr-defined]svc.resource_service = resource_service # type: ignore[attr-defined]+ svc.user_store = _USER_STORE # type: ignore[attr-defined]return svcdiff --git a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.pyindex d25f710ee..3ef918b1f 100644--- a/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py+++ b/core/tests/switch_core/bridges/agent/protocol/test_room_roster_authz.py@@ -24,6 +24,7 @@ from switch_core.db.models import Client, Room, Userfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.db.stores.api_key_store import ApiKeyStorefrom switch_core.db.stores.room_store import RoomStore+from switch_core.db.stores.user_store import UserStore_PROFILE = IntegrationProfile(connection_model="session_passive",@@ -65,6 +66,7 @@ def _service(session_factory: async_sessionmaker[AsyncSession]) -> ProtocolServisvc.agent_store = AgentStore() # type: ignore[attr-defined]svc.api_key_store = ApiKeyStore() # type: ignore[attr-defined]svc.room_store = RoomStore() # type: ignore[attr-defined]+ svc.user_store = UserStore() # type: ignore[attr-defined]svc.client_lifecycle = _FakeClientLifecycle(session_factory) # type: ignore[attr-defined]svc.collab_lifecycle = _NoBridges() # type: ignore[attr-defined]svc.config = SimpleNamespace(jwt_secret_key="test-secret") # type: ignore[attr-defined]diff --git a/core/tests/switch_core/db/test_tenant_admin_role_split.py b/core/tests/switch_core/db/test_tenant_admin_role_split.pynew file mode 100644index 000000000..c76cabcc1--- /dev/null+++ b/core/tests/switch_core/db/test_tenant_admin_role_split.py@@ -0,0 +1,229 @@+"""The operator/workspace-admin role split (CHOO-2726, phase 2 design §2).++Before this change, `authz.Principal.is_admin` came from `users.role ==+"admin"` alone — a global bit that `tenant_members.role` never fed into. So a+workspace's `owner` membership row granted nothing: every admin-gated route+checked the global bit, never the caller's role in the tenant the request is+bound to.++These tests pin the four behavioural claims that split makes true:++- a workspace `owner` can administer resources in *their own* tenant;+- the same person has no such power in a tenant they only hold a `member`+ row in — `UserStore.administers` must read the *bound* tenant's row, not+ any row belonging to the caller;+- a deployment operator (`users.role == "admin"`) keeps its unconditional+ bypass regardless of what `tenant_members` says, in every tenant, with or+ without a membership row at all;+- a plain `member` with no operator bit gains nothing.++Each is proven both at the pure-decision level (`authz.administers_tenant`,+covered in `test_authz.py`) and here, against a real Postgres session and a+real `tenant_members` row, through `UserStore.administers` — the one place+that turns "who is this" plus "what tenant is bound" into that bit — and+through `authz.can` on a real `Room`, so the wiring from a membership row to+an actual resource decision is exercised end to end, not just the boolean.+"""++from __future__ import annotations++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.authz import Principal, can+from switch_core.db.models import TENANT_ZERO_ID, Room, Tenant, TenantMember, User+from switch_core.db.stores.user_store import UserStore+from switch_core.tenant_context import tenant_scope++TENANT_B = "tenant-b"+++async def _make_user(session: AsyncSession, name: str, *, role: str = "user") -> User:+ user = User(+ name=name, email=f"{name}@example.invalid", role=role, password_hash="x"+ )+ session.add(user)+ await session.flush()+ return user+++async def _make_tenant(session: AsyncSession, tenant_id: str) -> Tenant:+ tenant = Tenant(id=tenant_id, slug=tenant_id, name=tenant_id)+ session.add(tenant)+ await session.flush()+ return tenant+++async def _membership(+ session: AsyncSession, tenant_id: str, user_id: str, role: str+) -> None:+ session.add(TenantMember(tenant_id=tenant_id, user_id=user_id, role=role))+ await session.flush()+++class TestUserStoreAdministers:+ async def test_owner_administers_their_own_tenant(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ owner = await _make_user(session, "owner-of-zero")+ await _membership(session, TENANT_ZERO_ID, owner.id, "owner")+ await session.commit()++ # Ambient tenant is TENANT_ZERO_ID (see conftest.session_factory).+ assert await store.administers(session, owner) is True++ async def test_owner_has_no_power_in_a_tenant_they_only_belong_to_as_member(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Two sessions, one per tenant: `TenantCheckedSession` stamps a+ # session's transaction with whichever tenant is bound when it opens+ # and refuses to let it drift mid-transaction+ # (`db/tenant_session.py`), the same guard that would catch a request+ # rebinding a session it did not open scoped. A real cross-tenant+ # comparison goes through two sessions for the same reason.+ store = UserStore()+ async with session_factory() as session:+ tenant_b = await _make_tenant(session, TENANT_B)+ owner = await _make_user(session, "cross-tenant-owner")+ await _membership(session, TENANT_ZERO_ID, owner.id, "owner")+ await _membership(session, tenant_b.id, owner.id, "member")+ await session.commit()++ assert await store.administers(session, owner) is True++ with tenant_scope(tenant_b.id):+ async with session_factory() as session_b:+ assert await store.administers(session_b, owner) is False++ async def test_admin_membership_role_also_administers(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ admin_member = await _make_user(session, "admin-of-zero")+ await _membership(session, TENANT_ZERO_ID, admin_member.id, "admin")+ await session.commit()++ assert await store.administers(session, admin_member) is True++ async def test_operator_bypasses_regardless_of_tenant_membership(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ tenant_b = await _make_tenant(session, TENANT_B)+ operator = await _make_user(session, "operator", role="admin")+ # A plain member in tenant zero...+ await _membership(session, TENANT_ZERO_ID, operator.id, "member")+ await session.commit()++ assert await store.administers(session, operator) is True++ # ...and no membership row at all in tenant B — a fresh session bound+ # there, per the note above.+ with tenant_scope(tenant_b.id):+ async with session_factory() as session_b:+ assert await store.administers(session_b, operator) is True++ async def test_plain_member_gains_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ member = await _make_user(session, "plain-member")+ await _membership(session, TENANT_ZERO_ID, member.id, "member")+ await session.commit()++ assert await store.administers(session, member) is False++ async def test_no_membership_row_in_the_bound_tenant_gains_nothing(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ stray = await _make_user(session, "no-membership")+ await session.commit()++ assert await store.administers(session, stray) is False+++class TestRoomAuthzThroughTenantRole:+ """The same claims, one layer up: a real `authz.can` decision on a real+ `Room` neither party personally owns, built from `UserStore.administers`+ the way `gateway/rooms.py` and `gateway/auth.py` build it."""++ async def test_workspace_owner_can_delete_a_room_they_do_not_personally_own(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ owner = await _make_user(session, "room-admin-owner")+ someone_else = await _make_user(session, "room-creator")+ await _membership(session, TENANT_ZERO_ID, owner.id, "owner")+ room = Room(+ tenant_id=TENANT_ZERO_ID,+ matrix_room_id="!private-room:test",+ name="private room",+ description="desc",+ owner_id=someone_else.id,+ read_visibility="private",+ write_visibility="private",+ )+ session.add(room)+ await session.commit()++ principal = Principal(owner.id, await store.administers(session, owner))+ assert can(principal, "delete", room)++ async def test_workspace_owner_cannot_delete_the_same_room_from_another_tenant(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ tenant_b = await _make_tenant(session, TENANT_B)+ owner = await _make_user(session, "room-admin-owner-2")+ someone_else = await _make_user(session, "room-creator-2")+ await _membership(session, TENANT_ZERO_ID, owner.id, "owner")+ await _membership(session, tenant_b.id, owner.id, "member")+ room = Room(+ tenant_id=TENANT_ZERO_ID,+ matrix_room_id="!private-room-2:test",+ name="private room",+ description="desc",+ owner_id=someone_else.id,+ read_visibility="private",+ write_visibility="private",+ )+ session.add(room)+ await session.commit()++ with tenant_scope(tenant_b.id):+ async with session_factory() as session_b:+ principal = Principal(+ owner.id, await store.administers(session_b, owner)+ )+ assert not can(principal, "delete", room)++ async def test_plain_member_cannot_delete_a_room_they_do_not_own(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ store = UserStore()+ async with session_factory() as session:+ member = await _make_user(session, "room-member")+ someone_else = await _make_user(session, "room-creator-3")+ await _membership(session, TENANT_ZERO_ID, member.id, "member")+ room = Room(+ tenant_id=TENANT_ZERO_ID,+ matrix_room_id="!private-room-3:test",+ name="private room",+ description="desc",+ owner_id=someone_else.id,+ read_visibility="private",+ write_visibility="private",+ )+ session.add(room)+ await session.commit()++ principal = Principal(member.id, await store.administers(session, member))+ assert not can(principal, "delete", room)diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.pyindex f71fb8186..400f3c417 100644--- a/core/tests/switch_core/gateway/test_collaborations_authz.py+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py@@ -10,9 +10,10 @@ bridge administration through the already admin-gatedThese tests lock in three properties:1. `/collab` is gone — not in the auth-bypass list, and its modules deleted.-2. Every collaboration write route on the gateway requires an admin (the- route dependency is `require_admin`), and every route requires at least- authentication.+2. Every collaboration write route on the gateway requires a tenant admin (the+ route dependency is `require_tenant_admin` — a collaboration bridge is+ tenant-scoped, so this is workspace administration, not the deployment+ operator bit), and every route requires at least authentication.3. The new set-default behaviour is correct against real Postgres."""@@ -31,7 +32,7 @@ from switch_core.bridges.collaboration.models import DirectoryUserfrom switch_core.db.models import Client, CollaborationBridge, Userfrom switch_core.db.stores.collaboration_bridge_store import CollaborationBridgeStorefrom switch_core.db.stores.room_store import RoomStore-from switch_core.gateway.auth import get_current_user, require_admin+from switch_core.gateway.auth import get_current_user, require_tenant_adminfrom switch_core.gateway.collaborations import (_require_directory_account,claim_bridge_identity,@@ -91,9 +92,10 @@ _OWNER_SCOPED_PATHS = {def test_bridge_write_routes_require_admin() -> None:- """EVERY state-changing route must be gated on require_admin — a bridge is an- unowned, workspace-wide integration holding platform secrets, so there is no- owner to scope mutation to.+ """EVERY state-changing route must be gated on require_tenant_admin — a+ bridge is an unowned, tenant-scoped integration holding platform secrets,+ so there is no per-resource owner to scope mutation to, but it still+ belongs to one workspace rather than the deployment as a whole.Derived from the router rather than a hand-listed set: a new write route thatforgets the gate fails here instead of shipping open.@@ -103,10 +105,10 @@ def test_bridge_write_routes_require_admin() -> None:for route in router.routesif route.methods & WRITE_METHODSand route.path not in _OWNER_SCOPED_PATHS- and require_admin not in _dependency_calls(route.dependant)+ and require_tenant_admin not in _dependency_calls(route.dependant))assert not unguarded, (- f"collaboration write routes missing require_admin: {unguarded}"+ f"collaboration write routes missing require_tenant_admin: {unguarded}")@@ -118,7 +120,7 @@ def test_owner_scoped_exemptions_name_real_routes() -> None:class TestIdentityRoutesAreSelfOrAdmin:- """The check the require_admin exemption trades away moved into the+ """The check the require_tenant_admin exemption trades away moved into thehandler; it did not disappear."""async def test_claiming_for_another_user_is_refused(self) -> None:@@ -236,6 +238,9 @@ class _StubGet:async def get(self, *_args: object, **_kwargs: object) -> object:return self._value+ async def administers(self, *_args: object, **_kwargs: object) -> bool:+ return False+def _user(*, id: str, role: str) -> SimpleNamespace:return SimpleNamespace(id=id, role=role, name=id)@@ -253,10 +258,10 @@ def test_known_bridge_write_routes_are_present() -> None:def test_every_collaboration_route_requires_authentication() -> None:"""No route may fall back to the old unauthenticated behaviour: each must- depend on get_current_user directly or via require_admin."""+ depend on get_current_user directly or via require_tenant_admin."""for route in router.routes:calls = _dependency_calls(route.dependant)- assert get_current_user in calls or require_admin in calls, (+ assert get_current_user in calls or require_tenant_admin in calls, (f"{sorted(route.methods)} {route.path} is not authenticated")diff --git a/core/tests/switch_core/gateway/test_reference_types_routes.py b/core/tests/switch_core/gateway/test_reference_types_routes.pyindex a792f7c60..7ffdaa416 100644--- a/core/tests/switch_core/gateway/test_reference_types_routes.py+++ b/core/tests/switch_core/gateway/test_reference_types_routes.py@@ -142,7 +142,12 @@ def _app() -> FastAPI:# stubbed. It is never called: a request with no cookie is refused# before it is touched.app.dependency_overrides[get_session_factory] = lambda: None- app.dependency_overrides[get_user_store] = lambda: None+ # A real store, not `None`: authorizing now reads `UserStore.administers`+ # before the route reaches the resource service. With no tenant bound —+ # this app never runs `get_current_user`'s `tenant_scope` — that resolves+ # from the operator bit alone without touching the stubbed session, so a+ # real instance is safe here and a bare `None` no longer is.+ app.dependency_overrides[get_user_store] = lambda: UserStore()app.dependency_overrides[get_config] = lambda: Noneapp.dependency_overrides[get_resource_service] = lambda: Nonereturn app@@ -352,7 +357,9 @@ class TestReferenceTypeCrudRoutes:_create_request("notion"), session, svc, _USER_STORE, alice)- response = await delete_reference_type("notion", session, svc, alice)+ response = await delete_reference_type(+ "notion", session, svc, _USER_STORE, alice+ )assert response.deleted_type == "notion"assert (@@ -386,7 +393,7 @@ class TestReferenceTypeCrudRoutes:)with pytest.raises(HTTPException) as exc:- await delete_reference_type("notion", session, svc, alice)+ await delete_reference_type("notion", session, svc, _USER_STORE, alice)assert exc.value.status_code == 409assert "cannot be deleted" in exc.value.detaildiff --git a/core/tests/switch_core/test_authz.py b/core/tests/switch_core/test_authz.pyindex 61c297fc2..ecf8d1182 100644--- a/core/tests/switch_core/test_authz.py+++ b/core/tests/switch_core/test_authz.py@@ -6,6 +6,7 @@ import pytestfrom switch_core.authz import (Principal,+ administers_tenant,can,can_manage,require,@@ -106,6 +107,26 @@ class TestCanManage:require_manage(ALICE, "u-alice") # owner — no raise+class TestAdministersTenant:+ """`administers_tenant` is the one function allowed to turn a role into+ the admin bit (`authz.py` module docstring) — the operator bypass and the+ per-tenant `owner`/`admin` membership role, combined."""++ def test_operator_administers_regardless_of_tenant_role(self) -> None:+ assert administers_tenant(is_operator=True, tenant_role=None)+ assert administers_tenant(is_operator=True, tenant_role="member")++ def test_owner_or_admin_membership_administers(self) -> None:+ assert administers_tenant(is_operator=False, tenant_role="owner")+ assert administers_tenant(is_operator=False, tenant_role="admin")++ def test_plain_member_does_not_administer(self) -> None:+ assert not administers_tenant(is_operator=False, tenant_role="member")++ def test_no_membership_does_not_administer(self) -> None:+ assert not administers_tenant(is_operator=False, tenant_role=None)++class TestValidateVisibilityPair:@pytest.mark.parametrize("read,write",diff --git a/core/tests/switch_core/test_migration_operator_owns_tenant_zero.py b/core/tests/switch_core/test_migration_operator_owns_tenant_zero.pynew file mode 100644index 000000000..a9dfd8577--- /dev/null+++ b/core/tests/switch_core/test_migration_operator_owns_tenant_zero.py@@ -0,0 +1,256 @@+"""The operator/workspace-admin role split migration moves real data correctly.++`test_migration_parity.py` replays the chain into an *empty* database, so it+can never catch a bug in what `8ef6d4038ecc` does to an existing deployment's+rows — a promoted-then-forgotten operator whose `tenant_members` row still+says `member` would pass every other test and only show up against real data.+This seeds tenant zero the way a deployment with that exact staleness would+look, stops the chain one revision short of the migration under test, runs+it, and inspects what came out.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from alembic.config import Config+from alembic.runtime.environment import EnvironmentContext+from alembic.script import ScriptDirectory+from sqlalchemy import Connection, text+from sqlalchemy.ext.asyncio import create_async_engine++_CORE = Path(__file__).resolve().parents[2]+_MIGRATION_DB = "migration_operator_owns_tenant_zero"++_PRE_MIGRATION_REVISION = "a3f61c02d5be"+_MIGRATION_UNDER_TEST = "8ef6d4038ecc"+_TENANT_ZERO_ID = "00000000-0000-0000-0000-000000000000"+++def _script_directory(config: Config) -> ScriptDirectory:+ config.set_main_option("script_location", str(_CORE / "switch_core" / "migrations"))+ return ScriptDirectory.from_config(config)+++def _upgrade_to(revision: str) -> Any:+ def upgrade(connection: Connection) -> None:+ config = Config(str(_CORE / "alembic.ini"))+ script = _script_directory(config)++ def do_upgrade(current_revision: str, context: Any) -> Any:+ return script._upgrade_revs(revision, current_revision)++ with EnvironmentContext(config, script, fn=do_upgrade) as environment:+ environment.configure(connection=connection)+ with environment.begin_transaction():+ environment.run_migrations()++ return upgrade+++async def _fixture_engine(postgres_url: str) -> Any:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_MIGRATION_DB}"'))+ await connection.execute(text(f'CREATE DATABASE "{_MIGRATION_DB}"'))+ await admin.dispose()+ base, _, _ = postgres_url.rpartition("/")+ return create_async_engine(f"{base}/{_MIGRATION_DB}")+++async def _drop_fixture(postgres_url: str) -> None:+ admin = create_async_engine(postgres_url, isolation_level="AUTOCOMMIT")+ async with admin.connect() as connection:+ await connection.execute(text(f'DROP DATABASE IF EXISTS "{_MIGRATION_DB}"'))+ await admin.dispose()+++async def test_a_promoted_operators_stale_member_row_becomes_owner(+ postgres_url: str,+) -> None:+ """The gap the migration exists for: `users.role` was promoted to+ `admin` by direct SQL after the `tenant_members` row already existed as+ `member` — nothing before this migration ever revisited it."""+ engine = await _fixture_engine(postgres_url)+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_PRE_MIGRATION_REVISION))++ async with engine.begin() as connection:+ await connection.execute(+ text(+ """+ INSERT INTO users (id, name, email, role, password_hash, metadata)+ VALUES ('promoted-op', 'Promoted', '[email protected]',+ 'admin', 'bcrypt-hash', NULL)+ """+ )+ )+ await connection.execute(+ text(+ f"""+ INSERT INTO tenant_members (tenant_id, user_id, role)+ VALUES ('{_TENANT_ZERO_ID}', 'promoted-op', 'member')+ """+ )+ )++ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_MIGRATION_UNDER_TEST))++ async with engine.connect() as connection:+ role = (+ await connection.execute(+ text(+ "SELECT role FROM tenant_members "+ "WHERE tenant_id = :t AND user_id = 'promoted-op'"+ ),+ {"t": _TENANT_ZERO_ID},+ )+ ).scalar_one()+ finally:+ await engine.dispose()+ await _drop_fixture(postgres_url)++ assert role == "owner"+++async def test_an_operator_with_no_membership_row_at_all_gets_one(+ postgres_url: str,+) -> None:+ """`UserStore.ensure_membership` should make this unreachable, but+ nothing at the database level enforces it — the migration closes the gap+ rather than assuming application code always ran first."""+ engine = await _fixture_engine(postgres_url)+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_PRE_MIGRATION_REVISION))++ async with engine.begin() as connection:+ await connection.execute(+ text(+ """+ INSERT INTO users (id, name, email, role, password_hash, metadata)+ VALUES ('orphan-op', 'Orphan', '[email protected]',+ 'admin', 'bcrypt-hash', NULL)+ """+ )+ )++ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_MIGRATION_UNDER_TEST))++ async with engine.connect() as connection:+ role = (+ await connection.execute(+ text(+ "SELECT role FROM tenant_members "+ "WHERE tenant_id = :t AND user_id = 'orphan-op'"+ ),+ {"t": _TENANT_ZERO_ID},+ )+ ).scalar_one()+ finally:+ await engine.dispose()+ await _drop_fixture(postgres_url)++ assert role == "owner"+++async def test_a_plain_members_row_is_left_exactly_as_it_is(+ postgres_url: str,+) -> None:+ """Nothing else moves: a non-operator's membership row is not this+ migration's business, whatever role it happens to hold."""+ engine = await _fixture_engine(postgres_url)+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_PRE_MIGRATION_REVISION))++ async with engine.begin() as connection:+ await connection.execute(+ text(+ """+ INSERT INTO users (id, name, email, role, password_hash, metadata)+ VALUES ('plain-member', 'Plain', '[email protected]',+ 'user', 'bcrypt-hash', NULL)+ """+ )+ )+ await connection.execute(+ text(+ f"""+ INSERT INTO tenant_members (tenant_id, user_id, role)+ VALUES ('{_TENANT_ZERO_ID}', 'plain-member', 'member')+ """+ )+ )++ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_MIGRATION_UNDER_TEST))++ async with engine.connect() as connection:+ role = (+ await connection.execute(+ text(+ "SELECT role FROM tenant_members "+ "WHERE tenant_id = :t AND user_id = 'plain-member'"+ ),+ {"t": _TENANT_ZERO_ID},+ )+ ).scalar_one()+ finally:+ await engine.dispose()+ await _drop_fixture(postgres_url)++ assert role == "member"+++async def test_running_it_twice_is_a_no_op_the_second_time(+ postgres_url: str,+) -> None:+ engine = await _fixture_engine(postgres_url)+ try:+ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_PRE_MIGRATION_REVISION))++ async with engine.begin() as connection:+ await connection.execute(+ text(+ """+ INSERT INTO users (id, name, email, role, password_hash, metadata)+ VALUES ('idempotent-op', 'Idempotent', '[email protected]',+ 'admin', 'bcrypt-hash', NULL)+ """+ )+ )+ await connection.execute(+ text(+ f"""+ INSERT INTO tenant_members (tenant_id, user_id, role)+ VALUES ('{_TENANT_ZERO_ID}', 'idempotent-op', 'member')+ """+ )+ )++ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_MIGRATION_UNDER_TEST))+ async with engine.begin() as connection:+ await connection.run_sync(_upgrade_to(_MIGRATION_UNDER_TEST))++ async with engine.connect() as connection:+ rows = (+ await connection.execute(+ text(+ "SELECT role FROM tenant_members "+ "WHERE tenant_id = :t AND user_id = 'idempotent-op'"+ ),+ {"t": _TENANT_ZERO_ID},+ )+ ).all()+ finally:+ await engine.dispose()+ await _drop_fixture(postgres_url)++ assert [r.role for r in rows] == ["owner"]diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.pyindex 064c5f461..f4ceed200 100644--- a/core/tests/switch_core/test_rooms_yaml.py+++ b/core/tests/switch_core/test_rooms_yaml.py@@ -1052,10 +1052,12 @@ async def test_endpoint_json_body(env):from fastapi import HTTPException+ from switch_core.db.stores.user_store import UserStorefrom switch_core.gateway.rooms import create_room_from_yamlsvc = _svc(env)user_id = env["user_id"]+ user_store = UserStore()user = User(name="alice", email="[email protected]", role="member")# Poke the id to match the seeded user so provision works.object.__setattr__(user, "id", user_id)@@ -1071,12 +1073,14 @@ async def test_endpoint_json_body(env):request.headers = {"content-type": "application/json"}request.body.return_value = body- result = await create_room_from_yaml(request, svc, user)+ async with env["session_factory"]() as session:+ result = await create_room_from_yaml(request, session, svc, user_store, user)assert result.room_name == "carol local-deploy"# Non-string yaml value → 400.bad_body = json.dumps({"yaml": 123}).encode()request.body.return_value = bad_body- with pytest.raises(HTTPException) as exc_info:- await create_room_from_yaml(request, svc, user)+ async with env["session_factory"]() as session:+ with pytest.raises(HTTPException) as exc_info:+ await create_room_from_yaml(request, session, svc, user_store, user)assert exc_info.value.status_code == 400