Skip to content

The agent that grows with you

fix(gateway): validate a secondary's Docker MEDIA paths under its own profile scope

teknium128138f252433
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 5bb855b7225..55298cd5583 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -3250,6 +3250,18 @@ class BasePlatformAdapter(ABC):
if eph_ttl > 0 and result.success and result.message_id:
self._schedule_ephemeral_delete(event.source.chat_id, result.message_id, eph_ttl)
+ def _media_delivery_scope(self, source: Optional[SessionSource]):
+ """The runner's ``_media_delivery_scope_for_source`` (routed profile's home + terminal
+ policy) for validating outbound paths; a no-op without a runner or outside multiplexing."""
+ resolve = getattr(self.gateway_runner, "_media_delivery_scope_for_source", None)
+ if not callable(resolve) or source is None:
+ return contextlib.nullcontext()
+ try:
+ return resolve(source)
+ except Exception:
+ logger.debug("[%s] Failed to resolve media delivery scope", self.name, exc_info=True)
+ return contextlib.nullcontext()
+
def _final_delivery_adapter(self, source: Optional[SessionSource]) -> "BasePlatformAdapter":
"""The runner's CURRENT adapter for a new final-response send: a reconnect can swap the
registry adapter mid-task; an unsent final response belongs on the replacement transport,
@@ -4012,30 +4024,32 @@ class BasePlatformAdapter(ABC):
# Captured before extract_media strips it: images then go via send_document (no recompression).
force_document = "[[as_document]]" in response
pre_extract = response
- # Pre-extract snapshot for the #29346 recovery/invariant below.
- media_files, response = self.extract_media(response)
- media_files = self.filter_media_delivery_paths(media_files, session_key=session_key)
- images, text_content = self.extract_images(response)
- # Strip any remaining internal directives from message body (fixes #1561). _strip_media_directives
- # shares MEDIA_TAG_CLEANUP_RE, so a MEDIA: tag with an unknown extension is intentionally left in
- # the body for extract_local_files below to pick up rather than silently dropped (#34517).
- text_content = _strip_media_directives(text_content).strip()
- if images:
- logger.info("[%s] extract_images found %d image(s) in response (%d chars)", self.name, len(images), len(response))
- local_files = []
- if not is_ephemeral_response:
- local_files, text_content = self.extract_local_files(text_content)
- local_files = self.filter_local_delivery_paths(local_files, session_key=session_key)
- history = (await self._bounded_history_media_paths_for_session(session_key)
- if local_files else None)
- if history:
- suppressed = [p for p in local_files if p in history]
- if suppressed:
- logger.info("[%s] Suppressing %d bare local file path(s) already delivered in "
- "this session: %s", self.name, len(suppressed), suppressed)
- local_files = [p for p in local_files if p not in history]
- if local_files:
- logger.info("[%s] extract_local_files found %d file(s) in response", self.name, len(local_files))
+ # The handler's routed profile scope is gone by now; Docker MEDIA translation and the
+ # bare-path validator infer the sandbox from the ACTIVE profile (#109024).
+ with self._media_delivery_scope(event.source):
+ media_files, response = self.extract_media(response)
+ media_files = self.filter_media_delivery_paths(media_files, session_key=session_key)
+ images, text_content = self.extract_images(response)
+ # Strip any remaining internal directives from message body (fixes #1561). _strip_media_directives
+ # shares MEDIA_TAG_CLEANUP_RE, so a MEDIA: tag with an unknown extension is intentionally left in
+ # the body for extract_local_files below to pick up rather than silently dropped (#34517).
+ text_content = _strip_media_directives(text_content).strip()
+ if images:
+ logger.info("[%s] extract_images found %d image(s) in response (%d chars)", self.name, len(images), len(response))
+ local_files = []
+ if not is_ephemeral_response:
+ local_files, text_content = self.extract_local_files(text_content)
+ local_files = self.filter_local_delivery_paths(local_files, session_key=session_key)
+ history = (await self._bounded_history_media_paths_for_session(session_key)
+ if local_files else None)
+ if history:
+ suppressed = [p for p in local_files if p in history]
+ if suppressed:
+ logger.info("[%s] Suppressing %d bare local file path(s) already delivered in "
+ "this session: %s", self.name, len(suppressed), suppressed)
+ local_files = [p for p in local_files if p not in history]
+ if local_files:
+ logger.info("[%s] extract_local_files found %d file(s) in response", self.name, len(local_files))
# A2 (#29346): extraction can reduce a non-empty response to empty text with no attachment, and the
# `if text_content` guard below then drops it silently. Recover on every platform (#33842 was
# Discord-only); the guard avoids duplicating an attachment.
diff --git a/gateway/platforms/weixin.py b/gateway/platforms/weixin.py
index 28e7986ec82..dc0fdc6e0e0 100644
--- a/gateway/platforms/weixin.py
+++ b/gateway/platforms/weixin.py
@@ -1020,11 +1020,13 @@ class WeixinAdapter(OwnAccessPolicyMixin, BasePlatformAdapter):
return SendResult(success=False, error="Not connected")
context_token = self._token_store.get(self._account_id, chat_id)
last_message_id: Optional[str] = None
- # Extract MEDIA: tags and bare local file paths before text delivery.
- media_files, cleaned_content = self.extract_media(content)
- local_files, final_content = self.extract_local_files(self.extract_images(cleaned_content)[1])
- deliveries = [(p, v, "media") for p, v in self.filter_media_delivery_paths(media_files)]
- deliveries += [(p, False, "local file") for p in self.filter_local_delivery_paths(local_files)]
+ # Extract MEDIA: tags and bare local file paths before text delivery, under the routed
+ # profile's scope: Docker MEDIA translation infers the sandbox from the active profile (#109024).
+ with self._media_delivery_scope(self.build_source(chat_id=chat_id)):
+ media_files, cleaned_content = self.extract_media(content)
+ local_files, final_content = self.extract_local_files(self.extract_images(cleaned_content)[1])
+ deliveries = [(p, v, "media") for p, v in self.filter_media_delivery_paths(media_files)]
+ deliveries += [(p, False, "local file") for p in self.filter_local_delivery_paths(local_files)]
try:
for path, is_voice, label in deliveries:
ext = Path(path).suffix.lower()
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index dde3e7ca7a2..16b29133ffa 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -2090,6 +2090,20 @@ class GatewayTurnMixin:
return _profile_runtime_scope(self._resolve_profile_home_for_source(source))
return nullcontext()
+ def _media_delivery_scope_for_source(self, source: SessionSource):
+ """Home + terminal-policy scope for validating a turn's MEDIA / local-file paths on the
+ adapter's delivery side, which runs after the routed turn scope was reset.
+
+ Docker path translation (``platforms/base.py::_translate_docker_container_media_path``)
+ infers the producing container from the ACTIVE profile (``get_active_profile_name``) and the
+ scope-aware ``TERMINAL_DOCKER_VOLUMES``; without this a secondary's ``MEDIA:/output/x.png``
+ resolves against the default profile's sandbox and mounts (#109024). No secret hydration:
+ path validation reads no credentials and this runs on the event loop."""
+ if not getattr(getattr(self, "config", None), "multiplex_profiles", False):
+ return nullcontext()
+ from gateway.run import _profile_runtime_scope
+ return _profile_runtime_scope(self._resolve_profile_home_for_source(source), {})
+
def _reset_notice_session_info(self, source: SessionSource) -> str:
"""Session-info block for the auto-reset notice, resolved inside the profile serving ``source``.
diff --git a/tests/gateway/test_multiplex_docker_media_delivery_scope.py b/tests/gateway/test_multiplex_docker_media_delivery_scope.py
new file mode 100644
index 00000000000..78eea2d35f1
--- /dev/null
+++ b/tests/gateway/test_multiplex_docker_media_delivery_scope.py
@@ -0,0 +1,91 @@
+"""Regression for #109024: a multiplexed secondary's Docker ``MEDIA:`` paths must be validated
+under THAT profile's home + terminal policy on the adapter delivery side.
+
+The routed handler runs inside ``_profile_runtime_scope``, but ``_process_message_background``
+extracts and filters the reply's media AFTER that scope has exited. Docker path translation
+(``_docker_sandbox_dir_candidates`` / ``_parse_docker_volume_mounts``) infers the producing
+container from the ACTIVE profile, so a secondary's ``MEDIA:/output/x.png`` resolved through the
+default profile's mounts (a decoy of the same name) or was dropped as "not found on this host".
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+
+import pytest
+
+from gateway.config import GatewayConfig, Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, SendResult
+from gateway.platforms.event import MessageEvent, MessageType
+from gateway.run import GatewayRunner, _async_profile_runtime_scope
+from gateway.session import SessionSource, build_session_key
+
+
+class _Adapter(BasePlatformAdapter):
+ def __init__(self):
+ super().__init__(PlatformConfig(enabled=True, token="t"), Platform.DISCORD)
+ self.images: list[bytes] = []
+
+ async def connect(self, *, is_reconnect=False):
+ return True
+
+ async def disconnect(self):
+ return None
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ return SendResult(success=True, message_id="m")
+
+ async def send_typing(self, chat_id, metadata=None):
+ return None
+
+ async def get_chat_info(self, chat_id):
+ return {"id": chat_id}
+
+ async def send_image_file(self, chat_id, image_path, caption=None, reply_to=None, metadata=None, **kw):
+ self.images.append(Path(image_path).read_bytes())
+ return SendResult(success=True, message_id="i")
+
+
+async def _hold_typing(_chat_id, interval=2.0, metadata=None, stop_event=None):
+ await (stop_event.wait() if stop_event is not None else asyncio.Event().wait())
+
+
+def _docker_profile(home: Path, mount: Path) -> None:
+ mount.mkdir(parents=True)
+ (home / "config.yaml").write_text(json.dumps(
+ {"terminal": {"backend": "docker", "docker_volumes": [f"{mount}:/output"]}}), encoding="utf-8")
+
+
+async def test_secondary_docker_media_resolves_via_its_own_mounts(tmp_path, monkeypatch):
+ root = tmp_path / "hermes"
+ default_out, public_out = root / "cache" / "output", root / "profiles" / "public" / "cache" / "output"
+ _docker_profile(root, default_out)
+ _docker_profile(root / "profiles" / "public", public_out)
+ # The launch process carries the DEFAULT profile's bridged terminal env.
+ monkeypatch.setenv("HERMES_HOME", str(root))
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{default_out}:/output"]))
+ (public_out / "pic.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"public" * 8)
+ (default_out / "pic.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"decoy!" * 8) # same name, wrong profile
+
+ runner = GatewayRunner(GatewayConfig(multiplex_profiles=True))
+ adapter = _Adapter()
+ adapter.gateway_runner = runner
+ adapter._keep_typing = _hold_typing
+
+ async def routed_handler(event): # what _make_profile_message_handler does around _handle_message
+ event.source.profile = "public"
+ async with _async_profile_runtime_scope(root / "profiles" / "public"):
+ return "here MEDIA:/output/pic.png"
+
+ adapter.set_message_handler(routed_handler)
+ event = MessageEvent(
+ text="pic", message_type=MessageType.TEXT, message_id="m1",
+ source=SessionSource(platform=Platform.DISCORD, chat_id="1", chat_type="dm", user_id="u"))
+ await adapter._process_message_background(event, build_session_key(event.source, profile="public"))
+
+ assert len(adapter.images) == 1
+ assert b"public" in adapter.images[0]
diff --git a/tests/tui_gateway/test_mcp_profile_rpcs.py b/tests/tui_gateway/test_mcp_profile_rpcs.py
index 17708893fc0..88f9f947ffb 100644
--- a/tests/tui_gateway/test_mcp_profile_rpcs.py
+++ b/tests/tui_gateway/test_mcp_profile_rpcs.py
@@ -360,3 +360,31 @@ def test_default_profile_add_when_profile_omitted(hermes_root):
assert "rootsvc" not in _read_yaml(root / "profiles" / "work" / "config.yaml").get(
"mcp_servers", {}
)
+
+
+def test_test_resolves_env_refs_from_requested_profile_secret_scope(hermes_root, monkeypatch):
+ """``mcp.servers.test`` for a secondary must expand its ``${VAR}`` header from THAT profile's
+ secret scope, not the launch process's ``os.environ`` (the default profile's value) — the
+ Desktop MCP setup "Test connection" otherwise reports green against the wrong credential.
+ ``os.environ`` is never mutated by the scope."""
+ import hermes_cli.mcp_config as mcp_config
+
+ work = hermes_root / "profiles" / "work"
+ (work / ".env").write_text("ALPHA_ONLY_TOKEN=work-token\n", encoding="utf-8")
+ (work / "config.yaml").write_text(
+ "mcp_servers:\n srv:\n url: http://x/mcp\n"
+ " headers:\n Authorization: Bearer ${ALPHA_ONLY_TOKEN}\n", encoding="utf-8")
+ monkeypatch.setenv("ALPHA_ONLY_TOKEN", "default-process-token")
+
+ resolved = {}
+
+ def fake_probe(name, config, connect_timeout=30, details=None):
+ resolved.update(mcp_config._resolve_mcp_server_config(config).get("headers", {}))
+ return [("tool-a", "desc")]
+
+ monkeypatch.setattr(mcp_config, "_probe_single_server", fake_probe)
+ result = _result(_call("mcp.servers.test", {"profile": "work", "name": "srv"}))
+
+ assert result["ok"] is True
+ assert resolved["Authorization"] == "Bearer work-token"
+ assert os.environ["ALPHA_ONLY_TOKEN"] == "default-process-token"