Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
[CHOO-3906] Record the operator's agents' admin decisions as platform access
Petr Bauch809152f3a33e
diff --git a/core/switch_core/bridges/agent/commands.py b/core/switch_core/bridges/agent/commands.pyindex c54bd67f7..ae7923552 100644--- a/core/switch_core/bridges/agent/commands.py+++ b/core/switch_core/bridges/agent/commands.py@@ -50,6 +50,7 @@ from switch_core.db.stores.session_activity_store import (from switch_core.db.stores.user_store import UserStorefrom switch_core.delivery.addressing import AddressingResolverfrom switch_core.events import CommandEvent+from switch_core.platform_access import administers_on_recordfrom switch_core.transport import RoomRefif TYPE_CHECKING:@@ -1327,7 +1328,15 @@ async def _may_remove_agent(if principal.kind == "user":for user_id in principal.user_ids:user = await session.get(User, user_id)- if user is not None and await host._user_store.administers(session, user):+ if user is not None and await administers_on_record(+ session,+ host.session_factory,+ host._user_store,+ user,+ target_type="agent",+ target_id=target.id,+ details={"event": "chat_command", "command": "remove_agent"},+ ):return Truereturn Falseif principal.kind == "agent":@@ -1399,14 +1408,16 @@ async def _manage_authority(user = await host._user_store.get(session, user_id)if user is None:continue- try:- require_manage(- Principal(user.id, await host._user_store.administers(session, user)),- agent.owner_id,- )+ if user.id == agent.owner_id or await administers_on_record(+ session,+ host.session_factory,+ host._user_store,+ user,+ target_type="agent",+ target_id=agent.id,+ details={"event": "chat_command", "command": "manage_agent"},+ ):return _Authority(user.id, None)- except PermissionError:- continuereturn _Authority(None, "Only the agent's owner or a workspace admin can rename or delete it.")diff --git a/core/switch_core/bridges/agent/protocol/agent_core.py b/core/switch_core/bridges/agent/protocol/agent_core.pyindex 4ca938067..7a157e695 100644--- a/core/switch_core/bridges/agent/protocol/agent_core.py+++ b/core/switch_core/bridges/agent/protocol/agent_core.py@@ -122,6 +122,7 @@ from switch_core.events import (ToolCallReport as RoomToolCallReport,)from switch_core.messages.recorded_types import MEMBERSHIP_EVENT_TYPE+from switch_core.platform_access import administers_on_recordfrom switch_core.room_wide_mention import (ROOM_WIDE_TARGET,is_reserved_mention_name,@@ -3137,8 +3138,14 @@ class AgentCore:owner_is_admin = Falseif agent.owner_id is not None:owner = await session.get(User, agent.owner_id)- owner_is_admin = owner is not None and await self.user_store.administers(- session, owner+ owner_is_admin = owner is not None and await administers_on_record(+ session,+ self.session_factory,+ self.user_store,+ owner,+ target_type="agent",+ target_id=agent.id,+ details={"event": "agent_acting"},)return agent, agent.owner_id, owner_is_admindiff --git a/core/switch_core/bridges/collaboration/install_service.py b/core/switch_core/bridges/collaboration/install_service.pyindex bb228b62a..4373fe576 100644--- a/core/switch_core/bridges/collaboration/install_service.py+++ b/core/switch_core/bridges/collaboration/install_service.py@@ -126,6 +126,7 @@ from switch_core.db.stores.messaging_install_store import (from switch_core.db.stores.user_store import UserStorefrom switch_core.db.tenant_lookup import tenant_of_messaging_installfrom switch_core.keys import Keyring+from switch_core.platform_access import administers_on_recordfrom switch_core.tenant_context import no_tenant, tenant_scopelogger = logging.getLogger(__name__)@@ -1048,7 +1049,15 @@ class MessagingInstallService:self, session: AsyncSession, burnt: MessagingInstallState, platform: str) -> None:user = await session.get(User, burnt.created_by_user_id)- if user is None or not await self._users.administers(session, user):+ if user is None or not await administers_on_record(+ session,+ self._session_factory,+ self._users,+ user,+ target_type="messaging_install",+ target_id=None,+ details={"event": "messaging_install", "platform": platform},+ ):raise InstallClaimNotPermitted(f"connecting the first {platform} chat turns {platform} on for ""this organisation, which only an admin can do. Ask an admin to "diff --git a/core/switch_core/platform_access.py b/core/switch_core/platform_access.pynew file mode 100644index 000000000..a0c56a172--- /dev/null+++ b/core/switch_core/platform_access.py@@ -0,0 +1,58 @@+"""The platform operator's admin rights outside a gateway request, on record.++An agent acts as its owner, and a chat account linked to a Switch user acts+as that user (`authz.py`). Where that person is the platform operator and+holds no role that administers the workspace, an admin decision made for+them rests on the operator flag alone: `platform_access`, which the+workspace's audit log records, as the gateway records the operator's own+writes (`gateway/auth.py`). Recorded where the decision is made rather than+per request, because only the decision uses the flag: an agent posting in a+room it belongs to does not, and its keepalives would bury the record.+"""++from __future__ import annotations++from typing import Any++from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.audit import AuditAction, record_audit_event+from switch_core.db.models import User, require_tenant_id+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.user_store import UserStore+++async def administers_on_record(+ session: AsyncSession,+ session_factory: async_sessionmaker[AsyncSession],+ user_store: UserStore,+ user: User,+ *,+ target_type: str,+ target_id: str | None,+ details: dict[str, Any],+) -> bool:+ """`UserStore.administers` for the workspace bound to `session`, recording+ `platform_access` when only the operator flag makes it true.++ Recorded on a session of its own and committed at once, so a read-only+ caller that never commits still leaves the record, and a caller whose+ transaction fails later does too.+ """+ tenant_id = require_tenant_id()+ if await user_store.administers_by_role(session, tenant_id, user.id):+ return True+ if user.role != "admin":+ return False+ async with tenant_session(session_factory, tenant_id) as record:+ await record_audit_event(+ record,+ tenant_id=tenant_id,+ actor_user_id=user.id,+ action=AuditAction.PLATFORM_ACCESS,+ target_type=target_type,+ target_id=target_id,+ details=details,+ )+ await record.commit()+ return Truediff --git a/core/tests/switch_core/bridges/agent/test_commands_remove_agent.py b/core/tests/switch_core/bridges/agent/test_commands_remove_agent.pyindex fea1030a7..f3c2a9f15 100644--- a/core/tests/switch_core/bridges/agent/test_commands_remove_agent.py+++ b/core/tests/switch_core/bridges/agent/test_commands_remove_agent.py@@ -91,9 +91,11 @@ class _Harness:async def _get_agent_id_by_alias(_session, _room_id, token): # type: ignore[no-untyped-def]return (aliases or {}).get(token)- async def _administers(_session, user): # type: ignore[no-untyped-def]+ async def _administers_on_record(_session, _factory, _users, user, **_kw): # type: ignore[no-untyped-def]return user.id in admins+ monkeypatch.setattr(commands, "administers_on_record", _administers_on_record)+async def _remove_agents_from_room(room_id, agent_ids, **_kw): # type: ignore[no-untyped-def]self.removed.append((room_id, list(agent_ids)))@@ -111,7 +113,7 @@ class _Harness:_room_role_store=None,_external_user_store=None,_connections=SimpleNamespace(live_connection_ids=lambda: set()),- _user_store=SimpleNamespace(administers=_administers),+ _user_store=None,_room_service=SimpleNamespace(remove_agents_from_room=_remove_agents_from_room),diff --git a/core/tests/switch_core/test_platform_access.py b/core/tests/switch_core/test_platform_access.pynew file mode 100644index 000000000..3aa5e89b2--- /dev/null+++ b/core/tests/switch_core/test_platform_access.py@@ -0,0 +1,115 @@+"""`administers_on_record`: an admin decision made for the platform operator+on the operator flag alone is recorded in the workspace's audit log, and one+made on a role anyone may hold is not."""++from __future__ import annotations++import uuid++from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.db.audit import AuditAction+from switch_core.db.models import (+ TENANT_ZERO_ID,+ AuditEvent,+ OrganizationMember,+ TenantMember,+ User,+)+from switch_core.db.session_scope import tenant_session+from switch_core.db.stores.user_store import UserStore+from switch_core.platform_access import administers_on_record+++async def _user(+ session_factory: async_sessionmaker[AsyncSession],+ *,+ role: str,+ tenant_role: str | None = None,+ organization_role: str | None = None,+) -> User:+ async with session_factory() as session:+ user = User(+ name=f"u-{uuid.uuid4().hex[:6]}",+ email=f"{uuid.uuid4().hex[:6]}@example.invalid",+ role=role,+ )+ session.add(user)+ await session.flush()+ if tenant_role is not None:+ session.add(+ TenantMember(+ tenant_id=TENANT_ZERO_ID, user_id=user.id, role=tenant_role+ )+ )+ if organization_role is not None:+ session.add(+ OrganizationMember(+ organization_id=TENANT_ZERO_ID,+ user_id=user.id,+ role=organization_role,+ )+ )+ await session.commit()+ return user+++async def _decide(+ session_factory: async_sessionmaker[AsyncSession], user: User+) -> tuple[bool, list[AuditEvent]]:+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:+ decided = await administers_on_record(+ session,+ session_factory,+ UserStore(),+ user,+ target_type="agent",+ target_id="agent-1",+ details={"event": "agent_acting"},+ )+ async with tenant_session(session_factory, TENANT_ZERO_ID) as session:+ events = list(+ await session.scalars(+ select(AuditEvent).where(+ AuditEvent.action == AuditAction.PLATFORM_ACCESS,+ AuditEvent.actor_user_id == user.id,+ )+ )+ )+ return decided, events+++async def test_the_operator_on_the_flag_alone_administers_on_record(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ operator = await _user(session_factory, role="admin", tenant_role="member")++ decided, [event] = await _decide(session_factory, operator)++ assert decided is True+ assert (event.target_type, event.target_id) == ("agent", "agent-1")+ assert event.details == {"event": "agent_acting"}+++async def test_the_operator_through_a_role_is_not_marked(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ operator = await _user(+ session_factory,+ role="admin",+ tenant_role="member",+ organization_role="org_admin",+ )++ assert await _decide(session_factory, operator) == (True, [])+++async def test_anyone_else_is_answered_by_their_role_and_never_recorded(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ admin = await _user(session_factory, role="user", tenant_role="admin")+ member = await _user(session_factory, role="user", tenant_role="member")++ assert await _decide(session_factory, admin) == (True, [])+ assert await _decide(session_factory, member) == (False, [])