The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): route-stamp primary callback auth and carry is_bot through the adapter auth check
Teknium74775df53fd4
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.pyindex 27724da9db7..8a6444da0b6 100644--- a/gateway/platforms/base.py+++ b/gateway/platforms/base.py@@ -3968,6 +3968,9 @@ class BasePlatformAdapter(ABC):user_id: Optional[str],chat_type: Optional[str] = None,chat_id: Optional[str] = None,+ *,+ is_bot: bool = False,+ thread_id: Optional[str] = None,) -> Optional[bool]:"""Return whether ``user_id`` is on the allowlist, if a check is configured.@@ -3976,6 +3979,11 @@ class BasePlatformAdapter(ABC):when no check is registered (caller should treat as "trust unknown"and preserve legacy behaviour).+ ``is_bot`` / ``thread_id`` are forwarded as keywords only when set, so+ the gateway callback can apply its bot policy (``*_ALLOW_BOTS``) and+ thread-level profile routes while legacy three-positional callbacks+ keep working unchanged.+Only the literal booleans are propagated. A callback that returnsanything else is treated as "unknown" rather than coerced with``bool()``: callers that gate a credentialed side effect on an@@ -3984,8 +3992,13 @@ class BasePlatformAdapter(ABC):"""if not user_id or self._authorization_check is None:return None+ extra: Dict[str, Any] = {}+ if is_bot:+ extra["is_bot"] = True+ if thread_id is not None:+ extra["thread_id"] = thread_idtry:- result = self._authorization_check(user_id, chat_type, chat_id)+ result = self._authorization_check(user_id, chat_type, chat_id, **extra)if result is True:return Trueif result is False:diff --git a/gateway/run.py b/gateway/run.pyindex efedf4305c6..b45b1a6fc27 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -17793,11 +17793,30 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew``profile_name`` binds the callback to the secondary adapter's ownmultiplex profile, so its ``SessionSource`` resolves that profile'ssecret scope instead of falling back to the active profile.++ For the shared primary adapter under ``multiplex_profiles``+ (``profile_name`` is None) the callback mirrors the inbound message+ path exactly: the chat's ``profile_routes`` match is stamped on the+ source so the routed profile's pairing store is consulted, while the+ allowlist/gate reads stay under the transport (launch) home via+ ``_is_user_authorized_for_source`` — the same split+ ``_make_default_profile_message_handler`` applies. Without this an+ inline-button caller approved only in the routed profile's pairing+ store was denied (#86296), because the adapter's callback source was+ never route-stamped."""+ multiplex = bool(getattr(self.config, "multiplex_profiles", False))+ transport_home = (+ Path(get_hermes_home()) if multiplex and profile_name is None else None+ )+def check(user_id: str,chat_type: Optional[str] = None,chat_id: Optional[str] = None,+ *,+ is_bot: bool = False,+ thread_id: Optional[str] = None,) -> bool:if not user_id:return False@@ -17806,9 +17825,34 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatewchat_id=chat_id or "",chat_type=chat_type or "group",user_id=user_id,+ thread_id=thread_id,+ is_bot=bool(is_bot),profile=profile_name,)- return self._is_user_authorized(source)+ # Same in-process transport provenance ``build_source`` retains, so+ # adapter-level policy reads (config.yaml group_allowed_chats,+ # allow_from) resolve the receiving adapter even once the routed+ # profile is stamped below.+ registry = (+ (getattr(self, "_profile_adapters", None) or {}).get(profile_name)+ if profile_name+ else getattr(self, "adapters", None)+ ) or {}+ adapter = registry.get(platform)+ if adapter is not None:+ source._transport_adapter_ref = _weakref.ref(adapter)+ if transport_home is None:+ return self._is_user_authorized(source)+ source._authorization_profile_home = transport_home+ from gateway.profile_routing import ProfileRouteRejected++ try:+ source.profile = self._profile_name_for_source(source)+ except ProfileRouteRejected:+ # Same fail-closed outcome as the ingress gate in+ # ``_handle_message`` for a route to an unserved profile.+ return False+ return self._is_user_authorized_for_source(source)return checkdiff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.pyindex 28bf515ec25..15d2541d301 100644--- a/plugins/platforms/telegram/adapter.py+++ b/plugins/platforms/telegram/adapter.py@@ -1233,6 +1233,7 @@ class TelegramAdapter(BasePlatformAdapter):normalized_user_id,chat_type=normalized_chat_type,chat_id=str(chat_id or normalized_user_id),+ thread_id=str(thread_id) if thread_id is not None else None,)if injected is not None:return injected@@ -1285,6 +1286,9 @@ class TelegramAdapter(BasePlatformAdapter):user = getattr(message, "from_user", None)chat = getattr(message, "chat", None)user_id = str(getattr(user, "id", "")).strip() or None+ # Carry the bot flag so the runner's ``*_ALLOW_BOTS`` policy branch is+ # reachable from this prefilter, exactly as it is for ``build_source``.+ is_bot = bool(getattr(user, "is_bot", False)) if user is not None else Falseuser_name = (str(getattr(user, "username", "") or getattr(user, "full_name", "") or "").strip()or None@@ -1330,6 +1334,7 @@ class TelegramAdapter(BasePlatformAdapter):user_id=user_id,user_name=user_name,thread_id=thread_id,+ is_bot=is_bot,)def _source_from_reaction_for_auth(self, update):@@ -1411,14 +1416,20 @@ class TelegramAdapter(BasePlatformAdapter):if source.chat_type != "dm":return False- runner = getattr(getattr(self, "_message_handler", None), "__self__", None)+ # The bound-handler ``__self__`` is None under multiplex (the handler is+ # a profile closure); ``gateway_runner`` is injected on every adapter+ # by ``GatewayRunner._create_adapter`` and survives that wrapping.+ runner = getattr(+ getattr(self, "_message_handler", None), "__self__", None+ ) or getattr(self, "gateway_runner", None)behavior_fn = getattr(runner, "_get_unauthorized_dm_behavior", None)if callable(behavior_fn):try:return (behavior_fn(Platform.TELEGRAM,- profile=getattr(source, "profile", None),+ profile=getattr(source, "profile", None)+ or getattr(self, "_owner_profile", None),)== "pair")@@ -1511,6 +1522,8 @@ class TelegramAdapter(BasePlatformAdapter):user_id,chat_type=source.chat_type,chat_id=source.chat_id,+ is_bot=source.is_bot,+ thread_id=source.thread_id,)if has_callbackelse Nonediff --git a/tests/gateway/test_multiplex_interactive_auth.py b/tests/gateway/test_multiplex_interactive_auth.pynew file mode 100644index 00000000000..798d179b73b--- /dev/null+++ b/tests/gateway/test_multiplex_interactive_auth.py@@ -0,0 +1,110 @@+"""Multiplex interactive-auth regressions (#86296, #92840, #72657, #87240 egress).++Real ``GatewayRunner`` methods on an ``object.__new__`` runner, real+``PairingStore`` files under a temp HERMES_HOME, multiplex active.+"""++from pathlib import Path+from types import SimpleNamespace++import pytest++from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.pairing import PairingStore+from gateway.profile_routing import ProfileRoute+++def mux_home(tmp_path, monkeypatch):+ from agent import secret_scope++ home = tmp_path / "hh"+ (home / "profiles" / "secondary").mkdir(parents=True)+ (home / ".env").write_text("")+ (home / "profiles" / "secondary" / ".env").write_text("")+ monkeypatch.setenv("HERMES_HOME", str(home))+ for key in (+ "TELEGRAM_ALLOWED_USERS",+ "TELEGRAM_ALLOW_BOTS",+ "GATEWAY_ALLOW_ALL_USERS",+ "GATEWAY_ALLOWED_USERS",+ "SLACK_ALLOW_ALL_USERS",+ "SLACK_ALLOWED_USERS",+ ):+ monkeypatch.delenv(key, raising=False)+ prev = secret_scope.is_multiplex_active()+ secret_scope.set_multiplex_active(True)+ yield home+ secret_scope.set_multiplex_active(prev)+++def _runner(home):+ from gateway.run import GatewayRunner++ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(multiplex_profiles=True)+ runner.config.profile_routes = [+ ProfileRoute(name="r", platform="telegram", chat_id="-100555", profile="secondary")+ ]+ runner.config.platforms = {Platform.TELEGRAM: PlatformConfig(enabled=True, extra={})}+ runner.pairing_store = PairingStore(profile="default")+ runner.pairing_stores = {+ "default": runner.pairing_store,+ "secondary": PairingStore(profile="secondary"),+ }+ runner._primary_profile_name = "default"+ runner._profile_adapters = {"secondary": {}}+ return runner+++def _telegram(runner):+ from plugins.platforms.telegram.adapter import TelegramAdapter++ tg = object.__new__(TelegramAdapter)+ tg.config = PlatformConfig(enabled=True, extra={})+ tg._authorization_check = None+ tg._message_handler = runner._primary_message_handler() # closure, no __self__+ runner.adapters = {Platform.TELEGRAM: tg}+ tg.set_authorization_check(runner._make_adapter_auth_check(Platform.TELEGRAM))+ return tg+++def test_routed_primary_callback_uses_routed_pairing_store_and_transport_allowlist(mux_home):+ """#86296: shared primary bot + profile_routes → the inline-button caller+ is authorized by the ROUTED profile's pairing store, while env allowlists+ resolve under the transport (launch) home, exactly like inbound messages."""+ runner = _runner(mux_home)+ store = runner.pairing_stores["secondary"]+ store._save_json(store._approved_path("telegram"), {"777": {}})+ (mux_home / ".env").write_text("TELEGRAM_ALLOWED_USERS=999\n")+ tg = _telegram(runner)++ # Paired only in the routed profile → allowed in the routed chat only.+ assert tg._is_callback_user_authorized("777", chat_id="-100555", chat_type="supergroup") is True+ assert tg._is_callback_user_authorized("777", chat_id="-100999", chat_type="supergroup") is False+ # Transport-home allowlist honored in the routed chat (not the routed profile's empty scope).+ assert tg._is_callback_user_authorized("999", chat_id="-100555", chat_type="supergroup") is True+ assert tg._is_callback_user_authorized("888", chat_id="-100555", chat_type="supergroup") is False+++def test_bot_sender_reaches_allow_bots_policy_through_callback(mux_home):+ """#92840: the early prefilter must carry ``is_bot`` so TELEGRAM_ALLOW_BOTS+ admits bot-authored messages under the multiplex closure handler."""+ from gateway.run import _profile_runtime_scope++ runner = _runner(mux_home)+ (mux_home / ".env").write_text("TELEGRAM_ALLOWED_USERS=999\nTELEGRAM_ALLOW_BOTS=all\n")+ tg = _telegram(runner)++ def msg(uid, is_bot):+ return SimpleNamespace(+ from_user=SimpleNamespace(id=uid, is_bot=is_bot, username="x", full_name="X"),+ chat=SimpleNamespace(id=-100777, type="supergroup", is_forum=False),+ sender_chat=None,+ message_thread_id=None,+ is_topic_message=False,+ )++ with _profile_runtime_scope(mux_home):+ assert tg._is_user_authorized_from_message(msg(4242, True)) is True+ assert tg._is_user_authorized_from_message(msg(4343, False)) is False