fix(gateway): scope reaction observers to routed profiles
This commit is contained in:
+7
-9
@@ -14141,14 +14141,13 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
|
||||
async def _handle_gateway_platform_event(self, event: dict, source) -> None:
|
||||
"""Authorize and publish one normalized adapter event to plugin hooks."""
|
||||
try:
|
||||
from hermes_cli.lifecycle import has_hook, invoke_hook
|
||||
|
||||
if not has_hook("gateway_platform_event"):
|
||||
return
|
||||
if not self._is_user_authorized(source):
|
||||
return
|
||||
from hermes_cli.plugins import get_plugin_manager
|
||||
|
||||
manager = get_plugin_manager()
|
||||
if not manager.has_hook("gateway_platform_event"):
|
||||
return
|
||||
manager.invoke_hook("gateway_platform_event", **event)
|
||||
invoke_hook("gateway_platform_event", **event)
|
||||
except Exception:
|
||||
# Observer failures must never break the adapter's update loop.
|
||||
logger.debug("gateway_platform_event hook dispatch failed", exc_info=True)
|
||||
@@ -14173,11 +14172,10 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
|
||||
return _handler
|
||||
|
||||
def _make_default_profile_platform_event_handler(self):
|
||||
"""Scope default-profile event auth under multiplexing from ingress."""
|
||||
profile_home = Path(get_hermes_home())
|
||||
"""Scope primary-transport events to their routed multiplex profile."""
|
||||
|
||||
async def _handler(event, source):
|
||||
with _profile_runtime_scope(profile_home):
|
||||
with _profile_runtime_scope(self._resolve_profile_home_for_source(source)):
|
||||
return await self._handle_gateway_platform_event(event, source)
|
||||
|
||||
return _handler
|
||||
|
||||
@@ -1069,8 +1069,6 @@ class TelegramAdapter(BasePlatformAdapter):
|
||||
is absent so the post-auth boundary fails closed rather than authorizing
|
||||
an incomplete source. A future event type must wire its own extraction.
|
||||
"""
|
||||
from gateway.session import SessionSource
|
||||
|
||||
mr = getattr(update, "message_reaction", None)
|
||||
if mr is None:
|
||||
raise ValueError(
|
||||
@@ -1103,13 +1101,13 @@ class TelegramAdapter(BasePlatformAdapter):
|
||||
# only forum signal available without the underlying message.
|
||||
chat_type = "forum" if getattr(chat, "is_forum", False) is True else "group"
|
||||
|
||||
return SessionSource(
|
||||
platform=Platform.TELEGRAM,
|
||||
return self.build_source(
|
||||
chat_id=chat_id,
|
||||
chat_type=chat_type,
|
||||
user_id=user_id,
|
||||
user_name=user_name,
|
||||
thread_id=None,
|
||||
message_id=str(message_id),
|
||||
)
|
||||
|
||||
def _telegram_auth_env_configured(self) -> bool:
|
||||
@@ -3746,7 +3744,16 @@ class TelegramAdapter(BasePlatformAdapter):
|
||||
alongside, never displaces, the core handlers. Malformed updates and
|
||||
dispatch errors cannot raise into PTB's update loop.
|
||||
"""
|
||||
handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]] = getattr(
|
||||
self, "_platform_event_handler", None
|
||||
)
|
||||
if handler is None:
|
||||
return
|
||||
try:
|
||||
from hermes_cli.lifecycle import has_hook
|
||||
|
||||
if not has_hook("gateway_platform_event"):
|
||||
return
|
||||
event = self._normalize_platform_event(update)
|
||||
except Exception:
|
||||
logger.debug("[%s] gateway_platform_event normalize error", self.name, exc_info=True)
|
||||
@@ -3757,11 +3764,6 @@ class TelegramAdapter(BasePlatformAdapter):
|
||||
# and its internal source to the gateway-owned boundary, where the full
|
||||
# profile-scoped authorization chain runs before plugin dispatch. No
|
||||
# callback means no trusted auth boundary, so fail closed.
|
||||
handler: Optional[Callable[[Dict[str, Any], Any], Awaitable[None]]] = getattr(
|
||||
self, "_platform_event_handler", None
|
||||
)
|
||||
if handler is None:
|
||||
return
|
||||
try:
|
||||
source = self._source_from_reaction_for_auth(update)
|
||||
await handler(event, source)
|
||||
@@ -3786,23 +3788,37 @@ class TelegramAdapter(BasePlatformAdapter):
|
||||
return None
|
||||
chat = getattr(mr, "chat", None)
|
||||
new_reaction = getattr(mr, "new_reaction", None) or []
|
||||
if not isinstance(new_reaction, (list, tuple)):
|
||||
return None
|
||||
chat_id = getattr(chat, "id", None) if chat is not None else None
|
||||
message_id = getattr(mr, "message_id", None)
|
||||
if (
|
||||
isinstance(chat_id, bool)
|
||||
or not isinstance(chat_id, (str, int))
|
||||
or isinstance(message_id, bool)
|
||||
or not isinstance(message_id, (str, int))
|
||||
):
|
||||
return None
|
||||
emojis: List[str] = []
|
||||
custom_emoji_ids: List[str] = []
|
||||
for r in new_reaction:
|
||||
for r in new_reaction[:64]:
|
||||
emoji = getattr(r, "emoji", None)
|
||||
if emoji is not None:
|
||||
emojis.append(emoji)
|
||||
if isinstance(emoji, str) and emoji:
|
||||
emojis.append(emoji[:64])
|
||||
custom_id = getattr(r, "custom_emoji_id", None)
|
||||
if custom_id is not None:
|
||||
custom_emoji_ids.append(str(custom_id))
|
||||
if (
|
||||
not isinstance(custom_id, bool)
|
||||
and isinstance(custom_id, (str, int))
|
||||
):
|
||||
custom_emoji_ids.append(str(custom_id)[:128])
|
||||
return {
|
||||
"platform": "telegram",
|
||||
"event_type": "reaction",
|
||||
"payload": {
|
||||
"emojis": emojis,
|
||||
"custom_emoji_ids": custom_emoji_ids,
|
||||
"chat_id": str(getattr(chat, "id", "")) if chat is not None else None,
|
||||
"message_id": str(getattr(mr, "message_id", "")),
|
||||
"chat_id": str(chat_id)[:128],
|
||||
"message_id": str(message_id)[:128],
|
||||
# Reactions don't carry thread_id; do not guess it or expose an
|
||||
# adapter object as a routing escape hatch.
|
||||
"thread_id": None,
|
||||
|
||||
@@ -19,14 +19,16 @@ Covers the normalized-envelope pattern that replaces raw-SDK handler args:
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from contextlib import nullcontext
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import MagicMock, patch
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from gateway.config import PlatformConfig
|
||||
from gateway.config import Platform, PlatformConfig
|
||||
|
||||
|
||||
_repo = str(Path(__file__).resolve().parents[2])
|
||||
@@ -56,6 +58,7 @@ _ensure_telegram_mock()
|
||||
|
||||
from plugins.platforms.telegram.adapter import TelegramAdapter # noqa: E402
|
||||
from gateway.run import GatewayRunner # noqa: E402
|
||||
from gateway.profile_routing import ProfileRoute # noqa: E402
|
||||
from hermes_cli.plugins import ( # noqa: E402
|
||||
VALID_HOOKS,
|
||||
PluginContext,
|
||||
@@ -73,11 +76,18 @@ def _adapter(extra=None) -> TelegramAdapter:
|
||||
normal reaction fires; pass a restrictive ``extra`` to exercise the gate.
|
||||
"""
|
||||
a = object.__new__(TelegramAdapter)
|
||||
a.platform = SimpleNamespace(value="telegram") # name -> "Telegram"
|
||||
a.platform = Platform.TELEGRAM
|
||||
a.config = SimpleNamespace(extra=extra if extra is not None else {"allow_from": ["*"]})
|
||||
a.gateway_runner = None
|
||||
return a
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _observer_available(monkeypatch):
|
||||
"""Most fire-site tests exercise the subscribed path explicitly."""
|
||||
monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda _name: True)
|
||||
|
||||
|
||||
def _reaction(*, emoji=None, custom_emoji_id=None):
|
||||
"""A PTB ReactionType stand-in.
|
||||
|
||||
@@ -91,7 +101,7 @@ def _reaction(*, emoji=None, custom_emoji_id=None):
|
||||
return r
|
||||
|
||||
|
||||
def _reaction_update(reactions, chat_id=123, message_id=456):
|
||||
def _reaction_update(reactions, chat_id: object = 123, message_id: object = 456):
|
||||
"""A PTB Update stand-in carrying a message_reaction with ``reactions``."""
|
||||
update = MagicMock()
|
||||
update.message_reaction = MagicMock()
|
||||
@@ -138,8 +148,7 @@ class TestRunnerDispatch:
|
||||
def test_authorized_event_routes_normalized_envelope(self):
|
||||
runner = object.__new__(GatewayRunner)
|
||||
runner._is_user_authorized = lambda source: source.user_id == "777"
|
||||
mgr = MagicMock()
|
||||
mgr.has_hook.return_value = True
|
||||
invoke = MagicMock()
|
||||
source = _adapter()._source_from_reaction_for_auth(
|
||||
_auth_reaction_update(user_id=777)
|
||||
)
|
||||
@@ -149,57 +158,56 @@ class TestRunnerDispatch:
|
||||
"payload": {"chat_id": "123", "message_id": "456", "emojis": ["x"]},
|
||||
}
|
||||
|
||||
with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):
|
||||
with patch("hermes_cli.lifecycle.invoke_hook", invoke):
|
||||
asyncio.run(runner._handle_gateway_platform_event(event, source))
|
||||
|
||||
mgr.invoke_hook.assert_called_once_with("gateway_platform_event", **event)
|
||||
invoke.assert_called_once_with("gateway_platform_event", **event)
|
||||
|
||||
def test_unauthorized_event_never_reaches_hooks(self):
|
||||
runner = object.__new__(GatewayRunner)
|
||||
runner._is_user_authorized = lambda source: False
|
||||
mgr = MagicMock()
|
||||
invoke = MagicMock()
|
||||
source = _adapter()._source_from_reaction_for_auth(
|
||||
_auth_reaction_update(user_id=777)
|
||||
)
|
||||
|
||||
with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):
|
||||
with patch("hermes_cli.lifecycle.invoke_hook", invoke):
|
||||
asyncio.run(runner._handle_gateway_platform_event(
|
||||
{"platform": "telegram", "event_type": "reaction", "payload": {}},
|
||||
source,
|
||||
))
|
||||
|
||||
mgr.has_hook.assert_not_called()
|
||||
mgr.invoke_hook.assert_not_called()
|
||||
invoke.assert_not_called()
|
||||
|
||||
def test_skips_dispatch_when_no_subscriber(self):
|
||||
runner = object.__new__(GatewayRunner)
|
||||
runner._is_user_authorized = lambda source: True
|
||||
mgr = MagicMock()
|
||||
mgr.has_hook.return_value = False
|
||||
authorized = MagicMock(return_value=True)
|
||||
runner._is_user_authorized = authorized
|
||||
invoke = MagicMock()
|
||||
source = _adapter()._source_from_reaction_for_auth(
|
||||
_auth_reaction_update(user_id=777)
|
||||
)
|
||||
|
||||
with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):
|
||||
with patch("hermes_cli.lifecycle.has_hook", return_value=False), patch(
|
||||
"hermes_cli.lifecycle.invoke_hook", invoke
|
||||
):
|
||||
asyncio.run(runner._handle_gateway_platform_event(
|
||||
{"platform": "telegram", "event_type": "reaction", "payload": {}},
|
||||
source,
|
||||
))
|
||||
|
||||
mgr.has_hook.assert_called_once_with("gateway_platform_event")
|
||||
mgr.invoke_hook.assert_not_called()
|
||||
authorized.assert_not_called()
|
||||
invoke.assert_not_called()
|
||||
|
||||
def test_plugin_layer_error_is_isolated(self):
|
||||
runner = object.__new__(GatewayRunner)
|
||||
runner._is_user_authorized = lambda source: True
|
||||
mgr = MagicMock()
|
||||
mgr.has_hook.return_value = True
|
||||
mgr.invoke_hook.side_effect = RuntimeError("plugin boom")
|
||||
invoke = MagicMock(side_effect=RuntimeError("plugin boom"))
|
||||
source = _adapter()._source_from_reaction_for_auth(
|
||||
_auth_reaction_update(user_id=777)
|
||||
)
|
||||
|
||||
with patch("hermes_cli.plugins.get_plugin_manager", return_value=mgr):
|
||||
with patch("hermes_cli.lifecycle.invoke_hook", invoke):
|
||||
asyncio.run(runner._handle_gateway_platform_event(
|
||||
{"platform": "telegram", "event_type": "reaction", "payload": {}},
|
||||
source,
|
||||
@@ -252,6 +260,38 @@ class TestNormalizePlatformEvent:
|
||||
assert event["payload"]["emojis"] == ["\U0001F44D", "\U0001F525"]
|
||||
assert event["payload"]["custom_emoji_ids"] == ["555"]
|
||||
|
||||
def test_malformed_values_never_escape_as_live_objects(self):
|
||||
a = _adapter()
|
||||
update = _reaction_update(
|
||||
[_reaction(emoji=object(), custom_emoji_id=object())]
|
||||
)
|
||||
|
||||
event = a._normalize_platform_event(update)
|
||||
|
||||
assert event is not None
|
||||
assert event["payload"]["emojis"] == []
|
||||
assert event["payload"]["custom_emoji_ids"] == []
|
||||
json.dumps(event)
|
||||
|
||||
def test_reaction_count_and_string_lengths_are_bounded(self):
|
||||
a = _adapter()
|
||||
update = _reaction_update(
|
||||
[_reaction(emoji="x" * 100, custom_emoji_id="9" * 200) for _ in range(100)],
|
||||
chat_id="c" * 200,
|
||||
message_id="m" * 200,
|
||||
)
|
||||
|
||||
event = a._normalize_platform_event(update)
|
||||
|
||||
assert event is not None
|
||||
payload = event["payload"]
|
||||
assert len(payload["emojis"]) == 64
|
||||
assert len(payload["custom_emoji_ids"]) == 64
|
||||
assert all(len(value) == 64 for value in payload["emojis"])
|
||||
assert all(len(value) == 128 for value in payload["custom_emoji_ids"])
|
||||
assert len(payload["chat_id"]) == 128
|
||||
assert len(payload["message_id"]) == 128
|
||||
|
||||
def test_non_reaction_update_returns_none(self):
|
||||
"""Unsupported update types return None until a concrete contract exists."""
|
||||
a = _adapter()
|
||||
@@ -266,6 +306,20 @@ class TestNormalizePlatformEvent:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TestOnPlatformUpdate:
|
||||
def test_no_subscriber_skips_normalization_source_and_dispatch(self):
|
||||
a = _adapter()
|
||||
a._normalize_platform_event = MagicMock()
|
||||
a._source_from_reaction_for_auth = MagicMock()
|
||||
handler = AsyncMock()
|
||||
a.set_platform_event_handler(handler)
|
||||
|
||||
with patch("hermes_cli.lifecycle.has_hook", return_value=False):
|
||||
asyncio.run(a._on_platform_update(MagicMock(), context=MagicMock()))
|
||||
|
||||
a._normalize_platform_event.assert_not_called()
|
||||
a._source_from_reaction_for_auth.assert_not_called()
|
||||
handler.assert_not_awaited()
|
||||
|
||||
def test_fires_gateway_platform_event_with_envelope(self):
|
||||
a = _adapter()
|
||||
seen: list = []
|
||||
@@ -377,6 +431,40 @@ class TestOnPlatformUpdateAuthBoundary:
|
||||
|
||||
|
||||
class TestProfileScopedPlatformEventHandler:
|
||||
def test_primary_shared_transport_uses_profile_route_and_transport_provenance(self):
|
||||
runner = object.__new__(GatewayRunner)
|
||||
runner.config = SimpleNamespace( # type: ignore[assignment]
|
||||
multiplex_profiles=True,
|
||||
profile_routes=[
|
||||
ProfileRoute(
|
||||
name="work-chat",
|
||||
platform="telegram",
|
||||
profile="work",
|
||||
chat_id="123",
|
||||
)
|
||||
],
|
||||
)
|
||||
adapter = _adapter()
|
||||
adapter.gateway_runner = runner # type: ignore[assignment]
|
||||
|
||||
source = adapter._source_from_reaction_for_auth(
|
||||
_auth_reaction_update(user_id=777)
|
||||
)
|
||||
|
||||
assert source.profile == "work"
|
||||
assert getattr(source, "_transport_adapter_ref")() is adapter
|
||||
|
||||
resolver = MagicMock(return_value=Path("/profiles/work"))
|
||||
runner._resolve_profile_home_for_source = resolver
|
||||
dispatch = AsyncMock()
|
||||
runner._handle_gateway_platform_event = dispatch
|
||||
handler = runner._make_default_profile_platform_event_handler()
|
||||
with patch("gateway.run._profile_runtime_scope", side_effect=lambda _home: nullcontext()):
|
||||
asyncio.run(handler({"event_type": "reaction"}, source))
|
||||
|
||||
resolver.assert_called_once_with(source)
|
||||
dispatch.assert_awaited_once_with({"event_type": "reaction"}, source)
|
||||
|
||||
def test_secondary_handler_stamps_profile_before_dispatch(self, monkeypatch):
|
||||
runner = object.__new__(GatewayRunner)
|
||||
captured = {}
|
||||
|
||||
Reference in New Issue
Block a user