Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(rooms): validate reference types when provisioning from YAML

raullopez-sandbox37262e294074
diff --git a/core/switch_core/rooms_yaml.py b/core/switch_core/rooms_yaml.py
index 09fc0a76d..c3c28defe 100644
--- a/core/switch_core/rooms_yaml.py
+++ b/core/switch_core/rooms_yaml.py
@@ -80,9 +80,10 @@ class InlineExternalReference(BaseModel):
@model_validator(mode="after")
def _validate_value(self) -> InlineExternalReference:
- # Validate the value bag against the type's schema now, so a bad inline
- # reference fails at parse time rather than mid-provision.
- self.value = validate_reference_value(self.type, self.value)
+ # Only the value bag's shape can be checked here: parse() is
+ # synchronous and holds neither a session nor a principal, so whether
+ # the type exists and is readable is settled in _resolve_references.
+ self.value = validate_reference_value(self.value)
return self
@@ -250,7 +251,8 @@ class RoomYamlService:
self, entries: list[ExternalReferenceEntry], *, user_id: str, is_admin: bool
) -> tuple[list[str], list[InlineExternalReference]]:
"""Resolve attach-existing references up front (fail loud on missing /
- ambiguous / no-access). Returns (attach-existing ids, inline entries)."""
+ ambiguous / no-access) and check every inline entry's type resolves for
+ this principal. Returns (attach-existing ids, inline entries)."""
attached_ids: list[str] = []
inline: list[InlineExternalReference] = []
async with self._session_factory() as session:
@@ -278,6 +280,12 @@ class RoomYamlService:
)
attached_ids.append(matches[0])
else:
+ # Raises if the type does not exist or the user cannot
+ # read it — here, before create_room, so provisioning
+ # aborts with nothing created.
+ await self._resources.resolve_type_for_principal(
+ session, entry.type, user_id=user_id, is_admin=is_admin
+ )
inline.append(entry)
return attached_ids, inline
diff --git a/core/tests/switch_core/test_rooms_yaml.py b/core/tests/switch_core/test_rooms_yaml.py
index eb1a15215..591840031 100644
--- a/core/tests/switch_core/test_rooms_yaml.py
+++ b/core/tests/switch_core/test_rooms_yaml.py
@@ -14,7 +14,7 @@ import uuid
import pytest
import pytest_asyncio
-from sqlalchemy import insert
+from sqlalchemy import insert, select
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.bridges.resource.service import ResourceService
@@ -25,6 +25,8 @@ from switch_core.db.models import (
ClientRoom,
CollaborationBridge,
ExternalUser,
+ Reference,
+ ReferenceType,
Room,
RoomRole,
User,
@@ -224,8 +226,8 @@ def test_parse_inline_ref_missing_value_fails(env):
def test_parse_inline_ref_bad_value_schema_fails(env):
- # github value requires a non-empty urls list.
- with pytest.raises(ValueError, match="Invalid value for type"):
+ # Every reference value requires a non-empty urls list.
+ with pytest.raises(ValueError, match="Invalid reference value"):
_svc(env).parse(
"""
room:
@@ -321,6 +323,84 @@ async def test_provision_unknown_agent_fails_loud(env):
await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+async def test_provision_unknown_reference_type_fails_before_the_room_exists(env):
+ """An inline reference naming an unresolvable type aborts provisioning.
+
+ parse() cannot catch this — it is synchronous and holds neither a session
+ nor a principal — so the check lives in ``_resolve_references``, which runs
+ before ``create_room``. Nothing may be created.
+ """
+ spec = _svc(env).parse(
+ """
+ room:
+ name: "Bad type"
+ description: "d"
+ references:
+ - type: never_registered
+ name: "R"
+ description: "d"
+ instructions: "i"
+ value: { urls: ["https://example.com/thing"] }
+ """
+ )
+ with pytest.raises(ValueError, match="Unknown reference type 'never_registered'"):
+ await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+
+ async with env["session_factory"]() as session:
+ rooms = (
+ (await session.execute(select(Room).where(Room.name == "Bad type")))
+ .scalars()
+ .all()
+ )
+ refs = (
+ (
+ await session.execute(
+ select(Reference).where(Reference.type == "never_registered")
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert rooms == []
+ assert refs == []
+
+
+async def test_provision_inline_ref_of_a_user_defined_type(env):
+ """A type the principal can read provisions like a built-in."""
+ async with env["session_factory"]() as session:
+ session.add(
+ ReferenceType(
+ type="notion",
+ owner_id=env["user_id"],
+ read_visibility="private",
+ write_visibility="private",
+ display_name="Notion",
+ instructions="Read the linked Notion pages.",
+ value_hint="Paste links to Notion pages.",
+ )
+ )
+ await session.commit()
+
+ spec = _svc(env).parse(
+ """
+ room:
+ name: "Custom type"
+ description: "d"
+ references:
+ - type: notion
+ name: "Spec page"
+ description: "d"
+ instructions: "i"
+ value: { urls: ["https://example.com/notion/spec"] }
+ """
+ )
+ result = await _svc(env).provision(spec, user_id=env["user_id"], is_admin=False)
+ assert len(result.created_reference_ids) == 1
+ assert result.failed_attachments == []
+
+
@pytest.mark.asyncio
async def test_provision_attach_reference_by_name(env):
# Seed an existing reference owned by the user.