Skip to content

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

Close open change sockets and chat streams once a person's sessions end

Petr Bauch21cf485b1205
diff --git a/core/switch_core/gateway/auth.py b/core/switch_core/gateway/auth.py
index 7cde0055a..efe65022d 100644
--- a/core/switch_core/gateway/auth.py
+++ b/core/switch_core/gateway/auth.py
@@ -319,6 +319,20 @@ async def _require_current_session(
_refuse_ended_session(version, payload)
+async def session_is_current(
+ session_factory: async_sessionmaker[AsyncSession],
+ user_store: UserStore,
+ user_id: str,
+ session_version: int,
+) -> bool:
+ """Whether a session minted with `session_version` still stands: the
+ account exists and its sessions have not been ended since. Asked again
+ by a socket or stream that stays open long after it was authenticated."""
+ async with session_factory() as system_session:
+ current = await user_store.session_version(system_session, user_id)
+ return current == session_version
+
+
async def _require_user_exists(
session_factory: async_sessionmaker[AsyncSession],
user_store: UserStore,
@@ -1137,6 +1151,9 @@ class SocketCaller:
# time: the socket is closed then, and the client opens it again with the
# cookie it has renewed meanwhile.
expires_at: float
+ # The `users.session_version` the cookie was minted with, checked again
+ # while the socket is open (`session_is_current`).
+ session_version: int
async def authenticate_socket(
@@ -1163,7 +1180,10 @@ async def authenticate_socket(
config.gateway_tenant_choice_enabled,
)
return SocketCaller(
- user_id=user_id, tenant_id=tenant_id, expires_at=float(payload["exp"])
+ user_id=user_id,
+ tenant_id=tenant_id,
+ expires_at=float(payload["exp"]),
+ session_version=_session_version(payload),
)
diff --git a/core/switch_core/gateway/changes.py b/core/switch_core/gateway/changes.py
index 192e020c8..bdae9b460 100644
--- a/core/switch_core/gateway/changes.py
+++ b/core/switch_core/gateway/changes.py
@@ -22,7 +22,9 @@ socket that would not open, and its next read of a list (which still polls
every few minutes) gets the same 401 and asks the user to sign in again. The
socket holds no database connection while it is open. It is closed with 4401
when the cookie it was opened with expires, so a client reconnects with the
-cookie it has renewed since.
+cookie it has renewed since, and, at the next ping, once the account's
+sessions are ended (signing out of all devices, a password change), so the
+reconnect is refused.
A user holds at most `MAX_SOCKETS_PER_USER` of these at once. Console opens
one per server, so the cap only meets a client opening sockets in a loop, which
@@ -39,6 +41,7 @@ from __future__ import annotations
import asyncio
import logging
import time
+from collections.abc import Awaitable, Callable
from typing import Annotated
from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect
@@ -46,7 +49,11 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from switch_core.config import SwitchConfig
from switch_core.db.stores.user_store import UserStore
-from switch_core.gateway.auth import SocketCaller, authenticate_socket
+from switch_core.gateway.auth import (
+ SocketCaller,
+ authenticate_socket,
+ session_is_current,
+)
from switch_core.gateway.dependencies import (
get_config,
get_session_factory,
@@ -63,7 +70,8 @@ PROTOCOL = 1
PING_INTERVAL_SECONDS = 25.0
# Intervals without a word from the client before its socket is closed.
_SILENT_PINGS = 3
-# The close code for a session cookie that has expired: 4000 plus 401.
+# The close code for a session cookie that has expired or whose sessions were
+# ended: 4000 plus 401.
_EXPIRED = 4401
# Sockets one user may hold on this process: one per Console is the norm, so this
# leaves room for several machines and windows and stops a runaway client.
@@ -92,7 +100,16 @@ async def changes_socket(
websocket: WebSocket,
caller: Annotated[SocketCaller, Depends(get_socket_caller)],
changes: Annotated[LocalUserChanges, Depends(get_user_changes)],
+ session_factory: Annotated[
+ async_sessionmaker[AsyncSession], Depends(get_session_factory)
+ ],
+ user_store: Annotated[UserStore, Depends(get_user_store)],
) -> None:
+ async def still_current() -> bool:
+ return await session_is_current(
+ session_factory, user_store, caller.user_id, caller.session_version
+ )
+
await websocket.accept()
# No await between the count and the subscribe, so two sockets opening at
# once cannot both slip under the cap.
@@ -118,7 +135,14 @@ async def changes_socket(
},
}
)
- code = await _serve(websocket, subscription, heard, listener, caller.expires_at)
+ code = await _serve(
+ websocket,
+ subscription,
+ heard,
+ listener,
+ caller.expires_at,
+ still_current,
+ )
except (WebSocketDisconnect, RuntimeError):
# Gone, or closed under us by the server shutting down: nothing to send.
return
@@ -144,9 +168,11 @@ async def _serve(
heard: asyncio.Event,
listener: asyncio.Task[None],
expires_at: float,
+ still_current: Callable[[], Awaitable[bool]],
) -> int:
"""Send notices as they come and a ping every interval, until the client
- goes quiet, goes away or its cookie expires. Returns the close code.
+ goes quiet, goes away, its cookie expires or, asked at each ping, its
+ session no longer `still_current`. Returns the close code.
One writer: a WebSocket must not be sent to from two tasks at once, so
notices and pings both go out from this loop."""
@@ -181,6 +207,8 @@ async def _serve(
heard.clear()
if silent >= _SILENT_PINGS:
return 1001
+ if not await still_current():
+ return _EXPIRED
await websocket.send_json({"event": "ping", "data": {}})
next_ping = loop.time() + PING_INTERVAL_SECONDS
return 1000
diff --git a/core/switch_core/gateway/chats.py b/core/switch_core/gateway/chats.py
index 496060a58..22cdc23b9 100644
--- a/core/switch_core/gateway/chats.py
+++ b/core/switch_core/gateway/chats.py
@@ -16,7 +16,7 @@ import contextlib
import json
import logging
import time
-from collections.abc import AsyncIterator
+from collections.abc import AsyncIterator, Awaitable, Callable
from datetime import datetime
from typing import Annotated, Any, Literal
@@ -57,8 +57,10 @@ from switch_core.db.models import (
require_tenant_id,
)
from switch_core.db.session_scope import tenant_session
+from switch_core.db.stores.user_store import UserStore
from switch_core.gateway.agent_sessions import ApprovalRequestView
-from switch_core.gateway.auth import get_current_user
+from switch_core.gateway.auth import get_current_user, session_is_current
+from switch_core.gateway.dependencies import get_user_store
from switch_core.session_activity.listener import Change, RoomSubscription
logger = logging.getLogger(__name__)
@@ -341,10 +343,26 @@ async def create_chat(
)
+def _session_check(
+ service: ChatService, user_store: UserStore, user: User
+) -> Callable[[], Awaitable[bool]]:
+ """What a stream asks at each re-read: whether the session it was opened
+ with still stands, or the account's sessions have been ended since."""
+ session_version = user.session_version
+
+ async def still_current() -> bool:
+ return await session_is_current(
+ service.session_factory, user_store, user.id, session_version
+ )
+
+ return still_current
+
+
@router.get("/events")
async def chat_events_stream(
user: CurrentUser,
service: Service,
+ user_store: Annotated[UserStore, Depends(get_user_store)],
after: Annotated[str | None, Query()] = None,
) -> StreamingResponse:
tenant_id = require_tenant_id()
@@ -356,6 +374,7 @@ async def chat_events_stream(
parse_after(after),
ping_seconds=PING_SECONDS,
recheck_seconds=RECHECK_SECONDS,
+ session_current=_session_check(service, user_store, user),
),
media_type="text/event-stream",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
@@ -383,7 +402,9 @@ async def agent_candidates(
@router.get("/activity/events")
async def chat_activity_stream(
- user: CurrentUser, service: Service
+ user: CurrentUser,
+ service: Service,
+ user_store: Annotated[UserStore, Depends(get_user_store)],
) -> StreamingResponse:
tenant_id = require_tenant_id()
return StreamingResponse(
@@ -394,6 +415,7 @@ async def chat_activity_stream(
ping_seconds=PING_SECONDS,
recheck_seconds=RECHECK_SECONDS,
queue_max=ACTIVITY_QUEUE_MAX,
+ session_current=_session_check(service, user_store, user),
),
media_type="text/event-stream",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"},
@@ -874,6 +896,7 @@ async def chat_events(
*,
ping_seconds: float,
recheck_seconds: float,
+ session_current: Callable[[], Awaitable[bool]],
) -> AsyncIterator[bytes]:
"""The caller's chat events as SSE frames.
@@ -882,7 +905,8 @@ async def chat_events(
`chat` and followed from its head; one that leaves the list is `chat.removed`.
A change to the caller's chats wakes the stream at once, whichever process
made it (`chats/signals.py`). A re-read every `recheck_seconds` recovers
- anything a missed notification or a missed signal left behind.
+ anything a missed notification or a missed signal left behind, and ends
+ the stream once the caller's session no longer `session_current`.
"""
stream = _ChatStream(service, tenant_id, user, after)
service.watch_memberships(tenant_id, user.id, stream.on_memberships)
@@ -908,6 +932,8 @@ async def chat_events(
yield b": ping\n\n"
read: set[str] | None
if now >= next_recheck:
+ if not await session_current():
+ return
next_recheck = now + recheck_seconds
read = None
elif stream.wake.is_set():
@@ -934,6 +960,7 @@ async def chat_activity_events(
ping_seconds: float,
recheck_seconds: float,
queue_max: int,
+ session_current: Callable[[], Awaitable[bool]],
) -> AsyncIterator[bytes]:
"""Turn steps and approval requests of the rooms the caller may read, as SSE.
@@ -943,7 +970,8 @@ async def chat_activity_events(
`recheck_seconds`. Readability is still checked on every change, so
leaving a room stops its frames at once. `resync` means changes may have
been missed (the listener reconnected, this connection fell behind, or the
- caller joined a room): reload snapshots.
+ caller joined a room): reload snapshots. Each re-read first ends the
+ stream if the caller's session no longer `session_current`.
"""
queue: asyncio.Queue[object] = asyncio.Queue(maxsize=queue_max)
@@ -995,6 +1023,8 @@ async def chat_activity_events(
yield b": ping\n\n"
recheck = now >= next_recheck
if recheck:
+ if not await session_current():
+ return
next_recheck = now + recheck_seconds
if recheck or item is _RESYNC or item is _MEMBERSHIPS:
current = await _readable_room_ids(service, tenant_id, user)
diff --git a/core/tests/switch_core/gateway/test_changes_socket.py b/core/tests/switch_core/gateway/test_changes_socket.py
index 337d0efba..fbec4931f 100644
--- a/core/tests/switch_core/gateway/test_changes_socket.py
+++ b/core/tests/switch_core/gateway/test_changes_socket.py
@@ -46,14 +46,24 @@ def feed() -> LocalUserChanges:
def _signed_in(
- monkeypatch: pytest.MonkeyPatch, user_id: str = "ada", expires_in: float = 3600
+ monkeypatch: pytest.MonkeyPatch,
+ user_id: str = "ada",
+ expires_in: float = 3600,
+ sessions_ended: bool = False,
) -> None:
async def _authenticate(*_: Any) -> SocketCaller:
return SocketCaller(
- user_id=user_id, tenant_id="t1", expires_at=time.time() + expires_in
+ user_id=user_id,
+ tenant_id="t1",
+ expires_at=time.time() + expires_in,
+ session_version=0,
)
+ async def _current(*_: Any) -> bool:
+ return not sessions_ended
+
monkeypatch.setattr(changes, "authenticate_socket", _authenticate)
+ monkeypatch.setattr(changes, "session_is_current", _current)
@pytest.fixture
@@ -155,6 +165,18 @@ def test_closes_with_4401_when_the_session_cookie_expires(
assert closed.value.code == 4401
+def test_closes_with_4401_at_the_next_ping_once_the_sessions_are_ended(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(changes, "PING_INTERVAL_SECONDS", 0.02)
+ _signed_in(monkeypatch, sessions_ended=True)
+ with client.websocket_connect("/changes/ws") as ws:
+ ws.receive_json()
+ with pytest.raises(WebSocketDisconnect) as closed:
+ ws.receive_json()
+ assert closed.value.code == 4401
+
+
def test_closing_the_socket_drops_its_subscription(
client: TestClient, feed: LocalUserChanges, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/core/tests/switch_core/gateway/test_chats_routes.py b/core/tests/switch_core/gateway/test_chats_routes.py
index e1385bb4b..091f31847 100644
--- a/core/tests/switch_core/gateway/test_chats_routes.py
+++ b/core/tests/switch_core/gateway/test_chats_routes.py
@@ -14,7 +14,7 @@ from __future__ import annotations
import asyncio
import json
import uuid
-from collections.abc import AsyncIterator, Callable
+from collections.abc import AsyncIterator, Awaitable, Callable
from datetime import UTC, datetime, timedelta
from typing import Any
@@ -42,7 +42,9 @@ from switch_core.db.models import (
from switch_core.db.stores.agent_store import AgentStore
from switch_core.db.stores.message_store import MessageStore
from switch_core.db.stores.room_store import RoomStore
+from switch_core.db.stores.user_store import UserStore
from switch_core.gateway import chats as chats_module
+from switch_core.gateway.auth import session_is_current
from switch_core.gateway.chats import (
chat_activity_events,
chat_events,
@@ -852,6 +854,73 @@ class _Events:
return data
+async def _always_current() -> bool:
+ return True
+
+
+def _session_of(chats: _Harness, user: User) -> Callable[[], Awaitable[bool]]:
+ """The check a route hands its stream: the session the stream was opened
+ with, against the account as it is now."""
+ session_version = user.session_version
+
+ async def current() -> bool:
+ return await session_is_current(
+ chats.factory, UserStore(), user.id, session_version
+ )
+
+ return current
+
+
+async def _end_sessions(chats: _Harness, user: User) -> None:
+ async with chats.factory() as session:
+ await UserStore().end_sessions(session, user.id)
+ await session.commit()
+
+
+async def test_the_stream_ends_at_its_next_re_read_once_the_sessions_are_ended(
+ chats: _Harness,
+) -> None:
+ events = _Events(
+ chat_events(
+ chats.service,
+ TENANT,
+ chats.alice,
+ {},
+ ping_seconds=60.0,
+ recheck_seconds=0.05,
+ session_current=_session_of(chats, chats.alice),
+ )
+ )
+ assert (await events.next())[0] == "ready"
+
+ await _end_sessions(chats, chats.alice)
+
+ with pytest.raises(StopAsyncIteration):
+ await events.next()
+
+
+async def test_the_activity_stream_ends_once_the_sessions_are_ended(
+ chats: _Harness,
+) -> None:
+ events = _Events(
+ chat_activity_events(
+ chats.service,
+ TENANT,
+ chats.alice,
+ ping_seconds=60.0,
+ recheck_seconds=0.05,
+ queue_max=64,
+ session_current=_session_of(chats, chats.alice),
+ )
+ )
+ assert (await events.next())[0] == "ready"
+
+ await _end_sessions(chats, chats.alice)
+
+ with pytest.raises(StopAsyncIteration):
+ await events.next()
+
+
def _stream(
chats: _Harness, user: User, after: dict[str, int], recheck: float
) -> _Events:
@@ -863,6 +932,7 @@ def _stream(
after,
ping_seconds=60.0,
recheck_seconds=recheck,
+ session_current=_always_current,
)
)
@@ -1191,6 +1261,7 @@ def _stream_on(process: _Process, user: User) -> _Events:
{},
ping_seconds=60.0,
recheck_seconds=3600.0,
+ session_current=_always_current,
)
)
@@ -1754,6 +1825,7 @@ def _activity_stream(
ping_seconds=ping_seconds,
recheck_seconds=recheck_seconds,
queue_max=queue_max,
+ session_current=_always_current,
)
)
@@ -2132,6 +2204,7 @@ def _activity_stream_on(process: _Process, user: User) -> _Events:
ping_seconds=60.0,
recheck_seconds=3600.0,
queue_max=64,
+ session_current=_always_current,
)
)