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
Restrict visibility changes on references, types and packages (#1004)
Abel Dantas4f1e30399ab5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 132c0f328..ddfa548ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -275,6 +275,12 @@ version of their own to them without also giving them a release of their own.compares it only when someone signs in.#### Changed+- **Only the owner or a workspace admin can change a reference's, reference+ type's, package's or library document's visibility.** This tightens+ permissions: before, anyone with write access could, so on a publicly+ writable resource any member could make it private and lock everyone else+ out of it and the rooms that use it.+ Editing its other fields still needs only write access, as it does for rooms.- **Unlinking a resource from a room is for those taking part in it.** Ittook write access to the room, which on a publicly writable room, thedefault, is everyone's. It is now for the room's owner, people in it (indiff --git a/core/switch_core/authz.py b/core/switch_core/authz.pyindex 299500195..749de97de 100644--- a/core/switch_core/authz.py+++ b/core/switch_core/authz.py@@ -182,6 +182,34 @@ def require_manage(principal: Principal, owner_id: str | None) -> None:raise PermissionError("Not authorized to manage this resource")+def require_visibility_change(+ principal: Principal,+ resource: Authorizable,+ read_visibility: str | None,+ write_visibility: str | None,+ label: str,+) -> None:+ """Raise ``PermissionError`` if this changes who may see or edit+ `resource` and `principal` is neither its owner nor an admin.++ Write access is not enough, the same as for a room: with write visibility+ public, anyone could otherwise make the resource private and lock everyone+ else out of it, and out of the rooms that use it. A value equal to the+ current one changes nothing, so an edit that sends it back unchanged+ needs only write access.+ """+ changes = (+ read_visibility is not None and read_visibility != resource.read_visibility+ ) or (+ write_visibility is not None and write_visibility != resource.write_visibility+ )+ if changes and not can_manage(principal, resource.owner_id):+ raise PermissionError(+ f"Only the {label}'s owner or a workspace admin can change who may "+ "see or edit it."+ )++def can_unlink_from_room(principal: Principal, *, takes_part: bool) -> bool:"""Whether `principal` may unlink a reference, document or package from aroom: those taking part in it and tenant admins. `takes_part` is the roomdiff --git a/core/switch_core/bridges/resource/service.py b/core/switch_core/bridges/resource/service.pyindex ce60acbd3..aeb235ad0 100644--- a/core/switch_core/bridges/resource/service.py+++ b/core/switch_core/bridges/resource/service.py@@ -13,6 +13,7 @@ from switch_core.authz import (can,can_manage,require,+ require_visibility_change,validate_visibility_pair,)from switch_core.bridges.resource.events import ResourceLoadEntry@@ -361,10 +362,17 @@ class ResourceService:read_visibility: str | None = None,write_visibility: str | None = None,) -> ReferenceType:- reference_type = await self._reference_types.get(session, type_)+ reference_type = await self._reference_types.get_for_update(session, type_)if reference_type is None:raise ValueError(f"Reference type not found: {type_}")require(Principal(user_id, is_admin), "write", reference_type)+ require_visibility_change(+ Principal(user_id, is_admin),+ reference_type,+ read_visibility,+ write_visibility,+ "reference type",+ )validate_visibility_pair(read_visibilityif read_visibility is not None@@ -617,10 +625,17 @@ class ResourceService:write_visibility: str | None = None,value: dict[str, Any] | None = None,) -> Reference:- ref = await self._references.get(session, reference_id)+ ref = await self._references.get_for_update(session, reference_id)if ref is None:raise ValueError(f"Reference not found: {reference_id}")require(Principal(user_id, is_admin), "write", ref)+ require_visibility_change(+ Principal(user_id, is_admin),+ ref,+ read_visibility,+ write_visibility,+ "reference",+ )# Validate the *resulting* visibility pair (partial updates must not# leave a writable-but-unreadable resource).validate_visibility_pair(@@ -916,10 +931,17 @@ class ResourceService:write_visibility: str | None = None,content: str | None = None,) -> Document:- doc = await self._documents.get(session, document_id)+ doc = await self._documents.get_for_update(session, document_id)if doc is None:raise ValueError(f"Document not found: {document_id}")require(Principal(user_id, is_admin), "write", doc)+ require_visibility_change(+ Principal(user_id, is_admin),+ doc,+ read_visibility,+ write_visibility,+ "document",+ )validate_visibility_pair(read_visibility if read_visibility is not None else doc.read_visibility,write_visibility if write_visibility is not None else doc.write_visibility,@@ -1294,10 +1316,17 @@ class ResourceService:read_visibility: str | None = None,write_visibility: str | None = None,) -> Package:- pkg = await self._packages.get(session, package_id)+ pkg = await self._packages.get_for_update(session, package_id)if pkg is None:raise ValueError(f"Package not found: {package_id}")require(Principal(user_id, is_admin), "write", pkg)+ require_visibility_change(+ Principal(user_id, is_admin),+ pkg,+ read_visibility,+ write_visibility,+ "package",+ )validate_visibility_pair(read_visibility if read_visibility is not None else pkg.read_visibility,write_visibility if write_visibility is not None else pkg.write_visibility,diff --git a/core/switch_core/db/stores/document_store.py b/core/switch_core/db/stores/document_store.pyindex 1386a39a9..b0b8a1a37 100644--- a/core/switch_core/db/stores/document_store.py+++ b/core/switch_core/db/stores/document_store.py@@ -14,6 +14,19 @@ class DocumentStore:async def get(self, session: AsyncSession, document_id: str) -> Document | None:return await session.get(Document, document_id)+ async def get_for_update(+ self, session: AsyncSession, document_id: str+ ) -> Document | None:+ """Load the row locked until the transaction ends, for a caller that+ checks it and then writes it.++ ``populate_existing`` refreshes a copy already in the session, so the+ check sees the committed row rather than an earlier read of it.+ """+ return await session.get(+ Document, document_id, with_for_update=True, populate_existing=True+ )+async def get_many(self, session: AsyncSession, document_ids: list[str]) -> list[Document]:diff --git a/core/switch_core/db/stores/package_store.py b/core/switch_core/db/stores/package_store.pyindex 75744e206..67d8fb67a 100644--- a/core/switch_core/db/stores/package_store.py+++ b/core/switch_core/db/stores/package_store.py@@ -22,6 +22,19 @@ class PackageStore:async def get(self, session: AsyncSession, package_id: str) -> Package | None:return await session.get(Package, package_id)+ async def get_for_update(+ self, session: AsyncSession, package_id: str+ ) -> Package | None:+ """Load the row locked until the transaction ends, for a caller that+ checks it and then writes it.++ ``populate_existing`` refreshes a copy already in the session, so the+ check sees the committed row rather than an earlier read of it.+ """+ return await session.get(+ Package, package_id, with_for_update=True, populate_existing=True+ )+async def list_for_user(self, session: AsyncSession, user_id: str) -> list[Package]:result = await session.execute(select(Package).where(diff --git a/core/switch_core/db/stores/reference_store.py b/core/switch_core/db/stores/reference_store.pyindex 222dd281c..60741b39a 100644--- a/core/switch_core/db/stores/reference_store.py+++ b/core/switch_core/db/stores/reference_store.py@@ -26,6 +26,19 @@ class ReferenceStore:async def get(self, session: AsyncSession, reference_id: str) -> Reference | None:return await session.get(Reference, reference_id)+ async def get_for_update(+ self, session: AsyncSession, reference_id: str+ ) -> Reference | None:+ """Load the row locked until the transaction ends, for a caller that+ checks it and then writes it.++ ``populate_existing`` refreshes a copy already in the session, so the+ check sees the committed row rather than an earlier read of it.+ """+ return await session.get(+ Reference, reference_id, with_for_update=True, populate_existing=True+ )+async def list_for_user(self, session: AsyncSession, user_id: str) -> list[Reference]:diff --git a/core/switch_core/db/stores/reference_type_store.py b/core/switch_core/db/stores/reference_type_store.pyindex 8bd4843af..8ddf7d8f5 100644--- a/core/switch_core/db/stores/reference_type_store.py+++ b/core/switch_core/db/stores/reference_type_store.py@@ -53,6 +53,22 @@ class ReferenceTypeStore:async def get(self, session: AsyncSession, type_: str) -> ReferenceType | None:return await session.get(ReferenceType, (require_tenant_id(), type_))+ async def get_for_update(+ self, session: AsyncSession, type_: str+ ) -> ReferenceType | None:+ """Load the row locked until the transaction ends, for a caller that+ checks it and then writes it.++ ``populate_existing`` refreshes a copy already in the session, so the+ check sees the committed row rather than an earlier read of it.+ """+ return await session.get(+ ReferenceType,+ (require_tenant_id(), type_),+ with_for_update=True,+ populate_existing=True,+ )+async def get_many(self, session: AsyncSession, types: list[str]) -> list[ReferenceType]:diff --git a/core/tests/switch_core/bridges/resource/test_visibility_changes.py b/core/tests/switch_core/bridges/resource/test_visibility_changes.pynew file mode 100644index 000000000..6a357e087--- /dev/null+++ b/core/tests/switch_core/bridges/resource/test_visibility_changes.py@@ -0,0 +1,226 @@+"""Changing a reference's, reference type's, package's or library document's+visibility is its owner's or a workspace admin's; editing anything else needs only write access.++Through `ResourceService`, which both the gateway routes and the agent+operations call, against a real database.+"""++from __future__ import annotations++import asyncio++import pytest+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.resource.service import ResourceService+from switch_core.db.models import Document, Package, Reference, ReferenceType+from switch_core.db.stores.document_store import DocumentStore+from switch_core.db.stores.package_store import PackageStore+from switch_core.db.stores.reference_store import ReferenceStore+from switch_core.db.stores.reference_type_store import ReferenceTypeStore+from switch_core.db.stores.room_link_store import RoomLinkStore+from tests.switch_core.bridges.resource.test_reference_types_service import (+ _make_user,+)+++def service(session_factory: async_sessionmaker[AsyncSession]) -> ResourceService:+ return ResourceService(+ reference_store=ReferenceStore(),+ reference_type_store=ReferenceTypeStore(),+ document_store=DocumentStore(),+ package_store=PackageStore(),+ room_link_store=RoomLinkStore(),+ session_factory=session_factory,+ )+++OPEN = {"read_visibility": "public", "write_visibility": "public"}+++async def _open_resources(+ session: AsyncSession, owner_id: str+) -> tuple[str, str, str, str]:+ reference = Reference(+ owner_id=owner_id,+ type="url",+ name="docs",+ description="",+ instructions="",+ value={"url": "https://example.test"},+ **OPEN,+ )+ package = Package(+ owner_id=owner_id, name="kit", description="", instructions="", **OPEN+ )+ reference_type = ReferenceType(+ type="ticket",+ owner_id=owner_id,+ display_name="Ticket",+ instructions="",+ value_hint="",+ **OPEN,+ )+ document = Document(+ owner_id=owner_id,+ room_id=None,+ name="notes",+ description="",+ instructions="",+ content="",+ **OPEN,+ )+ session.add_all([reference, package, reference_type, document])+ await session.flush()+ return reference.id, package.id, reference_type.type, document.id+++async def test_a_writer_edits_the_description_but_not_the_visibility(+ session_factory: async_sessionmaker[AsyncSession], service: ResourceService+) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "owner")+ writer = await _make_user(session, "writer")+ reference_id, package_id, slug, document_id = await _open_resources(+ session, owner.id+ )+ await session.commit()++ await service.update_reference(+ session, reference_id, user_id=writer.id, is_admin=False, description="x"+ )+ await service.update_package(+ session, package_id, user_id=writer.id, is_admin=False, description="x"+ )+ await service.update_reference_type(+ session, slug, user_id=writer.id, is_admin=False, instructions="x"+ )+ await service.update_document(+ session, document_id, user_id=writer.id, is_admin=False, content="x"+ )+ with pytest.raises(PermissionError, match="reference's owner"):+ await service.update_reference(+ session,+ reference_id,+ user_id=writer.id,+ is_admin=False,+ read_visibility="private",+ write_visibility="private",+ )+ with pytest.raises(PermissionError, match="package's owner"):+ await service.update_package(+ session,+ package_id,+ user_id=writer.id,+ is_admin=False,+ write_visibility="private",+ )+ with pytest.raises(PermissionError, match="reference type's owner"):+ await service.update_reference_type(+ session,+ slug,+ user_id=writer.id,+ is_admin=False,+ write_visibility="private",+ )+ with pytest.raises(PermissionError, match="document's owner"):+ await service.update_document(+ session,+ document_id,+ user_id=writer.id,+ is_admin=False,+ read_visibility="private",+ )++[email protected]("as_admin", [False, True])+async def test_the_owner_and_an_admin_change_the_visibility(+ session_factory: async_sessionmaker[AsyncSession],+ service: ResourceService,+ as_admin: bool,+) -> None:+ async with session_factory() as session:+ owner = await _make_user(session, "owner")+ admin = await _make_user(session, "admin")+ reference_id, package_id, slug, document_id = await _open_resources(+ session, owner.id+ )+ await session.commit()+ actor = admin.id if as_admin else owner.id+ private = {"read_visibility": "private", "write_visibility": "private"}++ reference = await service.update_reference(+ session, reference_id, user_id=actor, is_admin=as_admin, **private+ )+ package = await service.update_package(+ session, package_id, user_id=actor, is_admin=as_admin, **private+ )+ reference_type = await service.update_reference_type(+ session, slug, user_id=actor, is_admin=as_admin, **private+ )+ document = await service.update_document(+ session, document_id, user_id=actor, is_admin=as_admin, **private+ )+ for row in (reference, package, reference_type, document):+ assert (row.read_visibility, row.write_visibility) == ("private", "private")+++async def test_a_writer_racing_the_owner_is_checked_against_the_committed_row(+ session_factory: async_sessionmaker[AsyncSession], service: ResourceService+) -> None:+ """The owner makes everything private while a writer, who read it public,+ sends an edit with the visibility it saw. The writer waits for the owner's+ commit and is then refused, rather than passing a check made on the row as+ it was before."""+ async with session_factory() as session:+ owner = await _make_user(session, "owner")+ writer = await _make_user(session, "writer")+ reference_id, package_id, slug, document_id = await _open_resources(+ session, owner.id+ )+ await session.commit()+ private = {"read_visibility": "private", "write_visibility": "private"}+ updates = {+ "reference": (service.update_reference, reference_id, {"description": "x"}),+ "package": (service.update_package, package_id, {"description": "x"}),+ "reference type": (service.update_reference_type, slug, {"instructions": "x"}),+ "document": (service.update_document, document_id, {"instructions": "x"}),+ }++ for label, (update, key, edit) in updates.items():+ async with (+ session_factory() as owner_session,+ session_factory() as writer_session,+ ):+ await update(+ owner_session, key, user_id=owner.id, is_admin=False, **private+ )+ writer_edit = asyncio.create_task(+ update(+ writer_session,+ key,+ user_id=writer.id,+ is_admin=False,+ **OPEN,+ **edit,+ )+ )+ await asyncio.sleep(0.2)+ assert not writer_edit.done(), f"the {label} was not locked"+ await owner_session.commit()+ with pytest.raises(PermissionError):+ await writer_edit+ await writer_session.rollback()++ async with session_factory() as session:+ rows = [+ await ReferenceStore().get(session, reference_id),+ await PackageStore().get(session, package_id),+ await ReferenceTypeStore().get(session, slug),+ await DocumentStore().get(session, document_id),+ ]+ for row in rows:+ assert row is not None+ assert (row.read_visibility, row.write_visibility) == ("private", "private")+ assert "x" not in (getattr(row, "description", ""), row.instructions)diff --git a/core/tests/switch_core/test_authz.py b/core/tests/switch_core/test_authz.pyindex 80e782a05..092720a68 100644--- a/core/tests/switch_core/test_authz.py+++ b/core/tests/switch_core/test_authz.py@@ -14,6 +14,7 @@ from switch_core.authz import (owns_tenant,require,require_manage,+ require_visibility_change,validate_visibility_pair,)@@ -245,3 +246,28 @@ class TestValidateVisibilityPair:def test_rejects_invalid_enum(self, read: str, write: str) -> None:with pytest.raises(ValueError, match="expected public|private"):validate_visibility_pair(read, write)+++class TestRequireVisibilityChange:+ """Changing who may see or edit a resource is its owner's or an admin's,+ like a room's; write access alone does not reach it."""++ def _open(self) -> SimpleNamespace:+ return _resource(+ owner_id="u-owner", read_visibility="public", write_visibility="public"+ )++ def test_a_writer_may_not_change_visibility(self) -> None:+ with pytest.raises(PermissionError, match="owner or a workspace admin"):+ require_visibility_change(ALICE, self._open(), "private", None, "reference")+ with pytest.raises(PermissionError):+ require_visibility_change(ALICE, self._open(), None, "private", "package")++ def test_a_writer_may_send_the_current_visibility_back(self) -> None:+ require_visibility_change(ALICE, self._open(), "public", "public", "reference")+ require_visibility_change(ALICE, self._open(), None, None, "reference")++ def test_the_owner_and_an_admin_may_change_it(self) -> None:+ owner = Principal("u-owner", False)+ require_visibility_change(owner, self._open(), "private", "private", "package")+ require_visibility_change(ADMIN, self._open(), "private", "private", "package")