Skip to content

The agent that grows with you

fix(plugins): refuse a keyed inject into another profile's messaging session up front

unsupportedpastelsc92611c4c103
diff --git a/gateway/run_plugin_injection.py b/gateway/run_plugin_injection.py
index 47ebf147160..9cad626c581 100644
--- a/gateway/run_plugin_injection.py
+++ b/gateway/run_plugin_injection.py
@@ -128,15 +128,36 @@ class GatewayPluginInjectionMixin:
return authorized
def _plugin_session_key_admissible(self, session_key: str, *, plugin_home: Optional[Path], plugin_id: str) -> bool:
- """Synchronous refusal of a keyed injection into another profile's local session, so the
- plugin gets ``False``; any other key is decided at dispatch, as before. Dispatch rechecks."""
+ """Synchronous refusal of a keyed injection into another profile's session (local or
+ messaging), so the plugin gets ``False``; an unknown key is decided at dispatch, as before.
+ Dispatch rechecks."""
entry = self.session_store.lookup_by_session_key(session_key)
if entry is None or entry.origin is None:
return True
from gateway.session_identity import replace_source
source = replace_source(self._restored_source(entry))
- return source.platform != Platform.LOCAL or self._plugin_local_session(
- source, session_key, plugin_home=plugin_home, plugin_id=plugin_id) is not None
+ if source.platform == Platform.LOCAL:
+ return self._plugin_local_session(source, session_key, plugin_home=plugin_home,
+ plugin_id=plugin_id) is not None
+ return self._plugin_messaging_session_owned(session_key, plugin_home=plugin_home, plugin_id=plugin_id)
+
+ def _plugin_messaging_session_owned(self, session_key: str, *, plugin_home: Optional[Path],
+ plugin_id: str) -> bool:
+ """A messaging session belongs to the profile its key names (``agent:<profile>:...``) under
+ multiplexing, and to the one served profile of a standalone gateway; it must be the plugin's
+ own, as on the origin path. A caller with no plugin home is left to dispatch, as before."""
+ if plugin_home is None:
+ return True
+ profile = self._served_profile_for_home(plugin_home)
+ owner = profile
+ if profile is not None and getattr(getattr(self, "config", None), "multiplex_profiles", False) is True:
+ from hermes_state_keys import profile_from_session_key
+ owner = profile_from_session_key(session_key)
+ if profile is not None and owner == profile:
+ return True
+ logger.warning("Plugin message injection refused: plugin=%s session=%s belongs to profile %s, not the "
+ "plugin's profile %s", plugin_id, session_key, owner, profile)
+ return False
def _plugin_local_session(self, source: SessionSource, session_key: str, *, plugin_home: Optional[Path],
plugin_id: str):
@@ -169,6 +190,8 @@ class GatewayPluginInjectionMixin:
if source.platform == Platform.LOCAL:
return await self._dispatch_plugin_local_injection(source, entry, content=content, plugin_id=plugin_id,
plugin_home=plugin_home)
+ if not self._plugin_messaging_session_owned(session_key, plugin_home=plugin_home, plugin_id=plugin_id):
+ return False
if not self._plugin_injection_authorized(source, plugin_id=plugin_id, target=f"session={session_key}"):
return False
diff --git a/tests/gateway/test_plugin_gateway_session_parity.py b/tests/gateway/test_plugin_gateway_session_parity.py
index 34ce22c2a18..4d124ba1454 100644
--- a/tests/gateway/test_plugin_gateway_session_parity.py
+++ b/tests/gateway/test_plugin_gateway_session_parity.py
@@ -153,6 +153,51 @@ async def test_keyed_local_injection_stays_inside_the_plugins_own_profile(tmp_pa
authority.db.close()
+async def test_keyed_messaging_injection_stays_inside_the_plugins_own_profile(tmp_path, monkeypatch):
+ """A messaging session's key names its profile: beta's plugin naming default's Telegram session
+ gets ``False`` up front (reason in gateway.log) and nothing reaches the adapter, as for a local
+ session; default's own plugin is still accepted and its turn reaches the session's adapter."""
+ from datetime import datetime
+ from unittest.mock import AsyncMock
+ from gateway.config import GatewayConfig, Platform
+ from gateway.run import GatewayRunner
+ from gateway.session import SessionEntry, SessionSource
+
+ launch = tmp_path / ".hermes"
+ beta = launch / "profiles" / "beta"
+ beta.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ runner = GatewayRunner(GatewayConfig(sessions_dir=launch / "sessions"))
+ runner.config.multiplex_profiles = True
+ runner.config._runtime_profile_homes = [("default", launch), ("beta", beta)]
+ key, now = "agent:main:telegram:dm:42", datetime.now() # default's namespace
+ entry = SessionEntry(session_key=key, session_id="session-42", created_at=now, updated_at=now,
+ platform=Platform.TELEGRAM,
+ origin=SessionSource(platform=Platform.TELEGRAM, chat_id="42", chat_type="dm", user_id="42"))
+ monkeypatch.setattr(runner.session_store, "lookup_by_session_key", {key: entry}.get)
+ adapter = SimpleNamespace(handle_message=AsyncMock())
+ monkeypatch.setattr(runner, "_delivery_adapter_for", lambda _source: adapter)
+ monkeypatch.setattr(runner, "_plugin_injection_authorized", lambda *_args, **_kwargs: True)
+ (default_ctx, default_manager), (beta_ctx, beta_manager) = _context(launch), _context(beta)
+ for manager in (default_manager, beta_manager):
+ _publish(runner, manager)
+
+ with caplog_at("gateway.run") as records:
+ assert await asyncio.to_thread(beta_ctx.inject_message, "cross", session_key=key) is False
+ # Dispatch rechecks.
+ assert await runner._dispatch_plugin_message_injection(
+ session_key=key, content="cross", plugin_id="desk", plugin_home=beta) is False
+ refusals = [record.getMessage() for record in records if "refused" in record.getMessage()]
+ assert len(refusals) == 2 and all("not the plugin's profile beta" in message for message in refusals)
+ adapter.handle_message.assert_not_awaited()
+
+ assert await asyncio.to_thread(default_ctx.inject_message, "own", session_key=key) is True
+ await async_wait_until(lambda: adapter.handle_message.await_count, timeout=10,
+ what="the same-profile plugin turn at the session's adapter")
+ assert [call.args[0].text for call in adapter.handle_message.await_args_list] == ["own"]
+
+
class caplog_at:
"""Collect one logger's records without depending on the caplog fixture's propagation."""
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index a1619df85b7..2823318fcdc 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -940,6 +940,7 @@ In gateway mode:
- `session_key` is required and must identify an existing gateway session. It is the stable routing key, not the CLI session ID.
- Exception: a hook or tool running for a classic CLI session (`hermes chat`, whose turns run in the gateway) may omit both `session_key` and `origin`, as it could in the CLI. The text is committed to that session's queue and starts the next turn; it no longer interrupts a running one. `allow_gateway_injection` is still required.
- Hermes reuses that session's stored platform, chat, thread, profile, and conversation history. Plugins cannot change that route through `session_key`.
+- The session must belong to the plugin's own profile: the key of another profile's chat or local session gets `False` right away, with the reason in the gateway log.
- Hermes rechecks the stored route against the gateway's current authorisation rules before dispatch.
- Routes that relied only on an adapter-time or upstream authorisation decision are rejected unless Hermes can revalidate them from current core allowlists, pairing, or explicit allow-all configuration.
- Injected text is always conversational input. It cannot invoke slash commands, approve tools, or resolve pending confirmation and clarification prompts.