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
Count an org_admin as standing in their organization's workspaces everywhere
Petr Bauch41e1ee241bd3
diff --git a/core/switch_core/connections/broker.py b/core/switch_core/connections/broker.pyindex 70c3284cb..a8e9f96ea 100644--- a/core/switch_core/connections/broker.py+++ b/core/switch_core/connections/broker.py@@ -74,10 +74,10 @@ from switch_core.db.models import (ServiceConnection,ServiceGrant,ServiceTokenIssuance,- TenantMember,require_tenant_id,)from switch_core.db.session_scope import tenant_session+from switch_core.db.standing import stands_infrom switch_core.db.stores.service_connection_store import (ServiceConnectionBusy,ServiceConnectionStore,@@ -543,12 +543,7 @@ class ServiceBroker:403, FORBIDDEN, "This agent has no owner to act for.", retryable=False)owner_id = agent.owner_id- if (- await session.get(- TenantMember, (tenant_id, owner_id), populate_existing=True- )- is None- ):+ if not await stands_in(session, tenant_id, owner_id):raise ServiceError(403,FORBIDDEN,diff --git a/core/switch_core/db/standing.py b/core/switch_core/db/standing.pynew file mode 100644index 000000000..cf1a2ce20--- /dev/null+++ b/core/switch_core/db/standing.py@@ -0,0 +1,48 @@+"""Whether someone stands in a workspace: a membership row there, or `org_admin`+of the organization it belongs to, who administers it without one.++For the places that ask the question in SQL, or of a bare session, rather+than through `UserStore.effective_tenant_role`. A check that read only+`tenant_members` would treat an organization's admin as an outsider in every+workspace they have not been added to by hand.+"""++from __future__ import annotations++from sqlalchemy import ColumnElement, exists, or_, select+from sqlalchemy.ext.asyncio import AsyncSession+from sqlalchemy.orm import InstrumentedAttribute++from switch_core.authz import ORGANIZATION_ADMIN_ROLE+from switch_core.db.models import OrganizationMember, Tenant, TenantMember+++def organization_admin_of(+ tenant_id: str, user_id: ColumnElement[str] | InstrumentedAttribute[str] | str+) -> ColumnElement[bool]:+ """`user_id` is `org_admin` of the organization `tenant_id` belongs to."""+ return exists().where(+ OrganizationMember.user_id == user_id,+ OrganizationMember.role == ORGANIZATION_ADMIN_ROLE,+ OrganizationMember.organization_id+ == select(Tenant.organization_id)+ .where(Tenant.id == tenant_id)+ .scalar_subquery(),+ )+++def stands_in_tenant(+ tenant_id: str, user_id: ColumnElement[str] | InstrumentedAttribute[str] | str+) -> ColumnElement[bool]:+ """`user_id` holds a membership row in `tenant_id`, or administers it as+ its organization's `org_admin`."""+ return or_(+ exists().where(+ TenantMember.tenant_id == tenant_id, TenantMember.user_id == user_id+ ),+ organization_admin_of(tenant_id, user_id),+ )+++async def stands_in(session: AsyncSession, tenant_id: str, user_id: str) -> bool:+ return bool(await session.scalar(select(stands_in_tenant(tenant_id, user_id))))diff --git a/core/switch_core/db/stores/service_connection_store.py b/core/switch_core/db/stores/service_connection_store.pyindex 9e01d5f0b..bda962736 100644--- a/core/switch_core/db/stores/service_connection_store.py+++ b/core/switch_core/db/stores/service_connection_store.py@@ -21,9 +21,9 @@ from switch_core.db.models import (ServiceConnection,ServiceGrant,ServiceTokenIssuance,- TenantMember,require_tenant_id,)+from switch_core.db.standing import stands_in_tenantclass ServiceConnectionBusy(Exception):@@ -392,12 +392,7 @@ class ServiceConnectionStore:ServiceGrant.id == ServiceTokenIssuance.grant_id,))- member = exists(- select(TenantMember.user_id).where(- TenantMember.tenant_id == tenant_id,- TenantMember.user_id == ServiceTokenIssuance.owner_id,- )- )+ member = stands_in_tenant(tenant_id, ServiceTokenIssuance.owner_id)controller_live = exists(select(AgentController.id).where(AgentController.tenant_id == tenant_id,diff --git a/core/switch_core/delivery/recipient.py b/core/switch_core/delivery/recipient.pyindex bc33e718a..f816360b0 100644--- a/core/switch_core/delivery/recipient.py+++ b/core/switch_core/delivery/recipient.py@@ -30,6 +30,7 @@ from typing import TYPE_CHECKING, Literal, NamedTuple, Protocolfrom sqlalchemy import selectfrom switch_core.attachments import parse_attachment_group+from switch_core.authz import ORGANIZATION_ADMIN_TENANT_ROLE, TENANT_ADMIN_ROLESfrom switch_core.bridges.agent.commands import (AGENT_GREETINGS,COMMANDS_BY_NAME,@@ -68,6 +69,7 @@ from switch_core.clients.mentions import (from switch_core.clients.room_meta import RoomMetafrom switch_core.db.models import Agent, CloudMachine, TenantMemberfrom switch_core.db.session_scope import tenant_session+from switch_core.db.standing import organization_admin_offrom switch_core.db.stores.hosted_machine_store import owner_stoppedfrom switch_core.delivery.addressing import (ADDRESSING_DENIED_MESSAGE,@@ -1748,17 +1750,25 @@ class AgentRecipient:principal = await self._addressing.resolve_sender(session, sender, content)if principal is None or principal.kind != "user" or not principal.user_ids:return None+ tenant_id = self.tenant_idroles = set(await session.scalars(select(TenantMember.role).where(- TenantMember.user_id.in_(principal.user_ids)+ TenantMember.tenant_id == tenant_id,+ TenantMember.user_id.in_(principal.user_ids),)))- for role in ("owner", "admin", "member"):+ for role in TENANT_ADMIN_ROLES:if role in roles:return role- return None+ # An organization's admin administers the workspace without a+ # membership row, and is told to agents as an admin, as the workspace's+ # own pages show them.+ for user_id in principal.user_ids:+ if await session.scalar(select(organization_admin_of(tenant_id, user_id))):+ return ORGANIZATION_ADMIN_TENANT_ROLE+ return "member" if "member" in roles else Nonedef _sender_handle(self, event: InboundMessage) -> str:"""The @-handle to tag the message sender with.diff --git a/core/switch_core/gateway/hosted_controller.py b/core/switch_core/gateway/hosted_controller.pyindex 9c36aadb4..47a415438 100644--- a/core/switch_core/gateway/hosted_controller.py+++ b/core/switch_core/gateway/hosted_controller.py@@ -10,7 +10,8 @@ from sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.config import SwitchConfig-from switch_core.db.models import CloudMachine, TenantMember+from switch_core.db.models import CloudMachine+from switch_core.db.standing import stands_infrom switch_core.db.stores.hosted_machine_store import (MACHINE_CONNECT_TIMEOUT,CloudMachineStore,@@ -244,12 +245,7 @@ async def prepare(for workspace in await workspaces_on(factory, machine.id):with tenant_scope(workspace.tenant_id):async with factory() as scoped:- if (- await scoped.get(- TenantMember, (workspace.tenant_id, machine.owner_id)- )- is None- ):+ if not await stands_in(scoped, workspace.tenant_id, machine.owner_id):logger.warning("Cloud machine %s: its owner left workspace %s, so it runs no controller there.",machine.id,diff --git a/core/tests/switch_core/db/test_standing.py b/core/tests/switch_core/db/test_standing.pynew file mode 100644index 000000000..ce6ee8017--- /dev/null+++ b/core/tests/switch_core/db/test_standing.py@@ -0,0 +1,98 @@+"""Who stands in a workspace: a membership row, or `org_admin` of its+organization. Asked through the restricted role, from a workspace session,+as the broker, the token upkeep and the hosted controller ask it."""++from __future__ import annotations++import uuid++import pytest+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.models import (+ Organization,+ OrganizationMember,+ Tenant,+ TenantMember,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.standing import stands_in, stands_in_tenant+from tests.conftest import RLSHarness++pytestmark = pytest.mark.no_ambient_tenant+++def _id(prefix: str) -> str:+ return f"{prefix}-{uuid.uuid4().hex[:8]}"+++async def _organization(+ owner: async_sessionmaker[AsyncSession],+ *,+ in_workspace: dict[str, str],+ in_organization: dict[str, str],+) -> str:+ """A workspace in an organization of its own. `in_workspace` are given a+ membership row (user -> workspace role); `in_organization` an+ organization row only (user -> organization role)."""+ organization_id, tenant_id = _id("org"), _id("tenant")+ async with owner() 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="W", organization_id=organization_id+ )+ )+ for user_id in {*in_workspace, *in_organization}:+ if await session.get(User, user_id) is None:+ session.add(+ User(+ id=user_id,+ name=user_id,+ email=f"{user_id}@example.invalid",+ role="user",+ )+ )+ await session.flush()+ for user_id, role in in_workspace.items():+ session.add(TenantMember(tenant_id=tenant_id, user_id=user_id, role=role))+ for user_id, role in in_organization.items():+ session.add(+ OrganizationMember(+ organization_id=organization_id, user_id=user_id, role=role+ )+ )+ await session.commit()+ return tenant_id+++async def test_a_member_and_an_org_admin_stand_in_it_and_nobody_else(+ rls_harness: RLSHarness,+) -> None:+ member, admin, plain, outsider = (_id(name) for name in ("m", "a", "p", "o"))+ tenant_id = await _organization(+ rls_harness.owner,+ in_workspace={member: "member"},+ in_organization={admin: "org_admin", plain: "member"},+ )+ await _organization(+ rls_harness.owner, in_workspace={}, in_organization={outsider: "org_admin"}+ )++ async with tenant_session(rls_harness.restricted, tenant_id) as session:+ found = {+ user_id: await stands_in(session, tenant_id, user_id)+ for user_id in (member, admin, plain, outsider)+ }+ users = await session.scalars(+ select(User.id).where(+ User.id.in_([member, admin, plain, outsider]),+ stands_in_tenant(tenant_id, User.id),+ )+ )++ assert found == {member: True, admin: True, plain: False, outsider: False}+ assert set(users) == {member, admin}diff --git a/core/tests/switch_core/delivery/test_sender_role.py b/core/tests/switch_core/delivery/test_sender_role.pyindex 99e6d4780..7aa346307 100644--- a/core/tests/switch_core/delivery/test_sender_role.py+++ b/core/tests/switch_core/delivery/test_sender_role.py@@ -8,7 +8,14 @@ from types import SimpleNamespacefrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmakerfrom switch_core.bridges.agent.protocol.message_events import message_event-from switch_core.db.models import TENANT_ZERO_ID, TenantMember, User+from switch_core.db.models import (+ TENANT_ZERO_ID,+ Organization,+ OrganizationMember,+ Tenant,+ TenantMember,+ User,+)from switch_core.delivery.addressing import SenderPrincipalfrom switch_core.delivery.recipient import AgentRecipientfrom switch_core.transport.types import InboundMessage@@ -25,7 +32,7 @@ class _Addressing:def _recipient(principal: SenderPrincipal | None) -> SimpleNamespace:- return SimpleNamespace(_addressing=_Addressing(principal))+ return SimpleNamespace(_addressing=_Addressing(principal), tenant_id=TENANT_ZERO_ID)async def _member(session: AsyncSession, name: str, role: str) -> User:@@ -111,3 +118,40 @@ def test_the_role_rides_on_the_message() -> None:)assert event.payload.sender_role == "member" # type: ignore[union-attr]+++async def test_an_organization_admin_without_a_membership_is_an_admin(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """They administer the workspace through its organization, and agents+ are told so rather than that they hold no role."""+ async with session_factory() as session:+ organization = Organization(+ id="org-sender-role", slug="org-sender-role", name="O"+ )+ session.add(organization)+ await session.flush()+ tenant = await session.get(Tenant, TENANT_ZERO_ID)+ assert tenant is not None+ tenant.organization_id = organization.id+ oscar = User(name="oscar", email="[email protected]", role="user")+ session.add(oscar)+ await session.flush()+ session.add(+ OrganizationMember(+ organization_id=organization.id, user_id=oscar.id, role="org_admin"+ )+ )+ await session.flush()+ person = SenderPrincipal("user", "client-2", [oscar.id], None)++ assert (+ await AgentRecipient._sender_role(+ _recipient(person), # type: ignore[arg-type]+ session,+ "@oscar:test",+ {},+ )+ == "admin"+ )+ await session.rollback()