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
Read the organization only when the membership row does not answer
Petr Bauche06fc5b2469a
diff --git a/core/switch_core/authz.py b/core/switch_core/authz.pyindex 51ed907db..171150048 100644--- a/core/switch_core/authz.py+++ b/core/switch_core/authz.py@@ -86,6 +86,19 @@ def administers_tenant()+def effective_tenant_role(+ *, tenant_role: str | None, organization_role: str | None+) -> str | None:+ """The role someone acts with in a workspace: their membership role, or+ `ORGANIZATION_ADMIN_TENANT_ROLE` when they are its organization's+ `org_admin` and hold no higher role there. None when they hold neither."""+ if tenant_role in TENANT_ADMIN_ROLES:+ return tenant_role+ if organization_role == ORGANIZATION_ADMIN_ROLE:+ return ORGANIZATION_ADMIN_TENANT_ROLE+ return tenant_role++def owns_tenant(*, is_operator: bool, tenant_role: str | None) -> bool:"""Whether a caller may dispose of the tenant they hold `tenant_role` in.diff --git a/core/switch_core/chats/service.py b/core/switch_core/chats/service.pyindex 95915543f..40ee8e045 100644--- a/core/switch_core/chats/service.py+++ b/core/switch_core/chats/service.py@@ -46,7 +46,7 @@ from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.addressing import allows_on_behalf_of, parse_policy-from switch_core.authz import administers_tenant+from switch_core.authz import ORGANIZATION_ADMIN_ROLE, administers_tenantfrom switch_core.bridges.agent.protocol.agent_connections import AgentConnectionRegistryfrom switch_core.bridges.agent.registration_bootstrap import is_bootstrap_ownerfrom switch_core.chats import MEMBER_CLIENT_TYPE@@ -338,10 +338,13 @@ class ChatService:self, session: AsyncSession, tenant_id: str, user_id: str) -> bool:"""Whether `user_id` stands in `tenant_id`: a membership row, or- `org_admin` of its organization."""+ `org_admin` of its organization, read only when there is no row. Asked+ on every chat read and write."""+ if await self._user_store.tenant_role(session, tenant_id, user_id) is not None:+ return Truereturn (- await self._user_store.effective_tenant_role(session, tenant_id, user_id)- is not None+ await self._user_store.organization_role(session, tenant_id, user_id)+ == ORGANIZATION_ADMIN_ROLE)async def _room(self, session: AsyncSession, tenant_id: str, room_id: str) -> Room:diff --git a/core/switch_core/db/stores/user_store.py b/core/switch_core/db/stores/user_store.pyindex d586f632b..860226bd7 100644--- a/core/switch_core/db/stores/user_store.py+++ b/core/switch_core/db/stores/user_store.py@@ -10,10 +10,9 @@ from sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSessionfrom switch_core.authz import (- ORGANIZATION_ADMIN_ROLE,- ORGANIZATION_ADMIN_TENANT_ROLE,TENANT_ADMIN_ROLES,administers_tenant,+ effective_tenant_role,owns_tenant,)from switch_core.db.models import (@@ -515,13 +514,12 @@ class UserStore:`tenants.organization_id` `NOT NULL`; nobody holds a role in it, andthe policy would refuse the read, so it is not made."""- tenant = await session.get(Tenant, tenant_id)- if tenant is None or tenant.organization_id is None:- return None- member = await session.get(- OrganizationMember, (tenant.organization_id, user_id)+ role: str | None = await session.scalar(+ select(OrganizationMember.role)+ .join(Tenant, Tenant.organization_id == OrganizationMember.organization_id)+ .where(Tenant.id == tenant_id, OrganizationMember.user_id == user_id))- return member.role if member is not None else None+ return roleasync def administers_by_role(self, session: AsyncSession, tenant_id: str, user_id: str@@ -530,9 +528,22 @@ class UserStore:(a workspace admin or owner membership, or `org_admin` of itsorganization), leaving the operator flag out. An operator who doesnot is there on `platform_access`."""+ return await self._administers(session, tenant_id, user_id, is_operator=False)++ async def _administers(+ self, session: AsyncSession, tenant_id: str, user_id: str, *, is_operator: bool+ ) -> bool:+ """`authz.administers_tenant`, reading the organization only when the+ membership row does not already answer: most callers are a+ workspace's own admins and members."""+ tenant_role = await self.tenant_role(session, tenant_id, user_id)+ if administers_tenant(+ is_operator=is_operator, tenant_role=tenant_role, organization_role=None+ ):+ return Truereturn administers_tenant(- is_operator=False,- tenant_role=await self.tenant_role(session, tenant_id, user_id),+ is_operator=is_operator,+ tenant_role=tenant_role,organization_role=await self.organization_role(session, tenant_id, user_id),)@@ -546,12 +557,10 @@ class UserStore:role = await self.tenant_role(session, tenant_id, user_id)if role in TENANT_ADMIN_ROLES:return role- if (- await self.organization_role(session, tenant_id, user_id)- == ORGANIZATION_ADMIN_ROLE- ):- return ORGANIZATION_ADMIN_TENANT_ROLE- return role+ return effective_tenant_role(+ tenant_role=role,+ organization_role=await self.organization_role(session, tenant_id, user_id),+ )async def list_tenant_members(self, session: AsyncSession@@ -604,10 +613,8 @@ class UserStore:"administer a workspace is only answerable about a particular ""one")- return administers_tenant(- is_operator=user.role == "admin",- tenant_role=await self.tenant_role(session, tenant_id, user.id),- organization_role=await self.organization_role(session, tenant_id, user.id),+ return await self._administers(+ session, tenant_id, user.id, is_operator=user.role == "admin")async def owns(self, session: AsyncSession, user: User) -> bool:diff --git a/core/switch_core/gateway/tenants.py b/core/switch_core/gateway/tenants.pyindex 9ed127262..23a0f1b5d 100644--- a/core/switch_core/gateway/tenants.py+++ b/core/switch_core/gateway/tenants.py@@ -10,7 +10,12 @@ from fastapi.responses import JSONResponsefrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker-from switch_core.authz import ORGANIZATION_ADMIN_ROLE, ORGANIZATION_ADMIN_TENANT_ROLE+from switch_core.authz import (+ ORGANIZATION_ADMIN_ROLE,+ ORGANIZATION_ADMIN_TENANT_ROLE,+ administers_tenant,+ effective_tenant_role,+)from switch_core.bridges.agent.protocol.agent_core import AgentCorefrom switch_core.bridges.agent.registration_bootstrap import is_bootstrap_ownerfrom switch_core.clients.client_lifecycle_service import ClientLifecycleService@@ -56,7 +61,6 @@ from switch_core.gateway.auth import (get_authenticated_caller,get_authenticated_user_id,get_current_user,- get_tenant_is_admin,get_tenant_is_owner,list_tenant_memberships,may_bind_tenant,@@ -281,17 +285,21 @@ async def current_tenant(session: Annotated[AsyncSession, Depends(get_session)],user_store: Annotated[UserStore, Depends(get_user_store)],user: Annotated[User, Depends(get_current_user)],- is_admin: Annotated[bool, Depends(get_tenant_is_admin)],) -> CurrentTenantResponse:"""The tenant this request is bound to, and the caller's standing in it.A client needs the id for every `/tenants/{tenant_id}/...` path, and thebinding is settled server-side (see `_resolve_tenant_id`), so this is the- one place it can ask rather than guess from `GET /tenants`.+ one place it can ask rather than guess from `GET /tenants`. The two roles+ are read once each, and every answer below is worked out from them."""tenant_id = require_tenant_id()tenant = await session.get(Tenant, tenant_id)- role = await user_store.effective_tenant_role(session, tenant_id, user.id)+ tenant_role = await user_store.tenant_role(session, tenant_id, user.id)+ organization_role = await user_store.organization_role(session, tenant_id, user.id)+ role = effective_tenant_role(+ tenant_role=tenant_role, organization_role=organization_role+ )if role is None and request.state.platform_access:# The platform operator, there on the operator flag alone, acts as# an admin and holds no role to report.@@ -303,11 +311,13 @@ async def current_tenant(slug=tenant.slug,name=tenant.name,role=role,- organization_role=await user_store.organization_role(- session, tenant_id, user.id- ),+ organization_role=organization_role,organization_id=tenant.organization_id,- administers=is_admin,+ administers=administers_tenant(+ is_operator=user.role == "admin",+ tenant_role=tenant_role,+ organization_role=organization_role,+ ),)diff --git a/core/tests/switch_core/gateway/test_tenant_api_routes.py b/core/tests/switch_core/gateway/test_tenant_api_routes.pyindex 27bcd51d7..47d74e12b 100644--- a/core/tests/switch_core/gateway/test_tenant_api_routes.py+++ b/core/tests/switch_core/gateway/test_tenant_api_routes.py@@ -74,6 +74,7 @@ from switch_core.gateway.invite_mail import (from switch_core.gateway.tenants import router as tenants_routerfrom switch_core.keys import Keyringfrom tests.ownership import NeverOwned+from tests.switch_core.statement_counts import StatementCounts_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow_KEYRING = Keyring.parse("test:" + _SECRET, legacy_secret=None)@@ -1733,6 +1734,55 @@ def _window() -> dict[str, str]:class TestCurrentTenantRoute:+ async def test_a_members_request_reads_the_organization_once_at_most(+ self,+ session_factory: async_sessionmaker[AsyncSession],+ statement_counts: StatementCounts,+ ) -> None:+ """Checking a member's role reads their membership row, and the+ organization only when that row does not answer, so a workspace in an+ organization costs a member no more statements than one without."""+ tenant_id = f"tenant-{uuid.uuid4().hex[:8]}"+ organization_id = f"org-{uuid.uuid4().hex[:8]}"+ async with session_factory() as session:+ session.add(+ Organization(id=organization_id, slug=organization_id, name="O")+ )+ await session.flush()+ session.add(+ Tenant(+ id=tenant_id,+ slug=tenant_id,+ name=tenant_id,+ organization_id=organization_id,+ )+ )+ await session.commit()+ user_id = await _make_member(+ session_factory,+ name=f"counted-{uuid.uuid4().hex[:6]}",+ tenant_id=tenant_id,+ role="member",+ )+ async with session_factory() as session:+ session.add(+ OrganizationMember(+ organization_id=organization_id, user_id=user_id, role="member"+ )+ )+ await session.commit()+ token = _token(user_id, "[email protected]", tenant_id)++ async with _client(+ statement_counts.wrap(_app(session_factory)), token+ ) as client:+ response = await client.get("/tenants/current")++ assert response.status_code == 200, response.text+ statements = statement_counts.scopes[-1].statements+ assert sum("organization_members" in s for s in statements) == 1+ assert len(statements) <= 7, statements+async def test_a_member_is_told_the_workspace_they_are_bound_to(self, session_factory: async_sessionmaker[AsyncSession]) -> None: