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
fix(authz): resolve the tenant-admin bit once, in the dependency
Petr Bauch0fc9869571a4
diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex d1e4f6122..3506b9741 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -317,15 +317,22 @@ class UserStore: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.+ one membership row that can answer "in *this* tenant".++ Raises:+ RuntimeError: no tenant is bound. The question has no+ tenant-independent answer: half of it is a membership row that+ cannot be read without one. Answering on the operator bit+ alone would quietly demote a workspace owner to a plain+ member, and the symptom — a 403 on their own workspace — says+ nothing about why."""tenant_id = current_tenant_id()- role = (- None- if tenant_id is None- else await self.tenant_role(session, tenant_id, user.id)- )+ if tenant_id is None:+ raise RuntimeError(+ "administers requires a bound tenant; whether someone may "+ "administer a workspace is only answerable about a particular "+ "one"+ )+ role = 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 b2d908939..a2033b826 100644--- a/core/switch_core/gateway/agents.py+++ b/core/switch_core/gateway/agents.py@@ -26,7 +26,7 @@ from switch_core.db.models import 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+from switch_core.gateway.auth import get_current_user, get_tenant_is_adminfrom switch_core.gateway.dependencies import (get_agent_store,get_protocol,@@ -74,13 +74,14 @@ async def delete_agent_by_name(agent_store: Annotated[AgentStore, Depends(get_agent_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> dict[str, bool]:agent = await agent_store.get_by_name(session, agent_name)if agent is None:raise HTTPException(status_code=404, detail=f"Agent not found: {agent_name}")try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),agent.owner_id,)except PermissionError:@@ -104,13 +105,14 @@ async def delete_agent(agent_store: Annotated[AgentStore, Depends(get_agent_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> dict[str, bool]:agent = await agent_store.get(session, agent_id)if agent is None:raise HTTPException(status_code=404, detail=f"Agent not found: {agent_id}")try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),agent.owner_id,)except PermissionError:@@ -198,6 +200,7 @@ async def register_known_subagents(protocol: Annotated[ProtocolService, Depends(get_protocol)],session: Annotated[AsyncSession, Depends(get_session)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RegisterKnownSubagentsResponse:"""Register many Claude Code subagents under one parent agent (session-authed).@@ -223,7 +226,7 @@ async def register_known_subagents()try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),parent.owner_id,)except PermissionError as exc:@@ -308,6 +311,7 @@ async def update_agent_options(session: Annotated[AsyncSession, Depends(get_session)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> AgentSummary:"""Replace a known-agent's options.@@ -327,7 +331,7 @@ async def update_agent_options(try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),agent.owner_id,)except PermissionError:@@ -363,6 +367,7 @@ async def update_agent_icon(session: Annotated[AsyncSession, Depends(get_session)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> AgentSummary:"""Set, change, or clear an agent's icon (CHOO-2171).@@ -383,7 +388,7 @@ async def update_agent_icon(try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),agent.owner_id,)except PermissionError:@@ -419,6 +424,7 @@ async def update_agent_display_name(session: Annotated[AsyncSession, Depends(get_session)],agent_store: Annotated[AgentStore, Depends(get_agent_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> AgentSummary:"""Set, change, or clear an agent's human display name.@@ -436,7 +442,7 @@ async def update_agent_display_name(try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),agent.owner_id,)except PermissionError:@@ -516,6 +522,7 @@ async def update_addressing_policy(user_store: Annotated[UserStore, Depends(get_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> AgentDetail:"""Set or clear an agent's scoped addressing policy (CHOO-1585).@@ -528,7 +535,7 @@ async def update_addressing_policy(try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),agent.owner_id,)except PermissionError:diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.pyindex 5e4b4b8f6..2b9e7ccea 100644--- a/core/switch_core/gateway/auth.py+++ b/core/switch_core/gateway/auth.py@@ -287,6 +287,7 @@ async def require_room_access(room_id: str,user: User,action: Action,+ is_admin: bool,) -> Room:"""Load a room (404 if missing) and authorize `action` for `user`,raising HTTP 403 if denied.@@ -295,11 +296,19 @@ async def require_room_access(id (attaching references, linking rooms, …) so they cannot operate on aroom the caller lacks access to. Mirrors the protocol layer's``_require_room_action``.++ `is_admin` comes from ``get_tenant_is_admin``; it is a parameter rather+ than a read of its own so that a route cannot end up authorizing against+ a different admin bit than the one its own dependencies resolved.++ This is the widest of the tenant-admin gates: `authz.can` short-circuits+ on the admin bit, so a workspace owner or admin passes it for every room+ in their workspace, private ones included. See the phase 2 design note on+ what that grant covers."""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, is_admin), action, room)except PermissionError as e:diff --git a/core/switch_core/gateway/collaborations.py b/core/switch_core/gateway/collaborations.pyindex a7ae7361f..902a5c974 100644--- a/core/switch_core/gateway/collaborations.py+++ b/core/switch_core/gateway/collaborations.py@@ -21,7 +21,11 @@ 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_tenant_admin+from switch_core.gateway.auth import (+ get_current_user,+ get_tenant_is_admin,+ require_tenant_admin,+)from switch_core.gateway.dependencies import (get_bridge_store,get_collab_lifecycle,@@ -529,6 +533,7 @@ async def claim_bridge_identity(CollaborationBridgeLifecycleService, Depends(get_collab_lifecycle)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ExternalUserSummary:"""Claim a platform identity for a Switch user (CHOO-2137).@@ -548,7 +553,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 not await user_store.administers(session, user):+ if target_user_id != user.id and not is_admin:raise HTTPException(status_code=403,detail="Only an admin may claim a messaging identity for another user",@@ -635,6 +640,7 @@ async def release_bridge_identity(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],user_id: str | None = None,) -> ExternalUserSummary:"""Drop a claim on a platform account — your own, or someone else's if you@@ -644,7 +650,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 not await user_store.administers(session, user):+ if target_user_id != user.id and not is_admin:raise HTTPException(status_code=403,detail="Only an admin may release another user's messaging identity",diff --git a/core/switch_core/gateway/connectors.py b/core/switch_core/gateway/connectors.pyindex f21f7ea8f..8dd425657 100644--- a/core/switch_core/gateway/connectors.py+++ b/core/switch_core/gateway/connectors.py@@ -12,8 +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 UserStore-from switch_core.gateway.auth import get_current_user+from switch_core.gateway.auth import get_current_user, get_tenant_is_adminfrom switch_core.gateway.dependencies import (get_api_key_store,get_connector_lifecycle,@@ -132,6 +131,7 @@ async def delete_connector(ServerSideConnectorLifecycleService, Depends(get_connector_lifecycle)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> dict[str, bool]:record = await connector_store.get(session, connector_id)if record is None:@@ -139,7 +139,7 @@ async def delete_connector(reg_key = await api_key_store.get(session, record.api_key_id)if reg_key is None or reg_key.user_id != user.id:- if not await UserStore().administers(session, user):+ if not is_admin:raise HTTPException(status_code=403, detail="Not authorized to delete this connector")diff --git a/core/switch_core/gateway/documents.py b/core/switch_core/gateway/documents.pyindex 998b7ca17..93a7dd362 100644--- a/core/switch_core/gateway/documents.py+++ b/core/switch_core/gateway/documents.py@@ -308,8 +308,9 @@ async def list_room_documents(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)],) -> list[DocumentSummary]:- await require_room_access(session, room_store, room_id, user, "read")+ await require_room_access(session, room_store, room_id, user, "read", is_admin)docs = await resource_service.list_room_documents(session, room_id)return await _enrich_summaries(session, docs, resource_service, user_store, agent_store@@ -328,7 +329,7 @@ async def attach_document_to_room(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")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)try:await resource_service.attach_document_to_room(session,@@ -356,10 +357,11 @@ async def detach_document_from_room(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> None:"""For globally-owned docs: detach from the room. For room-scoped docs:hard-delete them entirely (since they live only in this room)."""- await require_room_access(session, room_store, room_id, user, "write")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)doc = await resource_service.get_room_scoped_document_or_none(session, room_id, document_id)@@ -382,11 +384,12 @@ async def get_room_document(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:"""Fetch a document by id within the context of a room. Accepts bothroom-scoped documents (read-only) and globally-attached documents. Roomread access is required and, once granted, implies access to its docs."""- await require_room_access(session, room_store, room_id, user, "read")+ await require_room_access(session, room_store, room_id, user, "read", is_admin)docs = await resource_service.list_room_documents(session, room_id)doc = next((d for d in docs if d.id == document_id), None)if doc is None:diff --git a/core/switch_core/gateway/packages.py b/core/switch_core/gateway/packages.pyindex ed3cdc9b2..4521f6d71 100644--- a/core/switch_core/gateway/packages.py+++ b/core/switch_core/gateway/packages.py@@ -10,7 +10,11 @@ from switch_core.db.models import Package, 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,@@ -140,13 +144,14 @@ async def get_package(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> PackageDetail:try:pkg = await resource_service.get_package_for_user(session,package_id,user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -163,13 +168,14 @@ async def patch_package(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> PackageDetail:try:pkg = await resource_service.update_package(session,package_id,user_id=user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,name=req.name,description=req.description,instructions=req.instructions,@@ -190,13 +196,14 @@ async def delete_package(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)],) -> PackageDeleteResponse:try:detached = await resource_service.delete_package(session,package_id,user_id=user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -212,13 +219,14 @@ async def list_rooms_for_package(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_package_for_user(session,package_id,user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -238,13 +246,14 @@ async def list_package_references(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[ReferenceDetail]:try:await resource_service.get_package_for_user(session,package_id,user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -261,6 +270,7 @@ async def add_reference_to_package(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)],) -> None:try:await resource_service.add_reference_to_package(@@ -268,7 +278,7 @@ async def add_reference_to_package(package_id,reference_id,user_id=user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -284,6 +294,7 @@ async def remove_reference_from_package(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)],) -> PackageMemberRemoveResponse:try:affected = await resource_service.remove_reference_from_package(@@ -291,7 +302,7 @@ async def remove_reference_from_package(package_id,reference_id,user_id=user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -314,13 +325,14 @@ async def list_package_documents(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)],) -> list[DocumentSummary]:try:await resource_service.get_package_for_user(session,package_id,user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -339,6 +351,7 @@ async def add_document_to_package(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)],) -> None:try:await resource_service.add_document_to_package(@@ -346,7 +359,7 @@ async def add_document_to_package(package_id,document_id,user_id=user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -362,6 +375,7 @@ async def remove_document_from_package(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)],) -> PackageMemberRemoveResponse:try:affected = await resource_service.remove_document_from_package(@@ -369,7 +383,7 @@ async def remove_document_from_package(package_id,document_id,user_id=user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -395,8 +409,9 @@ async def list_room_packages(room_store: Annotated[RoomStore, Depends(get_room_store)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[PackageDetail]:- await require_room_access(session, room_store, room_id, user, "read")+ await require_room_access(session, room_store, room_id, user, "read", is_admin)pkgs = await resource_service.list_room_packages(session, room_id)return await _enrich(session, pkgs, resource_service, user_store)@@ -410,15 +425,16 @@ async def attach_package_to_room(room_store: Annotated[RoomStore, Depends(get_room_store)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> PackageDetail:- await require_room_access(session, room_store, room_id, user, "write")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)try:await resource_service.attach_package_to_room(session,room_id,package_id,user_id=user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -429,7 +445,7 @@ async def attach_package_to_room(session,package_id,user.id,- is_admin=await UserStore().administers(session, user),+ is_admin=is_admin,)return await _enrich_one(session, pkg, resource_service, user_store)@@ -442,7 +458,8 @@ async def detach_package_from_room(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> None:- await require_room_access(session, room_store, room_id, user, "write")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)await resource_service.detach_package_from_room(session, room_id, package_id)await session.commit()diff --git a/core/switch_core/gateway/references.py b/core/switch_core/gateway/references.pyindex 7d80b3fa2..c78b6e7d8 100644--- a/core/switch_core/gateway/references.py+++ b/core/switch_core/gateway/references.py@@ -15,7 +15,11 @@ from switch_core.bridges.resource.service import (from switch_core.db.models import Reference, Userfrom 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_resource_service,get_room_store,@@ -165,9 +169,10 @@ async def list_reference_types(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[ReferenceTypeInfo]:views = await resource_service.list_reference_types_for_principal(- session, user_id=user.id, is_admin=await user_store.administers(session, user)+ session, user_id=user.id, is_admin=is_admin)owners = await _owner_names(session, user_store, {v.owner_id for v in views if v.owner_id is not None}@@ -184,9 +189,10 @@ async def list_owned_reference_types(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[ReferenceTypeDetail]:rows = await resource_service.list_owned_reference_types(- session, user_id=user.id, is_admin=await user_store.administers(session, user)+ session, user_id=user.id, is_admin=is_admin)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]@@ -229,13 +235,14 @@ async def patch_reference_type(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ReferenceTypeDetail:try:row = await resource_service.update_reference_type(session,type,user_id=user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,display_name=req.display_name,instructions=req.instructions,value_hint=req.value_hint,@@ -259,15 +266,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)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ReferenceTypeDeleteResponse:try:await resource_service.delete_reference_type(session,type,user_id=user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,)except ReferenceTypeInUseError as e:raise HTTPException(status_code=409, detail=str(e)) from e@@ -297,12 +304,13 @@ async def create_reference(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ReferenceDetail:try:ref = await resource_service.create_reference(session,owner_id=user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,read_visibility=req.read_visibility,write_visibility=req.write_visibility,type=req.type,@@ -324,13 +332,14 @@ async def get_reference(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ReferenceDetail:try:ref = await resource_service.get_reference_for_user(session,reference_id,user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -347,13 +356,14 @@ async def patch_reference(resource_service: Annotated[ResourceService, Depends(get_resource_service)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ReferenceDetail:try:ref = await resource_service.update_reference(session,reference_id,user_id=user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,name=req.name,description=req.description,instructions=req.instructions,@@ -374,8 +384,8 @@ 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)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ReferenceDeleteResponse:affected_packages = await resource_service.list_packages_for_reference(session, reference_id@@ -385,7 +395,7 @@ async def delete_reference(session,reference_id,user_id=user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -404,15 +414,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)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[ResourceRoom]:try:await resource_service.get_reference_for_user(session,reference_id,user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e@@ -430,8 +440,9 @@ async def list_room_references(room_store: Annotated[RoomStore, Depends(get_room_store)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[ReferenceDetail]:- await require_room_access(session, room_store, room_id, user, "read")+ await require_room_access(session, room_store, room_id, user, "read", is_admin)refs = await resource_service.list_room_references(session, room_id)return await _enrich(session, refs, resource_service, user_store)@@ -445,10 +456,10 @@ async def attach_reference_to_room(room_store: Annotated[RoomStore, Depends(get_room_store)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ReferenceDetail:- await require_room_access(session, room_store, room_id, user, "write")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)try:- is_admin = await user_store.administers(session, user)await resource_service.attach_reference_to_room(session,room_id,@@ -475,7 +486,8 @@ async def detach_reference_from_room(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> None:- await require_room_access(session, room_store, room_id, user, "write")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)await resource_service.detach_reference_from_room(session, room_id, reference_id)await session.commit()diff --git a/core/switch_core/gateway/room_groups.py b/core/switch_core/gateway/room_groups.pyindex 6d922673b..dca17f78d 100644--- a/core/switch_core/gateway/room_groups.py+++ b/core/switch_core/gateway/room_groups.py@@ -9,8 +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 UserStore-from switch_core.gateway.auth import get_current_user+from switch_core.gateway.auth import get_current_user, get_tenant_is_adminfrom switch_core.gateway.dependencies import (get_room_group_store,get_room_store,@@ -110,13 +109,14 @@ async def assign_rooms_to_group(room_group_store: Annotated[RoomGroupStore, Depends(get_room_group_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)],) -> RoomGroupAssignResponse:"""Bulk-assign rooms into a group. Requires write access to each room;unknown room ids are skipped."""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, await UserStore().administers(session, user))+ principal = Principal(user.id, is_admin)forbidden: list[str] = []allowed: list[str] = []for room_id in req.room_ids:diff --git a/core/switch_core/gateway/room_links.py b/core/switch_core/gateway/room_links.pyindex e219ee7fb..3c2e18a14 100644--- a/core/switch_core/gateway/room_links.py+++ b/core/switch_core/gateway/room_links.py@@ -8,7 +8,11 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.bridges.resource.service import ResourceServicefrom switch_core.db.models import Userfrom switch_core.db.stores.room_store import RoomStore-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_resource_service,get_room_store,@@ -41,8 +45,9 @@ async def list_linked_rooms(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[LinkedRoomDetail]:- await require_room_access(session, room_store, room_id, user, "read")+ await require_room_access(session, room_store, room_id, user, "read", is_admin)rows = await resource_service.list_linked_rooms_for_room(session, room_id)return [LinkedRoomDetail(**row) for row in rows]@@ -54,8 +59,9 @@ async def list_inbound_linked_rooms(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[InboundLinkedRoomDetail]:- await require_room_access(session, room_store, room_id, user, "read")+ await require_room_access(session, room_store, room_id, user, "read", is_admin)rows = await resource_service.list_inbound_linked_rooms(session, room_id)return [InboundLinkedRoomDetail(**row) for row in rows]@@ -68,8 +74,9 @@ async def create_linked_room(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> LinkedRoomDetail:- await require_room_access(session, room_store, room_id, user, "write")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)try:row = await resource_service.attach_linked_room(session,@@ -93,8 +100,9 @@ async def delete_linked_room(resource_service: Annotated[ResourceService, Depends(get_resource_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> Response:- await require_room_access(session, room_store, room_id, user, "write")+ await require_room_access(session, room_store, room_id, user, "write", is_admin)removed = await resource_service.detach_linked_room(session, source_room_id=room_id, target_room_id=target_room_id)diff --git a/core/switch_core/gateway/rooms.py b/core/switch_core/gateway/rooms.pyindex 5cdfad042..752326e05 100644--- a/core/switch_core/gateway/rooms.py+++ b/core/switch_core/gateway/rooms.py@@ -19,7 +19,7 @@ from switch_core.db.stores.external_user_store import ExternalUserStorefrom switch_core.db.stores.room_group_store import RoomGroupStorefrom 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+from switch_core.gateway.auth import get_current_user, get_tenant_is_adminfrom switch_core.gateway.dependencies import (get_bridge_store,get_collab_lifecycle,@@ -65,6 +65,7 @@ async def _require_room(room_id: str,user: User,action: Action,+ is_admin: bool,) -> Room:"""Load a room (404 if missing) and authorize `action` for `user`,raising HTTP 403 if denied."""@@ -73,7 +74,7 @@ async def _require_room(raise HTTPException(status_code=404, detail="Room not found")try:require(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),action,room,)@@ -242,13 +243,14 @@ async def list_rooms(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],search: Annotated[str | None, Query()] = None,include_archived: Annotated[bool, Query()] = False,) -> list[RoomSummary]:rooms = await room_store.list_readable(session,user.id,- is_admin=await user_store.administers(session, user),+ is_admin=is_admin,include_archived=include_archived,)@@ -377,8 +379,8 @@ 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)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> ProvisionResult:"""Provision a single room and its attachments from a YAML spec.@@ -405,9 +407,7 @@ async def create_room_from_yaml(text = (await request.body()).decode("utf-8")inputs = Nonespec = rooms_yaml.parse(text, inputs=inputs)- return await rooms_yaml.provision(- spec, user_id=user.id, is_admin=await user_store.administers(session, user)- )+ return await rooms_yaml.provision(spec, user_id=user.id, is_admin=is_admin)except ValueError as e:raise HTTPException(status_code=400, detail=str(e)) from eexcept PermissionError as e:@@ -423,6 +423,7 @@ async def export_room_yaml(room_store: Annotated[RoomStore, Depends(get_room_store)],rooms_yaml: Annotated[RoomYamlService, Depends(get_room_yaml_service)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],agents: Annotated[bool, Query()] = True,users: Annotated[bool, Query()] = True,references: Annotated[bool, Query()] = True,@@ -431,7 +432,7 @@ async def export_room_yaml() -> Response:"""Export a room to YAML in the same surface ``/rooms/from-yaml`` accepts.Each section can be dropped via its boolean toggle (default included)."""- await _require_room(session, room_store, room_id, user, "read")+ await _require_room(session, room_store, room_id, user, "read", is_admin)yaml_text = await rooms_yaml.export(room_id,agents=agents,@@ -452,8 +453,9 @@ async def get_room(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- room = await _require_room(session, room_store, room_id, user, "read")+ room = await _require_room(session, room_store, room_id, user, "read", is_admin)return await _build_room_detail(session, room, room_store, bridge_store, external_user_store, protocol)@@ -470,8 +472,9 @@ async def patch_room(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.update_room(room_id,@@ -500,8 +503,9 @@ async def list_room_roles(room_store: Annotated[RoomStore, Depends(get_room_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:- await _require_room(session, room_store, room_id, user, "read")+ await _require_room(session, room_store, room_id, user, "read", is_admin)return await _list_room_role_details(session, room_id, protocol)@@ -513,8 +517,9 @@ async def create_room_role(room_store: Annotated[RoomStore, Depends(get_room_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await protocol.room_role_store.define_role(session, room_id, req.name, req.instructions, req.exclusive@@ -534,8 +539,9 @@ async def patch_room_role(room_store: Annotated[RoomStore, Depends(get_room_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await protocol.room_role_store.edit_role(session, room_id, name, req.instructions, req.exclusive@@ -554,8 +560,9 @@ async def delete_room_role(room_store: Annotated[RoomStore, Depends(get_room_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> list[RoomRoleDetail]:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await protocol.room_role_store.delete_role(session, room_id, name)except ValueError as e:@@ -574,9 +581,10 @@ async def put_room_group(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:"""Assign the room to a group, or make it standalone (`group_id=null`)."""- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_store.set_group(session, room_id, req.group_id)except ValueError as e:@@ -604,8 +612,9 @@ async def put_protection(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.update_protection_config(room_id, req.protection_config)except ValueError:@@ -630,8 +639,9 @@ async def put_observe(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.update_observe_config(room_id, req.observe_config)except ValueError:@@ -656,8 +666,9 @@ async def post_room_agents(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.add_agents_to_room(room_id,@@ -688,8 +699,9 @@ async def patch_room_agent(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.set_join_event_listeners(room_id, {agent_id: req.receives_join_events}@@ -715,8 +727,9 @@ async def delete_room_agent(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.remove_agents_from_room(room_id, [agent_id])except ValueError as e:@@ -741,8 +754,9 @@ async def post_room_users(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.add_users_to_room(room_id, req.user_names)except ValueError as e:@@ -766,8 +780,9 @@ async def _set_archived(external_user_store: ExternalUserStore,protocol: ProtocolService,user: User,+ is_admin: bool,) -> RoomDetail:- await _require_room(session, room_store, room_id, user, "write")+ await _require_room(session, room_store, room_id, user, "write", is_admin)try:await room_service.set_room_archived(room_id, archived)except ValueError:@@ -790,8 +805,9 @@ async def archive_room(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- """Archive a room: hide it from the default active list. Reversible and+ """: hide it from the default active list. Reversible andmetadata-only — the Matrix room, members, and bridge channel are intact."""return await _set_archived(room_id,@@ -803,6 +819,7 @@ async def archive_room(external_user_store,protocol,user,+ is_admin,)@@ -816,8 +833,9 @@ async def unarchive_room(external_user_store: Annotated[ExternalUserStore, Depends(get_external_user_store)],protocol: Annotated[ProtocolService, Depends(get_protocol)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> RoomDetail:- """Unarchive a room: restore it to the active list."""+ """: restore it to the active list."""return await _set_archived(room_id,False,@@ -828,6 +846,7 @@ async def unarchive_room(external_user_store,protocol,user,+ is_admin,)@@ -838,8 +857,9 @@ async def delete_room(room_service: Annotated[RoomService, Depends(get_room_service)],room_store: Annotated[RoomStore, Depends(get_room_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> dict[str, bool]:- await _require_room(session, room_store, room_id, user, "delete")+ await _require_room(session, room_store, room_id, user, "delete", is_admin)try:await room_service.delete_room(room_id)except ValueError:@@ -853,10 +873,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)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> BulkDeleteResponse:- principal = Principal(user.id, await user_store.administers(session, user))+ principal = Principal(user.id, is_admin)deleted = 0for room_id in req.room_ids:room = await room_store.get(session, room_id)@@ -879,13 +899,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)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> 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, await user_store.administers(session, user))+ principal = Principal(user.id, is_admin)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 60c4917c9..44f9034b4 100644--- a/core/switch_core/gateway/templates.py+++ b/core/switch_core/gateway/templates.py@@ -29,7 +29,7 @@ from switch_core.db.stores.template_store import (TemplateStore,)from 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, get_tenant_is_adminfrom switch_core.gateway.dependencies import (get_config,get_session,@@ -155,7 +155,11 @@ def _require_within_size_limit(content: str, config: SwitchConfig) -> None:async def _load_for_management(- session: AsyncSession, store: TemplateStore, template_id: str, user: User+ session: AsyncSession,+ store: TemplateStore,+ template_id: str,+ user: User,+ is_admin: bool,) -> Template:"""Fetch a template the caller is allowed to change, or fail saying why."""template = await store.get(session, template_id)@@ -165,7 +169,7 @@ async def _load_for_management()try:require_manage(- Principal(user.id, await UserStore().administers(session, user)),+ Principal(user.id, is_admin),template.owner_id,)except PermissionError as e:@@ -306,8 +310,9 @@ async def patch_template(user_store: Annotated[UserStore, Depends(get_user_store)],config: Annotated[SwitchConfig, Depends(get_config)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> TemplateDetail:- await _load_for_management(session, template_store, template_id, user)+ await _load_for_management(session, template_store, template_id, user, is_admin)if req.content is not None:_require_within_size_limit(req.content, config)_require_storable(req.content)@@ -336,8 +341,9 @@ async def delete_template(session: Annotated[AsyncSession, Depends(get_session)],template_store: Annotated[TemplateStore, Depends(get_template_store)],user: Annotated[User, Depends(get_current_user)],+ is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> TemplateDeleteResponse:- await _load_for_management(session, template_store, template_id, user)+ await _load_for_management(session, template_store, template_id, user, is_admin)try:await template_store.delete(session, template_id)except ValueError as e:diff --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.pyindex c684b3d6f..87b40b674 100644--- 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.py@@ -78,7 +78,7 @@ class _FakeClientLifecycle:class _NoBridges:- def all_bridges(self) -> list[object]:+ def bridges_for_tenant(self, tenant_id: str) -> list[object]:return []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 7ed73cae0..b0656af7e 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@@ -141,7 +141,8 @@ async def _seed(async def _slugs_from_route(session: AsyncSession, service: ResourceService, user: User) -> set[str]:- listed = await route_list_types(session, service, _USER_STORE, user)+ is_admin = await _USER_STORE.administers(session, user)+ listed = await route_list_types(session, service, _USER_STORE, user, is_admin)return {info.type for info in listed}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.pyindex c76cabcc1..9f87d889f 100644--- a/core/tests/switch_core/db/test_tenant_admin_role_split.py+++ b/core/tests/switch_core/db/test_tenant_admin_role_split.py@@ -6,7 +6,7 @@ workspace's `owner` membership row granted nothing: every admin-gated routechecked the global bit, never the caller's role in the tenant the request isbound to.-These tests pin the four behavioural claims that split makes true:+These tests pin the 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`@@ -15,7 +15,9 @@ These tests pin the four behavioural claims that split makes true:- a deployment operator (`users.role == "admin"`) keeps its unconditionalbypass regardless of what `tenant_members` says, in every tenant, with orwithout a membership row at all;-- a plain `member` with no operator bit gains nothing.+- a plain `member` with no operator bit gains nothing;+- and with no tenant bound at all the question is refused rather than+ answered on the operator bit alone, for operators too.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@@ -27,12 +29,13 @@ an actual resource decision is exercised end to end, not just the boolean.from __future__ import annotations+import pytestfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.authz import Principal, canfrom switch_core.db.models import TENANT_ZERO_ID, Room, Tenant, TenantMember, Userfrom switch_core.db.stores.user_store import UserStore-from switch_core.tenant_context import tenant_scope+from switch_core.tenant_context import no_tenant, tenant_scopeTENANT_B = "tenant-b"@@ -147,6 +150,40 @@ class TestUserStoreAdministers:assert await store.administers(session, stray) is False+ async def test_unbound_is_refused_rather_than_answered_on_the_operator_bit(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # Answering here would mean answering a question that was not asked:+ # "may this person administer" has no deployment-wide form. The+ # tempting fallback — the operator bit alone — silently strips a+ # workspace owner of their role, and the 403 that follows names no+ # cause. Same call as the one #442 made for the bridge identities.+ store = UserStore()+ async with session_factory() as session:+ owner = await _make_user(session, "unbound-owner")+ await _membership(session, TENANT_ZERO_ID, owner.id, "owner")+ await session.commit()++ with no_tenant():+ with pytest.raises(RuntimeError, match="requires a bound tenant"):+ await store.administers(session, owner)++ async def test_unbound_is_refused_for_an_operator_too(+ self, session_factory: async_sessionmaker[AsyncSession]+ ) -> None:+ # The operator bypass is the one answer that *would* have been right+ # without a tenant, which is exactly why it must not be given: a+ # caller that reaches here unbound has a bug, and returning True for+ # the most privileged accounts is the worst moment to hide one.+ store = UserStore()+ async with session_factory() as session:+ operator = await _make_user(session, "unbound-operator", role="admin")+ await session.commit()++ with no_tenant():+ with pytest.raises(RuntimeError, match="requires a bound tenant"):+ await store.administers(session, operator)+class TestRoomAuthzThroughTenantRole:"""The same claims, one layer up: a real `authz.can` decision on a realdiff --git a/core/tests/switch_core/gateway/agent_route_harness.py b/core/tests/switch_core/gateway/agent_route_harness.pyindex f39af1c7a..697437dbf 100644--- a/core/tests/switch_core/gateway/agent_route_harness.py+++ b/core/tests/switch_core/gateway/agent_route_harness.py@@ -9,6 +9,19 @@ from __future__ import annotationsfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.db.models import Agent, ApiKey, Client, User+from switch_core.db.stores.user_store import UserStore++_USER_STORE = UserStore()+++async def is_admin(session: AsyncSession, user: User) -> bool:+ """The bit `get_tenant_is_admin` hands a route, resolved the same way.++ A route takes it as an argument now, so a test calling the coroutine+ directly has to supply one. Reading it through the store rather than+ passing a literal keeps a `role="admin"` on the user row meaningful.+ """+ return await _USER_STORE.administers(session, user)async def add_user(session: AsyncSession, *, name: str, role: str = "user") -> User:diff --git a/core/tests/switch_core/gateway/test_agent_display_name_route.py b/core/tests/switch_core/gateway/test_agent_display_name_route.pyindex d461993d2..474159bcc 100644--- a/core/tests/switch_core/gateway/test_agent_display_name_route.py+++ b/core/tests/switch_core/gateway/test_agent_display_name_route.py@@ -15,7 +15,11 @@ from switch_core.agent_display_name import MAX_DISPLAY_NAME_LENGTHfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.gateway.agents import update_agent_display_namefrom switch_core.gateway.schemas import UpdateAgentDisplayNameRequest-from tests.switch_core.gateway.agent_route_harness import add_agent, add_user+from tests.switch_core.gateway.agent_route_harness import (+ add_agent,+ add_user,+ is_admin,+)_AGENT_STORE = AgentStore()@@ -37,6 +41,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.display_name == _NAME@@ -59,6 +64,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.display_name == _NAME@@ -78,6 +84,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.display_name == _OTHER_NAME@@ -100,6 +107,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.display_name is None@@ -122,6 +130,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,other,+ await is_admin(session, other),)assert exc.value.status_code == 403@@ -143,6 +152,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,admin,+ await is_admin(session, admin),)assert summary.display_name == _NAME@@ -160,6 +170,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert exc.value.status_code == 404@@ -189,6 +200,7 @@ class TestUpdateAgentDisplayName:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert exc.value.status_code == 400diff --git a/core/tests/switch_core/gateway/test_agent_icon_route.py b/core/tests/switch_core/gateway/test_agent_icon_route.pyindex 673541a56..4cc002405 100644--- a/core/tests/switch_core/gateway/test_agent_icon_route.py+++ b/core/tests/switch_core/gateway/test_agent_icon_route.py@@ -15,7 +15,11 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.db.stores.agent_store import AgentStorefrom switch_core.gateway.agents import update_agent_iconfrom switch_core.gateway.schemas import UpdateAgentIconRequest-from tests.switch_core.gateway.agent_route_harness import add_agent, add_user+from tests.switch_core.gateway.agent_route_harness import (+ add_agent,+ add_user,+ is_admin,+)_AGENT_STORE = AgentStore()@@ -37,6 +41,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.icon_url == _ICON@@ -59,6 +64,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.icon_url == _OTHER_ICON@@ -80,6 +86,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.icon_url is None@@ -102,6 +109,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert summary.icon_url is None@@ -121,6 +129,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,other,+ await is_admin(session, other),)assert exc.value.status_code == 403@@ -142,6 +151,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,admin,+ await is_admin(session, admin),)assert summary.icon_url == _ICON@@ -159,6 +169,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert exc.value.status_code == 404@@ -192,6 +203,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)assert exc.value.status_code == 400@@ -215,6 +227,7 @@ class TestUpdateAgentIcon:session,_AGENT_STORE,owner,+ await is_admin(session, owner),)stored = await _AGENT_STORE.get(session, agent.id)diff --git a/core/tests/switch_core/gateway/test_collaborations_authz.py b/core/tests/switch_core/gateway/test_collaborations_authz.pyindex 400f3c417..aeeeb8b53 100644--- a/core/tests/switch_core/gateway/test_collaborations_authz.py+++ b/core/tests/switch_core/gateway/test_collaborations_authz.py@@ -138,6 +138,7 @@ class TestIdentityRoutesAreSelfOrAdmin:user_store=_StubGet(None), # type: ignore[arg-type]collab_lifecycle=object(), # type: ignore[arg-type]user=_user(id="me", role="user"),+ is_admin=False,)assert excinfo.value.status_code == 403@@ -153,6 +154,7 @@ class TestIdentityRoutesAreSelfOrAdmin:external_user_store=_StubGet(theirs), # type: ignore[arg-type]user_store=_StubGet(None), # type: ignore[arg-type]user=_user(id="me", role="user"),+ is_admin=False,user_id="someone-else",)assert excinfo.value.status_code == 403diff --git a/core/tests/switch_core/gateway/test_connectors.py b/core/tests/switch_core/gateway/test_connectors.pyindex 39f95eff1..a1b19b58d 100644--- a/core/tests/switch_core/gateway/test_connectors.py+++ b/core/tests/switch_core/gateway/test_connectors.py@@ -7,8 +7,16 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.db.models import ApiKey, ServerConnector, 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.connectors import delete_connector+_USER_STORE = UserStore()+++async def _is_admin(session: AsyncSession, user: User) -> bool:+ """The bit `get_tenant_is_admin` hands the route, resolved the same way."""+ return await _USER_STORE.administers(session, user)+class _StubLifecycle:"""Records remove() calls so we can assert whether deletion happened."""@@ -78,6 +86,7 @@ class TestDeleteConnectorAuthorization:api_key_store=ApiKeyStore(),connector_lifecycle=lifecycle, # type: ignore[arg-type]user=other,+ is_admin=await _is_admin(session, other),)assert exc.value.status_code == 403@@ -99,6 +108,7 @@ class TestDeleteConnectorAuthorization:api_key_store=ApiKeyStore(),connector_lifecycle=lifecycle, # type: ignore[arg-type]user=owner,+ is_admin=await _is_admin(session, owner),)assert result == {"ok": True}@@ -121,6 +131,7 @@ class TestDeleteConnectorAuthorization:api_key_store=ApiKeyStore(),connector_lifecycle=lifecycle, # type: ignore[arg-type]user=admin,+ is_admin=await _is_admin(session, admin),)assert result == {"ok": True}@@ -142,6 +153,7 @@ class TestDeleteConnectorAuthorization:api_key_store=ApiKeyStore(),connector_lifecycle=lifecycle, # type: ignore[arg-type]user=user,+ is_admin=await _is_admin(session, user),)assert exc.value.status_code == 404diff --git a/core/tests/switch_core/gateway/test_reference_types_routes.py b/core/tests/switch_core/gateway/test_reference_types_routes.pyindex 7ffdaa416..58f81fb54 100644--- a/core/tests/switch_core/gateway/test_reference_types_routes.py+++ b/core/tests/switch_core/gateway/test_reference_types_routes.py@@ -20,7 +20,7 @@ from 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 RoomLinkStorefrom 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, get_tenant_is_adminfrom switch_core.gateway.dependencies import (get_config,get_resource_service,@@ -49,6 +49,11 @@ _USER_STORE = UserStore()_REFERENCE_STORE = ReferenceStore()+async def _is_admin(session: AsyncSession, user: User) -> bool:+ """The bit `get_tenant_is_admin` hands the route, resolved the same way."""+ return await _USER_STORE.administers(session, user)++def _resource_service(session_factory: async_sessionmaker[AsyncSession],) -> ResourceService:@@ -142,12 +147,13 @@ 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- # 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()+ # Authorizing reads the tenant-admin bit before the route reaches the+ # resource service, and this app never runs `get_current_user`'s+ # `tenant_scope`, so the real dependency would refuse rather than answer+ # (`UserStore.administers`). These tests are about routing and body+ # validation, so the bit is supplied directly.+ app.dependency_overrides[get_tenant_is_admin] = lambda: Falseapp.dependency_overrides[get_config] = lambda: Noneapp.dependency_overrides[get_resource_service] = lambda: Nonereturn app@@ -219,7 +225,9 @@ class TestReferenceTypeCrudRoutes:assert created.shadowed_by_builtin is Falseassert created.value_schema["properties"]["urls"]- listed = await list_reference_types(session, svc, _USER_STORE, alice)+ listed = await list_reference_types(+ session, svc, _USER_STORE, alice, await _is_admin(session, alice)+ )by_slug = {t.type: t for t in listed}assert "notion" in by_slugassert by_slug["notion"].owner_name == "alice"@@ -228,7 +236,9 @@ class TestReferenceTypeCrudRoutes:assert by_slug["github"].owner_name is Noneassert by_slug["github"].value_hint- owned = await list_owned_reference_types(session, svc, _USER_STORE, alice)+ owned = await list_owned_reference_types(+ session, svc, _USER_STORE, alice, await _is_admin(session, alice)+ )assert [t.type for t in owned] == ["notion"]async def test_a_private_type_is_invisible_to_another_user(@@ -242,11 +252,16 @@ class TestReferenceTypeCrudRoutes:_create_request("notion"), session, svc, _USER_STORE, alice)- listed = await list_reference_types(session, svc, _USER_STORE, bob)+ listed = await list_reference_types(+ session, svc, _USER_STORE, bob, await _is_admin(session, bob)+ )assert "notion" not in {t.type for t in listed}assert (- await list_owned_reference_types(session, svc, _USER_STORE, bob) == []+ await list_owned_reference_types(+ session, svc, _USER_STORE, bob, await _is_admin(session, bob)+ )+ == [])async def test_invalid_slug_is_400(@@ -314,6 +329,7 @@ class TestReferenceTypeCrudRoutes:svc,_USER_STORE,alice,+ await _is_admin(session, alice),)assert updated.display_name == "Notion Workspace"@@ -325,6 +341,7 @@ class TestReferenceTypeCrudRoutes:svc,_USER_STORE,bob,+ await _is_admin(session, bob),)assert exc.value.status_code == 403@@ -343,6 +360,7 @@ class TestReferenceTypeCrudRoutes:svc,_USER_STORE,alice,+ await _is_admin(session, alice),)assert exc.value.status_code == 404@@ -358,12 +376,15 @@ class TestReferenceTypeCrudRoutes:)response = await delete_reference_type(- "notion", session, svc, _USER_STORE, alice+ "notion", session, svc, alice, await _is_admin(session, alice))assert response.deleted_type == "notion"assert (- await list_owned_reference_types(session, svc, _USER_STORE, alice) == []+ await list_owned_reference_types(+ session, svc, _USER_STORE, alice, await _is_admin(session, alice)+ )+ == [])async def test_delete_of_a_type_in_use_is_409(@@ -390,10 +411,13 @@ class TestReferenceTypeCrudRoutes:svc,_USER_STORE,alice,+ await _is_admin(session, alice),)with pytest.raises(HTTPException) as exc:- await delete_reference_type("notion", session, svc, _USER_STORE, alice)+ await delete_reference_type(+ "notion", session, svc, alice, await _is_admin(session, alice)+ )assert exc.value.status_code == 409assert "cannot be deleted" in exc.value.detail@@ -428,11 +452,19 @@ class TestTypeDisplayName:svc,_USER_STORE,alice,+ await _is_admin(session, alice),)assert created.type_display_name == "Notion"- fetched = await get_reference(created.id, session, svc, _USER_STORE, alice)+ fetched = await get_reference(+ created.id,+ session,+ svc,+ _USER_STORE,+ alice,+ await _is_admin(session, alice),+ )assert fetched.type_display_name == "Notion"async def test_an_unresolvable_slug_maps_to_none(diff --git a/core/tests/switch_core/gateway/test_room_resource_read_authz.py b/core/tests/switch_core/gateway/test_room_resource_read_authz.pyindex fd9dbce9b..d1d32fb20 100644--- a/core/tests/switch_core/gateway/test_room_resource_read_authz.py+++ b/core/tests/switch_core/gateway/test_room_resource_read_authz.py@@ -36,6 +36,11 @@ _USER_STORE = UserStore()_AGENT_STORE = AgentStore()+async def _is_admin(session: AsyncSession, user: User) -> bool:+ """The bit `get_tenant_is_admin` hands the route, resolved the same way."""+ return await _USER_STORE.administers(session, user)++def _svc(session_factory: async_sessionmaker[AsyncSession]) -> ResourceService:return ResourceService(reference_store=ReferenceStore(),@@ -88,6 +93,7 @@ class TestRoomResourceReadAuthz:_AGENT_STORE,_ROOM_STORE,other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -109,6 +115,7 @@ class TestRoomResourceReadAuthz:_AGENT_STORE,_ROOM_STORE,other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -123,7 +130,13 @@ class TestRoomResourceReadAuthz:with pytest.raises(HTTPException) as exc:await detach_document_from_room(- room.id, "any-doc", session, svc, _ROOM_STORE, other+ room.id,+ "any-doc",+ session,+ svc,+ _ROOM_STORE,+ other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -138,7 +151,13 @@ class TestRoomResourceReadAuthz:with pytest.raises(HTTPException) as exc:await detach_reference_from_room(- room.id, "any-ref", session, svc, _ROOM_STORE, other+ room.id,+ "any-ref",+ session,+ svc,+ _ROOM_STORE,+ other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -153,7 +172,13 @@ class TestRoomResourceReadAuthz:with pytest.raises(HTTPException) as exc:await detach_package_from_room(- room.id, "any-pkg", session, svc, _ROOM_STORE, other+ room.id,+ "any-pkg",+ session,+ svc,+ _ROOM_STORE,+ other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -176,6 +201,7 @@ class TestRoomResourceReadAuthz:_AGENT_STORE,_ROOM_STORE,owner,+ await _is_admin(session, owner),)== [])@@ -189,5 +215,6 @@ class TestRoomResourceReadAuthz:_AGENT_STORE,_ROOM_STORE,owner,+ await _is_admin(session, owner),)assert exc.value.status_code == 404diff --git a/core/tests/switch_core/gateway/test_room_write_authz.py b/core/tests/switch_core/gateway/test_room_write_authz.pyindex 1b352078d..0cd97809a 100644--- a/core/tests/switch_core/gateway/test_room_write_authz.py+++ b/core/tests/switch_core/gateway/test_room_write_authz.py@@ -31,6 +31,16 @@ _ROOM_STORE = RoomStore()_USER_STORE = UserStore()+async def _is_admin(session: AsyncSession, user: User) -> bool:+ """The bit `get_tenant_is_admin` hands the route, resolved the same way.++ Passing a literal here would test the handler against an admin bit no+ dependency could have produced; reading it through the store keeps the+ role on the user row meaningful.+ """+ return await _USER_STORE.administers(session, user)++def _resource_service(session_factory: async_sessionmaker[AsyncSession],) -> ResourceService:@@ -103,7 +113,14 @@ class TestAttachReferenceRoomWriteAuthz:with pytest.raises(HTTPException) as exc:await attach_reference_to_room(- room.id, ref.id, session, svc, _ROOM_STORE, _USER_STORE, other+ room.id,+ ref.id,+ session,+ svc,+ _ROOM_STORE,+ _USER_STORE,+ other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -119,7 +136,14 @@ class TestAttachReferenceRoomWriteAuthz:svc = _resource_service(session_factory)detail = await attach_reference_to_room(- room.id, ref.id, session, svc, _ROOM_STORE, _USER_STORE, owner+ room.id,+ ref.id,+ session,+ svc,+ _ROOM_STORE,+ _USER_STORE,+ owner,+ await _is_admin(session, owner),)assert detail.id == ref.id@@ -137,7 +161,14 @@ class TestAttachReferenceRoomWriteAuthz:svc = _resource_service(session_factory)detail = await attach_reference_to_room(- room.id, ref.id, session, svc, _ROOM_STORE, _USER_STORE, admin+ room.id,+ ref.id,+ session,+ svc,+ _ROOM_STORE,+ _USER_STORE,+ admin,+ await _is_admin(session, admin),)assert detail.id == ref.id@@ -161,7 +192,14 @@ class TestAttachReferenceRoomWriteAuthz:svc = _resource_service(session_factory)detail = await attach_reference_to_room(- room.id, ref.id, session, svc, _ROOM_STORE, _USER_STORE, other+ room.id,+ ref.id,+ session,+ svc,+ _ROOM_STORE,+ _USER_STORE,+ other,+ await _is_admin(session, other),)assert detail.id == ref.id@@ -176,7 +214,14 @@ class TestAttachReferenceRoomWriteAuthz:with pytest.raises(HTTPException) as exc:await attach_reference_to_room(- "missing-room", ref.id, session, svc, _ROOM_STORE, _USER_STORE, user+ "missing-room",+ ref.id,+ session,+ svc,+ _ROOM_STORE,+ _USER_STORE,+ user,+ await _is_admin(session, user),)assert exc.value.status_code == 404@@ -196,7 +241,13 @@ class TestCreateLinkedRoomWriteAuthz:with pytest.raises(HTTPException) as exc:await create_linked_room(- source.id, req, session, svc, _ROOM_STORE, other+ source.id,+ req,+ session,+ svc,+ _ROOM_STORE,+ other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -213,7 +264,13 @@ class TestCreateLinkedRoomWriteAuthz:req = LinkedRoomCreateRequest(target_room_id=target.id, label="rel")detail = await create_linked_room(- source.id, req, session, svc, _ROOM_STORE, owner+ source.id,+ req,+ session,+ svc,+ _ROOM_STORE,+ owner,+ await _is_admin(session, owner),)assert detail.target_room_id == target.id@@ -237,7 +294,13 @@ class TestDeleteLinkedRoomWriteAuthz:with pytest.raises(HTTPException) as exc:await delete_linked_room(- source.id, target.id, session, svc, _ROOM_STORE, other+ source.id,+ target.id,+ session,+ svc,+ _ROOM_STORE,+ other,+ await _is_admin(session, other),)assert exc.value.status_code == 403@@ -257,7 +320,13 @@ class TestDeleteLinkedRoomWriteAuthz:)resp = await delete_linked_room(- source.id, target.id, session, svc, _ROOM_STORE, owner+ source.id,+ target.id,+ session,+ svc,+ _ROOM_STORE,+ owner,+ await _is_admin(session, owner),)assert resp.status_code == 204diff --git a/core/tests/switch_core/gateway/test_template_routes.py b/core/tests/switch_core/gateway/test_template_routes.pyindex 490c37de6..4b42d6330 100644--- a/core/tests/switch_core/gateway/test_template_routes.py+++ b/core/tests/switch_core/gateway/test_template_routes.py@@ -31,6 +31,12 @@ from tests.switch_core.gateway.agent_route_harness import add_user_TEMPLATE_STORE = TemplateStore()_USER_STORE = UserStore()++async def _is_admin(session: AsyncSession, user: object) -> bool:+ """The bit `get_tenant_is_admin` hands the route, resolved the same way."""+ return await _USER_STORE.administers(session, user) # type: ignore[arg-type]++# Awkward on purpose: CRLF, a tab, trailing spaces, unicode, no final newline._AWKWARD_DOCUMENT = ("params:\r\n"@@ -290,6 +296,7 @@ class TestOwnership:session,_TEMPLATE_STORE,bob,+ await _is_admin(session, bob),)assert exc.value.status_code == 403assert await _TEMPLATE_STORE.get(session, created.id) is not None # type: ignore[attr-defined]@@ -312,6 +319,7 @@ class TestOwnership:_USER_STORE,_config(),bob,+ await _is_admin(session, bob),)assert exc.value.status_code == 403@@ -349,6 +357,7 @@ class TestOwnership:session,_TEMPLATE_STORE,alice,+ await _is_admin(session, alice),)assert result.deleted_id == created.id # type: ignore[attr-defined]assert await _TEMPLATE_STORE.get(session, created.id) is None # type: ignore[attr-defined]@@ -367,6 +376,7 @@ class TestOwnership:session,_TEMPLATE_STORE,admin,+ await _is_admin(session, admin),)assert await _TEMPLATE_STORE.get(session, created.id) is None # type: ignore[attr-defined]@@ -387,6 +397,7 @@ class TestOwnership:_USER_STORE,_config(),admin,+ await _is_admin(session, admin),)assert updated.description == "tidied up by an admin"# Still Alice's — an admin edit is not a transfer of ownership.@@ -400,7 +411,13 @@ class TestOwnership:await session.commit()with pytest.raises(HTTPException) as exc:- await delete_template("nope", session, _TEMPLATE_STORE, alice)+ await delete_template(+ "nope",+ session,+ _TEMPLATE_STORE,+ alice,+ await _is_admin(session, alice),+ )assert exc.value.status_code == 404@@ -421,6 +438,7 @@ class TestUpdate:_USER_STORE,_config(),alice,+ await _is_admin(session, alice),)assert updated.version == 2assert updated.content == "room:\n name: changed\n"@@ -441,6 +459,7 @@ class TestUpdate:_USER_STORE,_config(),alice,+ await _is_admin(session, alice),)assert updated.version == 1assert updated.description == "clearer"@@ -462,6 +481,7 @@ class TestUpdate:_USER_STORE,_config(template_max_bytes=100),alice,+ await _is_admin(session, alice),)assert exc.value.status_code == 413stored = await _TEMPLATE_STORE.get(session, created.id) # type: ignore[attr-defined]@@ -485,5 +505,6 @@ class TestUpdate:_USER_STORE,_config(),alice,+ await _is_admin(session, alice),)assert exc.value.status_code == 409diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.pyindex f4ceed200..8aaa0d3b2 100644--- a/core/tests/switch_core/test_rooms_yaml.py+++ b/core/tests/switch_core/test_rooms_yaml.py@@ -1052,12 +1052,13 @@ 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()+ # Not an administrator of anything: this exercises body parsing, and the+ # caller owns the room it creates.+ is_admin = Falseuser = 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)@@ -1074,7 +1075,7 @@ async def test_endpoint_json_body(env):request.body.return_value = bodyasync with env["session_factory"]() as session:- result = await create_room_from_yaml(request, session, svc, user_store, user)+ result = await create_room_from_yaml(request, session, svc, user, is_admin)assert result.room_name == "carol local-deploy"# Non-string yaml value → 400.@@ -1082,5 +1083,5 @@ async def test_endpoint_json_body(env):request.body.return_value = bad_bodyasync with env["session_factory"]() as session:with pytest.raises(HTTPException) as exc_info:- await create_room_from_yaml(request, session, svc, user_store, user)+ await create_room_from_yaml(request, session, svc, user, is_admin)assert exc_info.value.status_code == 400diff --git a/docs/old/multi-tenancy-phase2-tenants.md b/docs/old/multi-tenancy-phase2-tenants.mdindex ebc636b93..931048675 100644--- a/docs/old/multi-tenancy-phase2-tenants.md+++ b/docs/old/multi-tenancy-phase2-tenants.md@@ -70,6 +70,37 @@ This is a bigger change than the other three tickets put together, and it isthe reason they cannot ship without it. It should be its own ticket, sequencedfirst. **This is the decision I want confirmed before anything is built.**+### What a workspace admin actually gets, which is more than a list of routes++The tempting way to describe this grant is to enumerate the admin-gated routes+and classify each one. That description is incomplete, and incomplete in the+direction that matters.++`authz.can()` and `can_manage()` both short-circuit on `Principal.is_admin`+*before* they look at ownership or visibility. The moment `tenant_members.role`+feeds that bit, an `owner` or `admin` of a workspace holds read, write and+delete on **every owned resource in it** — rooms, references, documents,+packages — and management of every agent in it, whoever owns them. No route+opts into this; it falls out of the one short-circuit. The widest path is+`require_room_access`, which is not an explicitly admin-gated route at all.++**The least obvious case, and the one to decide on purpose: a private room+between a colleague and their agent.** A workspace admin can read it, write in+it, and delete it. "Workspace administrators can read private rooms in their+workspace" is a sentence someone should agree to rather than discover.++This is invisible in tenant zero today. After the backfill migration the only+`owner`/`admin` rows belong to deployment operators, who held all of it through+the global bypass already. It becomes real the first time a person is invited+into a workspace as an admin — that is, with §5.++**Chosen: accept it for this phase, and write it down here rather than leave it+implicit.** The alternative is a second, narrower bit — "administers the+workspace's configuration" as distinct from "may act on its contents" — which+is a real distinction and a real amount of work, and belongs to whichever phase+takes on resource-level sharing. What must not happen is shipping the wide+grant while the design describes the narrow one.+## 3. How a request picks its tenantA request must act in exactly one tenant — Phase 1 depends on that and nothing