Skip to content

The agent that grows with you

fix(cli): gate fs container-path translation on docker, host-first, per profile

Austin Pickett581eb6184dbb
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 7e2789708d1..693c5f654ac 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -1068,13 +1068,14 @@ def _cache_dir_container_mounts() -> list[tuple[Path, Path]]:
return []
-def _warn_unresolved_docker_media(candidate: Path, session_key: str, reason: str) -> None:
+def _warn_unresolved_docker_media(candidate: Path, session_key: str, reason: str, quiet: bool = False) -> None:
"""Name WHY a container-absolute MEDIA path failed translation (otherwise the only signal is
- the generic "Skipping unsafe MEDIA directive path" line). Docker-only; host rejections quiet.
+ the generic "Skipping unsafe MEDIA directive path" line). Docker-only; host rejections and ``quiet``
+ callers (fs routes, which also see ordinary host paths) stay silent.
See #93950.
"""
- if not _docker_env_active():
+ if quiet or not _docker_env_active():
return
logger.warning("Docker MEDIA path %s did not resolve to a host sandbox file (%s%s); "
"the producing container's sandbox directory may not exist yet or "
@@ -1082,7 +1083,7 @@ def _warn_unresolved_docker_media(candidate: Path, session_key: str, reason: str
f", session_key={session_key}" if session_key else "")
-def _translate_docker_container_media_path(candidate: Path, session_key: str = "") -> Optional[Path]:
+def _translate_docker_container_media_path(candidate: Path, session_key: str = "", *, quiet: bool = False) -> Optional[Path]:
"""Container-absolute path -> host path via longest-prefix match over ``docker_volumes``, the
auto-mounted cache dirs (``/root/.hermes/...``), persistent ``/workspace`` and ``/root``."""
if not candidate.as_posix().startswith("/"): # POSIX even on Windows gateways (not is_absolute)
@@ -1104,7 +1105,7 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = "
mounts.extend(
(root, Path("/root")) for root in _docker_persistent_sandbox_roots(session_key, "home"))
if not mounts:
- _warn_unresolved_docker_media(candidate, session_key, "no sandbox mounts resolved")
+ _warn_unresolved_docker_media(candidate, session_key, "no sandbox mounts resolved", quiet)
return None
# Longest container-prefix match; equal-length prefixes are tried in insertion order.
candidate_posix = candidate.as_posix()
@@ -1112,14 +1113,14 @@ def _translate_docker_container_media_path(candidate: Path, session_key: str = "
for prefix in (container_root.as_posix().rstrip("/") or "/",)
if candidate_posix == prefix or candidate_posix.startswith(prefix + "/")]
if not matched:
- _warn_unresolved_docker_media(candidate, session_key, "no mounted prefix matches")
+ _warn_unresolved_docker_media(candidate, session_key, "no mounted prefix matches", quiet)
return None
for host_root, container_root, _score in sorted(matched, key=lambda m: -m[2]):
translated = _resolve_path(host_root / candidate.relative_to(container_root), strict=True)
if translated is not None and (
translated == host_root or _path_is_within(translated, host_root)):
return translated
- _warn_unresolved_docker_media(candidate, session_key, "host file missing from sandbox")
+ _warn_unresolved_docker_media(candidate, session_key, "host file missing from sandbox", quiet)
return None
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index bb18911262f..7cc7b96127c 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -29,8 +29,8 @@ from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access
from hermes_cli.web_deps import late
from hermes_cli.web_server_files import (
- _agent_fs_path, _fs_path, _hosted_fs_read_guard, _managed_file_entry,
- _managed_response_meta, _resolve_managed_path,
+ SANDBOX_NOT_FOUND, _agent_fs_path, _fs_path, _hosted_fs_read_guard, _is_unmapped_container_path,
+ _managed_file_entry, _managed_response_meta, _resolve_managed_path,
)
from hermes_cli.web_models import (
ChatImageUpload, FsWriteText, ManagedDirectoryCreate, ManagedFileDelete, ManagedFileUpload,
@@ -160,18 +160,9 @@ def _io_errors(denied: str, failed: str):
raise HTTPException(status_code=500, detail=f"{failed}: {exc}")
-def _fs_docker_active() -> bool:
- """True when the gateway runs the docker terminal backend (#85238 detail)."""
- from gateway.platforms.base import _docker_env_active
-
- return _docker_env_active()
-
-
def _fs_sandbox_not_found_detail(path: Path) -> str:
"""Distinguish an untranslated agent-sandbox path from a plain missing file."""
- if _fs_docker_active() and path.as_posix().startswith("/"):
- return "File not found on the gateway host: the path may live inside the agent sandbox"
- return "File not found"
+ return SANDBOX_NOT_FOUND if _is_unmapped_container_path(path.as_posix()) else "File not found"
def _fs_regular_file(path: Path) -> tuple[Path, os.stat_result]:
@@ -783,7 +774,7 @@ async def fs_list(path: str, request: Request, profile: Optional[str] = None):
return await asyncio.to_thread(backend.list_dir, path, _FS_READDIR_HIDDEN)
except Exception as exc:
_raise_fs_backend_error(exc)
- target = _agent_fs_path(path)
+ target = _agent_fs_path(path, profile_home=_fs_profile_home(profile))
_hosted_fs_read_guard(target, request)
try:
entries = []
@@ -828,7 +819,7 @@ async def fs_read_text(path: str, request: Request = None, profile: Optional[str
"text": data.decode("utf-8", errors="replace"),
"truncated": size > _FS_TEXT_PREVIEW_MAX_BYTES,
}
- target = _agent_fs_path(path)
+ target = _agent_fs_path(path, profile_home=_fs_profile_home(profile))
_hosted_fs_read_guard(target, request)
target, st = _fs_regular_file(target)
if st.st_size > _FS_TEXT_SOURCE_MAX_BYTES:
@@ -905,6 +896,8 @@ async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
async def _fs_download_path(path: str, profile: Optional[str], session_id: Optional[str]) -> Path:
+ # Resolve container paths in the requested profile's sandbox, not the active one's.
+ profile_home = _fs_profile_home(profile)
if session_id is not None:
from hermes_cli.web_routers.sessions import get_session_detail
@@ -912,12 +905,17 @@ async def _fs_download_path(path: str, profile: Optional[str], session_id: Optio
raise HTTPException(status_code=404, detail="Session not found")
session = await get_session_detail(session_id, profile)
# Validate ownership even for absolute paths; never trust a client cwd.
- return _agent_fs_path(path, cwd=session.get("cwd") or "")
- if profile is not None:
- from hermes_cli.web_server_cron import _cron_profile_home
+ return _agent_fs_path(path, cwd=session.get("cwd") or "", profile_home=profile_home)
+ return _agent_fs_path(path, profile_home=profile_home)
+
+
+def _fs_profile_home(profile: Optional[str]) -> Optional[Path]:
+ """HERMES_HOME of a requested profile (404/400 on an unknown one), None for the active one."""
+ if profile is None:
+ return None
+ from hermes_cli.web_server_cron import _cron_profile_home
- _cron_profile_home(profile)
- return _agent_fs_path(path)
+ return _cron_profile_home(profile)[1]
@router.get("/api/fs/read-data-url")
diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.py
index 7c3c80f577e..ba975816f0e 100644
--- a/hermes_cli/web_server_files.py
+++ b/hermes_cli/web_server_files.py
@@ -69,41 +69,65 @@ def _fs_path(raw_path: str, *, cwd: str | None = None, decode_fallback: bool = T
raise HTTPException(status_code=400, detail="Invalid path")
-def _agent_container_path(raw: str) -> Path | None:
+def _translate_agent_path(candidate: Path) -> Path | None:
+ """One translation attempt under whatever scope is bound; None off the docker backend.
+
+ The gate keeps a local-backend gateway with leftover ``docker_volumes`` from serving
+ mount sources in place of real host files. Quiet: fs callers also see ordinary host
+ paths, which are not MEDIA misses worth a warning."""
+ from gateway.platforms.base import _docker_env_active, _translate_docker_container_media_path
+ from tools.terminal_tool import _ensure_terminal_env_bridged
+
+ _ensure_terminal_env_bridged()
+ if not _docker_env_active():
+ return None
+ return _translate_docker_container_media_path(candidate, quiet=True)
+
+
+def _agent_container_path(raw: str, *, profile_home: Path | None = None) -> Path | None:
"""Map an agent-visible container path to its host bind mount, or None.
Docker agents emit container paths (``/workspace/...``, ``/root/...``) in
transcripts and MEDIA tags, while the dashboard fs routes stat the gateway
- HOST filesystem (#85238). Reuse the gateway's MEDIA volume translator, and
- when no terminal scope is bound (``serve --isolated`` after a failed early
- bridge) retry once under the profile's complete terminal policy, never
- replacing an already-bound scope or refusal (retry from #104992).
+ HOST filesystem (#85238). Reuse the gateway's MEDIA volume translator.
+
+ ``profile_home`` (a request's ``profile``) binds that profile's home and
+ terminal policy, as MEDIA delivery does (#109024), so its sandbox and mounts
+ are used rather than the active profile's. Without one, when no terminal
+ scope is bound (``serve --isolated`` after a failed early bridge), retry once
+ under the active profile's complete terminal policy, never replacing an
+ already-bound scope or refusal (retry from #104992).
Runs on the raw string, before host normalization: on a Windows gateway
``Path("/workspace/x").resolve()`` anchors to the current drive and the
- container path is gone before translation sees it.
+ container path is gone before translation sees it. ``..`` segments are never
+ translated, so the managed routes keep refusing them.
"""
- if not raw.startswith("/") or raw.startswith("//"):
+ if not raw.startswith("/") or raw.startswith("//") or ".." in raw.split("/"):
return None
try:
- from gateway.platforms.base import _translate_docker_container_media_path
-
- candidate = Path(raw)
- translated = _translate_docker_container_media_path(candidate)
- if translated is not None:
- return translated
-
+ from hermes_cli.config import get_hermes_home
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
from tools.terminal_scope import (
- build_profile_terminal_scope, get_terminal_scope, reset_terminal_scope,
- set_terminal_scope,
+ build_profile_terminal_scope, get_terminal_scope, install_and_reset_profile_terminal_scope,
+ reset_terminal_scope, set_terminal_scope,
)
- if get_terminal_scope() is not None:
- return None
- from hermes_cli.config import get_hermes_home
+ candidate = Path(raw)
+ if profile_home is not None and Path(profile_home).resolve() != get_hermes_home().resolve():
+ home_token = set_hermes_home_override(str(profile_home))
+ try:
+ with install_and_reset_profile_terminal_scope(profile_home):
+ return _translate_agent_path(candidate)
+ finally:
+ reset_hermes_home_override(home_token)
+
+ translated = _translate_agent_path(candidate)
+ if translated is not None or get_terminal_scope() is not None:
+ return translated
token = set_terminal_scope(build_profile_terminal_scope(get_hermes_home()))
try:
- return _translate_docker_container_media_path(candidate)
+ return _translate_agent_path(candidate)
finally:
reset_terminal_scope(token)
except Exception: # fail open: translation is additive, the host path still serves
@@ -111,12 +135,51 @@ def _agent_container_path(raw: str) -> Path | None:
return None
-def _agent_fs_path(raw_path: str, *, cwd: str | None = None) -> Path:
- """``_fs_path`` for agent-facing reads: container paths resolve to their host
- mount first, so callers' boundary guards see the real host target. Fails open
- to the plain host path — translation is additive, not a gate."""
- translated = _agent_container_path(str(raw_path or "").strip())
- return translated if translated is not None else _fs_path(raw_path, cwd=cwd)
+SANDBOX_NOT_FOUND = "File not found on the gateway host: the path may live inside the agent sandbox"
+
+
+def _agent_fs_path(
+ raw_path: str, *, cwd: str | None = None, profile_home: Path | None = None,
+) -> Path:
+ """``_fs_path`` for agent-facing reads; container paths resolve to their host
+ mount, so callers' boundary guards see the real host target.
+
+ POSIX: a readable host path wins, and translation only runs when the host
+ lookup misses, so a root-run gateway can still browse its own ``/root``.
+ Windows: a container-shaped path never names a host file (it would anchor to
+ the current drive), so a translation miss is a 404 rather than a drive lookup.
+ """
+ raw = str(raw_path or "").strip()
+ if os.name != "nt":
+ host = _fs_path(raw_path, cwd=cwd)
+ if os.access(host, os.R_OK):
+ return host
+ translated = _agent_container_path(raw, profile_home=profile_home)
+ return translated if translated is not None else host
+ translated = _agent_container_path(raw, profile_home=profile_home)
+ if translated is not None:
+ return translated
+ if _is_unmapped_container_path(raw):
+ raise HTTPException(status_code=404, detail=SANDBOX_NOT_FOUND)
+ return _fs_path(raw_path, cwd=cwd)
+
+
+def _is_unmapped_container_path(raw: str) -> bool:
+ """A docker-backend container path (``/workspace``, ``/root`` or a configured
+ volume target) rather than a host path or a typo elsewhere on the host."""
+ if not raw.startswith("/") or raw.startswith("//"):
+ return False
+ try:
+ from gateway.platforms.base import _docker_env_active, _parse_docker_volume_mounts
+ from tools.environments.local import _msys_to_windows_path
+
+ if not _docker_env_active() or _msys_to_windows_path(raw) != raw:
+ return False
+ roots = {"/workspace", "/root", *(c.as_posix() for _, c in _parse_docker_volume_mounts())}
+ except Exception: # a refusal scope or import failure: just skip the hint
+ logger.debug("container path classification failed for %s", raw, exc_info=True)
+ return False
+ return any(raw == r or raw.startswith(r.rstrip("/") + "/") for r in roots)
def _canonical_path(path: Path, *, require_exists: bool = False) -> Path:
@@ -218,10 +281,11 @@ def _resolve_managed_path(
text = _path_text(raw_path)
root = policy.locked_root
- if for_agent_read and text and not text.startswith("file:"):
+ if for_agent_read and text and not text.startswith("file:") and (
+ os.name == "nt" or not os.access(text, os.R_OK)):
# Agent-emitted container paths (/workspace/...) resolve to their host
# bind mount before the root checks, so the locked-root refusal below
- # still governs the translated target (#85238).
+ # still governs the translated target (#85238). A readable host path wins.
translated = _agent_container_path(text)
if translated is not None:
text = str(translated)
diff --git a/tests/hermes_cli/test_web_server_files.py b/tests/hermes_cli/test_web_server_files.py
index 864d6ec1259..c24a5ec9e25 100644
--- a/tests/hermes_cli/test_web_server_files.py
+++ b/tests/hermes_cli/test_web_server_files.py
@@ -272,6 +272,19 @@ def test_managed_reads_resolve_docker_mount_inside_locked_root(
assert stream.status_code == 415
+def test_managed_read_still_refuses_dotdot_in_container_path(forced_files_client, monkeypatch):
+ """``..`` stays refused even when the path would translate inside the mount."""
+ client, root = forced_files_client
+ (root / "sub").mkdir(parents=True, exist_ok=True)
+ (root / "ok.txt").write_text("ok", encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{root}:/workspace"]))
+
+ response = client.get("/api/files/read", params={"path": "/workspace/sub/../ok.txt"})
+
+ assert response.status_code == 400, response.text
+
+
def test_managed_reads_reject_docker_mount_outside_locked_root(
forced_files_client, monkeypatch, tmp_path,
):
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index ec797300620..b394511b159 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -441,7 +441,7 @@ def test_fs_reads_translate_after_binding_profile_terminal_scope(client, tmp_pat
from tools.terminal_scope import get_terminal_scope
- def translate(path):
+ def translate(path, session_key="", *, quiet=False):
if path == Path("/workspace/isolated report.txt") and get_terminal_scope() is not None:
return target
return None
@@ -505,6 +505,7 @@ def test_fs_download_maps_root_home_to_persistent_sandbox(client, monkeypatch, t
assert response.content == b"PK\x03\x04zip"
def test_agent_fs_path_translates_before_host_normalization(monkeypatch, tmp_path):
"""On a Windows gateway ``_fs_path("/workspace/x")`` anchors to the current
drive (``D:\\workspace\\x``) and could serve an unrelated host file; the
@@ -514,10 +515,11 @@ def test_agent_fs_path_translates_before_host_normalization(monkeypatch, tmp_pat
mapped = tmp_path / "x.txt"
seen = []
- def translate(candidate, session_key=""):
+ def translate(candidate, session_key="", *, quiet=False):
seen.append(candidate.as_posix())
return mapped
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
monkeypatch.setattr("gateway.platforms.base._translate_docker_container_media_path", translate)
def boom(*_a, **_k):
@@ -529,6 +531,107 @@ def test_agent_fs_path_translates_before_host_normalization(monkeypatch, tmp_pat
assert seen == ["/workspace/x.txt"]
+def test_agent_fs_path_unmapped_container_path_404s_on_windows(monkeypatch):
+ """A container path that misses translation must not fall back to the drive."""
+ from fastapi import HTTPException
+
+ from hermes_cli import web_server_files
+
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_CONTAINER_PERSISTENT", "false")
+ monkeypatch.delenv("TERMINAL_DOCKER_VOLUMES", raising=False)
+
+ def boom(*_a, **_k):
+ raise AssertionError("an unmapped container path must not reach _fs_path")
+
+ monkeypatch.setattr(web_server_files, "_fs_path", boom)
+ with pytest.raises(HTTPException) as exc:
+ web_server_files._agent_fs_path("/workspace/x.txt")
+ assert exc.value.status_code == 404
+ assert "agent sandbox" in exc.value.detail
+
+
+def test_readable_host_path_wins_over_root_sandbox(client, monkeypatch, tmp_path):
+ """Host-first on POSIX: a readable host file is served even when the docker
+ sandbox has a file at the same container path."""
+ sandbox = tmp_path / "sandboxes"
+ host_dir = tmp_path / "host"
+ host_dir.mkdir()
+ (host_dir / "f.txt").write_text("HOST", encoding="utf-8")
+ sandbox_ws = tmp_path / "mount"
+ sandbox_ws.mkdir()
+ (sandbox_ws / "f.txt").write_text("SANDBOX", encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ monkeypatch.setenv("TERMINAL_SANDBOX_DIR", str(sandbox))
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{sandbox_ws}:{host_dir}"]))
+
+ response = client.get("/api/fs/read-text", params={"path": str(host_dir / "f.txt")})
+
+ assert response.status_code == 200
+ assert response.json()["text"] == "HOST"
+
+
+def test_local_backend_ignores_leftover_docker_volumes(client, monkeypatch, tmp_path):
+ """terminal.backend=local with docker_volumes still configured: no translation."""
+ real = tmp_path / "real"
+ alt = tmp_path / "alt"
+ real.mkdir()
+ alt.mkdir()
+ (alt / "x.txt").write_text("MOUNTED-COPY", encoding="utf-8")
+ monkeypatch.setenv("TERMINAL_ENV", "local")
+ monkeypatch.setenv("TERMINAL_DOCKER_VOLUMES", json.dumps([f"{alt}:{real}"]))
+
+ response = client.get("/api/fs/read-text", params={"path": str(real / "x.txt")})
+
+ assert response.status_code == 404
+ assert response.json()["detail"] == "File not found"
+
+
+def test_fs_download_profile_uses_that_profiles_sandbox(client, monkeypatch, tmp_path):
+ """``profile=work`` must resolve /root/... in the work profile's sandbox, not the
+ active profile's."""
+ from hermes_cli import profiles
+
+ default_home = tmp_path / "default-home"
+ work_home = default_home / "profiles" / "work"
+ for home in (default_home, work_home):
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text(
+ "terminal:\n backend: docker\n container_persistent: true\n", encoding="utf-8")
+ monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
+ monkeypatch.setenv("HERMES_HOME", str(default_home))
+ monkeypatch.delenv("TERMINAL_SANDBOX_DIR", raising=False)
+ monkeypatch.delenv("TERMINAL_DOCKER_VOLUMES", raising=False)
+ monkeypatch.setenv("TERMINAL_ENV", "docker")
+ from tools.environments.path_utils import sanitize_task_id_for_path
+
+ (default_home / "sandboxes/docker/default/home").mkdir(parents=True)
+ (default_home / "sandboxes/docker/default/home/f.txt").write_bytes(b"DEFAULT")
+ work_dir = work_home / "sandboxes/docker" / sanitize_task_id_for_path("profile:work") / "home"
+ work_dir.mkdir(parents=True)
+ (work_dir / "f.txt").write_bytes(b"WORK")
+
+ work = client.get("/api/fs/download", params={"path": "/root/f.txt", "profile": "work"})
+ default = client.get("/api/fs/download", params={"path": "/root/f.txt"})
+
+ assert work.status_code == 200, work.text
+ assert work.content == b"WORK"
+ assert default.content == b"DEFAULT"
+
+
+def test_fs_read_plain_host_path_logs_no_docker_media_warning(client, docker_volumes, tmp_path, caplog):
+ """fs routes see ordinary host paths constantly; misses are not MEDIA warnings."""
+ plain = tmp_path / "plain.txt"
+ plain.write_text("x", encoding="utf-8")
+ with caplog.at_level("WARNING", logger="gateway.platforms.base"):
+ client.get("/api/fs/read-text", params={"path": str(plain)})
+ client.get("/api/fs/read-text", params={"path": str(tmp_path / "missing.txt")})
+ client.get("/api/fs/list", params={"path": str(tmp_path)})
+ assert not [r for r in caplog.records if "Docker MEDIA path" in r.getMessage()]
+
+
def test_agent_fs_path_leaves_host_paths_to_fs_path(monkeypatch, tmp_path):
from hermes_cli import web_server_files