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-3834] Answer a refused invite, a refused room lookup and a bad history timestamp with 4xx, not 500 (#1075)
Christian McDermottb99274616482
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b4670ca09..fd821b3d0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -151,6 +151,14 @@ version of their own to them without also giving them a release of their own.Existing duplicates are left as they are and can be reached by id.#### Fixed+- **The agent HTTP API answers a refused or malformed request with a 4xx, not+ a 500.** Inviting an agent to a room the caller may not change answered 500+ instead of 403, and so did looking up a room the agent is not in. A room+ history request whose `since` or `before` is not an ISO 8601 timestamp+ answered 500 instead of 400; it now says which parameter was wrong, and so+ does `read_context` (#1045). One whose offset moves it outside the years 1+ to 9999 in UTC is refused the same way instead of answering 404, and a time+ in the last millisecond of 9999 is no longer refused at all.- **Every way of setting a password now applies the same rules.** Signupalready required 8 characters and at most 72 bytes. Changing your ownpassword checked only the 8 characters, and an admin creating a user checkeddiff --git a/core/switch_core/bridges/agent/api/handlers.py b/core/switch_core/bridges/agent/api/handlers.pyindex 30ef09fe8..0a2b073fb 100644--- a/core/switch_core/bridges/agent/api/handlers.py+++ b/core/switch_core/bridges/agent/api/handlers.py@@ -5,7 +5,7 @@ import hashlibimport loggingfrom collections.abc import AsyncGeneratorfrom contextvars import ContextVar-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Annotated, Any, castfrom fastapi import (@@ -125,12 +125,31 @@ logger = logging.getLogger(__name__)router = APIRouter()+_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)-def parse_timestamp_ms(iso: str) -> int:- dt = datetime.fromisoformat(iso)++def parse_timestamp_ms(name: str, iso: str) -> int:+ """Epoch milliseconds for `iso`, the value of parameter `name`.++ Raises ValueError naming the parameter when `iso` does not parse, or when+ its offset moves it outside the years 1 to 9999 in UTC, where it could not+ be turned back into a datetime to query with.+ """+ try:+ dt = datetime.fromisoformat(iso)+ except ValueError as exc:+ raise ValueError(f"'{name}' is not an ISO 8601 timestamp: {iso!r}") from excif dt.tzinfo is None:dt = dt.replace(tzinfo=UTC)- return int(dt.timestamp() * 1000)+ try:+ dt = dt.astimezone(UTC)+ except OverflowError as exc:+ raise ValueError(+ f"'{name}' is outside the years 1 to 9999 in UTC: {iso!r}"+ ) from exc+ # Integer arithmetic: through a float, a time in the last millisecond of+ # 9999 rounds up into the year 10000.+ return (dt - _EPOCH) // timedelta(milliseconds=1)async def _resolve_registration_user_id(@@ -1666,8 +1685,11 @@ async def get_room_history(] = None,limit: Annotated[int, Query()] = 50,) -> HistoryResponse:- since_ms = parse_timestamp_ms(since) if since else None- before_ms = parse_timestamp_ms(before) if before else None+ try:+ since_ms = parse_timestamp_ms("since", since) if since else None+ before_ms = parse_timestamp_ms("before", before) if before else None+ except ValueError as e:+ raise HTTPException(status_code=400, detail=str(e)) from etry:context = await protocol.read_context(@@ -1923,6 +1945,8 @@ async def invite_agent()except ValueError as e:raise HTTPException(status_code=422, detail=str(e)) from e+ except PermissionError as e:+ raise HTTPException(status_code=403, detail=str(e)) from ereturn {"ok": True}@@ -1955,6 +1979,8 @@ async def get_room(room_detail = await protocol.get_room_detail(agent.id, room_id)except ValueError as e:raise HTTPException(status_code=404, detail=str(e)) from e+ except PermissionError as e:+ raise HTTPException(status_code=403, detail=str(e)) from ereturn RoomDetailResponse(id=room_detail.id,diff --git a/core/switch_core/bridges/agent/operations/definitions.py b/core/switch_core/bridges/agent/operations/definitions.pyindex 26738bf69..a04ceaed1 100644--- a/core/switch_core/bridges/agent/operations/definitions.py+++ b/core/switch_core/bridges/agent/operations/definitions.py@@ -709,8 +709,8 @@ async def read_context(room_id = sole_connected_room(connected)protocol = get_protocol()- since_ms = parse_timestamp_ms(since) if since else None- before_ms = parse_timestamp_ms(before) if before else None+ since_ms = parse_timestamp_ms("since", since) if since else None+ before_ms = parse_timestamp_ms("before", before) if before else Nonebuffer = protocol.event_buffertenant_id = require_tenant_id()diff --git a/core/tests/switch_core/bridges/agent/api/test_refusal_status_codes.py b/core/tests/switch_core/bridges/agent/api/test_refusal_status_codes.pynew file mode 100644index 000000000..0a0c2594c--- /dev/null+++ b/core/tests/switch_core/bridges/agent/api/test_refusal_status_codes.py@@ -0,0 +1,162 @@+"""The agent API answers a refused or malformed request with a 4xx, not a 500.++AgentCore raises PermissionError when an agent is not allowed to act on a room,+and the timestamp parser raises ValueError on a string it cannot read. A route+that lets either escape answers 500, which tells an HTTP agent the server broke+when it was the request that was wrong, so the agent may retry something that+will never succeed.++Reported in https://github.com/sandbox-quantum/switch/issues/1045.+"""++from __future__ import annotations++from dataclasses import dataclass+from types import SimpleNamespace+from urllib.parse import urlencode++from fastapi import FastAPI, HTTPException+from fastapi.exceptions import RequestValidationError+from httpx import ASGITransport, AsyncClient, Response+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker++from switch_core.bridges.agent.api import handlers+from switch_core.bridges.agent.app import log_http_exceptions, log_validation_errors+from switch_core.bridges.agent.protocol.agent_core import AgentCore+from switch_core.db.stores.message_store import MessageStore+from tests.switch_core.bridges.agent.protocol.test_room_roster_authz import (+ _make_public_room,+ _make_user,+ _register,+ _service,+)+++async def _request(+ svc: AgentCore, caller_id: str, method: str, path: str, json: object = None+) -> Response:+ app = FastAPI()+ app.add_exception_handler(HTTPException, log_http_exceptions) # type: ignore[arg-type]+ app.add_exception_handler(RequestValidationError, log_validation_errors) # type: ignore[arg-type]+ app.include_router(handlers.router, prefix="/agents")+ app.dependency_overrides[handlers.get_agent_from_scope] = lambda: SimpleNamespace(+ id=caller_id+ )+ app.dependency_overrides[handlers.get_protocol] = lambda: svc++ transport = ASGITransport(app=app, raise_app_exceptions=False)+ async with AsyncClient(transport=transport, base_url="http://test") as client:+ return await client.request(method, path, json=json)+++@dataclass+class _Room:+ svc: AgentCore+ room_id: str+ member_id: str+ outsider_id: str+++async def _room_with_an_outsider(+ session_factory: async_sessionmaker[AsyncSession],+) -> _Room:+ svc = _service(session_factory)+ svc.message_store = MessageStore() # the roster tests never read history+ owner = await _make_user(session_factory, "owner")+ other = await _make_user(session_factory, "other")+ member_id = await _register(svc, "member-agent", owner)+ outsider_id = await _register(svc, "outsider-agent", other)+ room_id = await _make_public_room(+ session_factory, owner_id=owner, member_agent_ids=[member_id]+ )+ return _Room(svc=svc, room_id=room_id, member_id=member_id, outsider_id=outsider_id)+++async def test_a_refused_invite_is_403(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ r = await _room_with_an_outsider(session_factory)++ resp = await _request(+ r.svc,+ r.outsider_id,+ "POST",+ f"/agents/{r.outsider_id}/moderation/rooms/{r.room_id}/invite",+ json={"agent_name": "outsider-agent"},+ )++ assert resp.status_code == 403+ assert resp.json() == {"detail": "Not authorized to change this room's membership"}+++async def test_a_non_member_looking_up_a_room_is_403(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ r = await _room_with_an_outsider(session_factory)++ resp = await _request(+ r.svc,+ r.outsider_id,+ "GET",+ f"/agents/{r.outsider_id}/moderation/rooms/{r.room_id}",+ )++ assert resp.status_code == 403+ assert resp.json() == {"detail": "Agent is not a member of this room"}+++async def test_a_history_timestamp_that_does_not_parse_is_400_naming_it(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ r = await _room_with_an_outsider(session_factory)+ path = f"/agents/{r.member_id}/rooms/{r.room_id}/history"++ for param in ("since", "before"):+ resp = await _request(+ r.svc, r.member_id, "GET", f"{path}?{urlencode({param: 'yesterday'})}"+ )++ assert resp.status_code == 400+ assert resp.json() == {+ "detail": f"'{param}' is not an ISO 8601 timestamp: 'yesterday'"+ }+++async def test_a_history_timestamp_its_offset_moves_off_the_calendar_is_400(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ """It parses, but in UTC it falls in year 0 or 10000, which no query can use."""+ r = await _room_with_an_outsider(session_factory)+ path = f"/agents/{r.member_id}/rooms/{r.room_id}/history"++ for param, value in (+ ("since", "0001-01-01T00:00:00+01:00"),+ ("before", "9999-12-31T23:59:59-01:00"),+ ):+ resp = await _request(+ r.svc, r.member_id, "GET", f"{path}?{urlencode({param: value})}"+ )++ assert resp.status_code == 400+ assert resp.json() == {+ "detail": f"'{param}' is outside the years 1 to 9999 in UTC: '{value}'"+ }+++async def test_history_reads_between_the_first_and_last_moments_of_the_calendar(+ session_factory: async_sessionmaker[AsyncSession],+) -> None:+ r = await _room_with_an_outsider(session_factory)+ query = urlencode(+ {"since": "0001-01-01T00:00:00Z", "before": "9999-12-31T23:59:59.999999Z"}+ )++ resp = await _request(+ r.svc,+ r.member_id,+ "GET",+ f"/agents/{r.member_id}/rooms/{r.room_id}/history?{query}",+ )++ assert resp.status_code == 200+ assert resp.json() == {"events": [], "has_more": False}diff --git a/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py b/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.pyindex 89d3cbe25..4759e9e5e 100644--- a/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py+++ b/core/tests/switch_core/bridges/agent/operations/test_read_context_room_argument.py@@ -155,6 +155,18 @@ async def test_a_room_you_are_not_a_member_of_is_refused(assert protocol.calls == []+async def test_a_timestamp_that_does_not_parse_is_refused_naming_it(+ protocol: _Protocol, connected: None, caller: None+) -> None:+ with pytest.raises(+ ValueError, match="'before' is not an ISO 8601 timestamp: 'yesterday'"+ ):+ await read_context(before="yesterday")++ assert protocol.calls == []++@pytest.mark.asyncioasync def test_an_unconnected_caller_can_still_read_a_room_it_names(protocol: _Protocol, unbound_caller: None