Skip to content

The agent that grows with you

fix(desktop): secure SSH workspace browsing

fangliquanflqe1ab5577165a
diff --git a/hermes_cli/ssh_workspace_fs.py b/hermes_cli/ssh_workspace_fs.py
new file mode 100644
index 00000000000..7814309235c
--- /dev/null
+++ b/hermes_cli/ssh_workspace_fs.py
@@ -0,0 +1,293 @@
+"""Filesystem adapter for Desktop workspaces executed over SSH."""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import posixpath
+import shlex
+import subprocess
+import threading
+import uuid
+from dataclasses import dataclass
+from typing import Any, Iterator
+
+from hermes_cli._subprocess_compat import windows_hide_flags
+from tools.environments.ssh import SSHEnvironment
+
+
+class SshWorkspaceFsError(RuntimeError):
+ """A filesystem error reported by the SSH execution target."""
+
+ def __init__(self, code: str, message: str | None = None):
+ super().__init__(message or code)
+ self.code = code
+
+
+@dataclass(frozen=True)
+class _SshFsConfig:
+ host: str
+ user: str
+ port: int
+ key_path: str
+ cwd: str
+ timeout: int
+
+
+_CACHE_LOCK = threading.RLock()
+_BACKENDS: dict[str, tuple[_SshFsConfig, "SshWorkspaceFs"]] = {}
+
+
+class SshWorkspaceFs:
+ """Binary-safe workspace operations using the configured SSH transport."""
+
+ def __init__(self, env: SSHEnvironment):
+ self._env = env
+ self._lock = threading.RLock()
+
+ @property
+ def cwd(self) -> str:
+ return self._normalize(self._env.cwd)
+
+ def _normalize(self, path: str) -> str:
+ raw = str(path or "").strip()
+ if not raw:
+ raise SshWorkspaceFsError("EINVAL", "Path is required")
+ if "\0" in raw or raw.lower().startswith("file:"):
+ raise SshWorkspaceFsError("EINVAL", "Invalid path")
+ if raw == "~":
+ raw = self._env._remote_home
+ elif raw.startswith("~/"):
+ raw = posixpath.join(self._env._remote_home, raw[2:])
+ elif not raw.startswith("/"):
+ raw = posixpath.join(self._env.cwd, raw)
+ return posixpath.normpath(raw)
+
+ def _execute(self, command: str, *, stdin_data: str | None = None, timeout: int | None = None) -> dict:
+ with self._lock:
+ return self._env.execute(
+ command,
+ cwd=self._env.cwd,
+ stdin_data=stdin_data,
+ timeout=timeout or self._env.timeout,
+ )
+
+ @staticmethod
+ def _error_code(output: str, fallback: str = "EIO") -> str:
+ marker = "__HERMES_FS_ERROR__:"
+ for line in (output or "").splitlines():
+ if line.startswith(marker):
+ return line[len(marker) :].strip() or fallback
+ return fallback
+
+ def list_dir(self, path: str, hidden_names: set[str] | frozenset[str]) -> dict[str, Any]:
+ target = self._normalize(path)
+ quoted = shlex.quote(target)
+ command = f"""
+p={quoted}
+if [ ! -e "$p" ] && [ ! -L "$p" ]; then printf '__HERMES_FS_ERROR__:ENOENT\\n'; exit 44; fi
+if [ ! -d "$p" ]; then printf '__HERMES_FS_ERROR__:ENOTDIR\\n'; exit 45; fi
+if [ ! -r "$p" ]; then printf '__HERMES_FS_ERROR__:EACCES\\n'; exit 46; fi
+for child in "$p"/* "$p"/.[!.]* "$p"/..?*; do
+ [ -e "$child" ] || [ -L "$child" ] || continue
+ name=${{child##*/}}
+ name64=$(printf '%s' "$name" | base64 | tr -d '\\r\\n')
+ path64=$(printf '%s' "$child" | base64 | tr -d '\\r\\n')
+ if [ -d "$child" ]; then kind=d; else kind=f; fi
+ printf '%s\\t%s\\t%s\\n' "$name64" "$path64" "$kind"
+done
+"""
+ result = self._execute(command)
+ if result.get("returncode") != 0:
+ return {"entries": [], "error": self._error_code(result.get("output", ""), "read-error")}
+
+ entries = []
+ try:
+ for line in result.get("output", "").splitlines():
+ if not line.strip():
+ continue
+ name64, path64, kind = line.split("\t", 2)
+ name = base64.b64decode(name64, validate=True).decode("utf-8", errors="replace")
+ child_path = base64.b64decode(path64, validate=True).decode("utf-8", errors="replace")
+ if name in hidden_names:
+ continue
+ entries.append({"name": name, "path": child_path, "isDirectory": kind == "d"})
+ except (ValueError, UnicodeError, binascii.Error) as exc:
+ raise SshWorkspaceFsError("EIO", "SSH filesystem returned an invalid directory listing") from exc
+
+ entries.sort(key=lambda item: (not item["isDirectory"], item["name"].lower(), item["name"]))
+ return {"entries": entries}
+
+ def read_bytes(
+ self,
+ path: str,
+ *,
+ max_bytes: int,
+ read_limit: int | None = None,
+ ) -> tuple[bytes, int, str]:
+ target = self._normalize(path)
+ quoted = shlex.quote(target)
+ read_command = (
+ f"set -o pipefail; head -c {int(read_limit)} < \"$p\" | base64"
+ if read_limit is not None
+ else 'base64 < "$p"'
+ )
+ command = f"""
+p={quoted}
+if [ ! -e "$p" ] && [ ! -L "$p" ]; then printf '__HERMES_FS_ERROR__:ENOENT\\n'; exit 44; fi
+if [ ! -f "$p" ]; then printf '__HERMES_FS_ERROR__:ENOTREG\\n'; exit 45; fi
+size=$(stat -c %s "$p" 2>/dev/null || stat -f %z "$p" 2>/dev/null) || {{ printf '__HERMES_FS_ERROR__:EACCES\\n'; exit 46; }}
+if [ "$size" -gt {int(max_bytes)} ]; then printf '__HERMES_FS_ERROR__:EFBIG\\n'; exit 47; fi
+printf '__HERMES_FS_SIZE__:%s\\n' "$size"
+{{ {read_command}; }} || {{ printf '__HERMES_FS_ERROR__:EACCES\\n'; exit 46; }}
+"""
+ result = self._execute(command)
+ output = result.get("output", "")
+ if result.get("returncode") != 0:
+ raise SshWorkspaceFsError(self._error_code(output))
+ lines = output.splitlines()
+ if not lines or not lines[0].startswith("__HERMES_FS_SIZE__:"):
+ raise SshWorkspaceFsError("EIO", "SSH filesystem did not return a file size")
+ try:
+ size = int(lines[0].split(":", 1)[1])
+ except ValueError as exc:
+ raise SshWorkspaceFsError("EIO", "SSH filesystem returned an invalid file size") from exc
+ encoded = "".join(lines[1:])
+ try:
+ data = base64.b64decode(encoded, validate=True)
+ except (ValueError, binascii.Error) as exc:
+ raise SshWorkspaceFsError("EIO", "SSH filesystem returned invalid file data") from exc
+ return data, size, target
+
+ def inspect_file(self, path: str) -> tuple[str, int]:
+ """Return a regular file's resolved remote path and size without reading it."""
+ target = self._normalize(path)
+ command = f"""
+p={shlex.quote(target)}
+target=$(realpath "$p" 2>/dev/null || readlink -f "$p" 2>/dev/null) || {{ printf '__HERMES_FS_ERROR__:ENOENT\\n'; exit 44; }}
+if [ ! -f "$target" ]; then printf '__HERMES_FS_ERROR__:ENOTREG\\n'; exit 45; fi
+size=$(stat -c %s "$target" 2>/dev/null || stat -f %z "$target" 2>/dev/null) || {{ printf '__HERMES_FS_ERROR__:EACCES\\n'; exit 46; }}
+printf '__HERMES_FS_TARGET__:%s\\n' "$(printf '%s' "$target" | base64 | tr -d '\\r\\n')"
+printf '__HERMES_FS_SIZE__:%s\\n' "$size"
+"""
+ result = self._execute(command)
+ output = result.get("output", "")
+ if result.get("returncode") != 0:
+ raise SshWorkspaceFsError(self._error_code(output))
+ target_line = next((line for line in output.splitlines() if line.startswith("__HERMES_FS_TARGET__:")), "")
+ size_line = next((line for line in output.splitlines() if line.startswith("__HERMES_FS_SIZE__:")), "")
+ if not target_line or not size_line:
+ raise SshWorkspaceFsError("EIO", "SSH filesystem did not return file metadata")
+ try:
+ resolved = base64.b64decode(target_line.split(":", 1)[1], validate=True).decode("utf-8", errors="strict")
+ size = int(size_line.split(":", 1)[1])
+ except (ValueError, UnicodeError, binascii.Error) as exc:
+ raise SshWorkspaceFsError("EIO", "SSH filesystem returned invalid file metadata") from exc
+ return resolved, size
+
+ def stream_file(self, path: str, chunk_size: int = 64 * 1024) -> Iterator[bytes]:
+ """Stream an already-authorized remote file without buffering it in memory."""
+ target = self._normalize(path)
+ command = self._env._build_ssh_command()
+ command.extend(["bash", "-c", shlex.quote(f"exec cat < {shlex.quote(target)}")])
+ process = subprocess.Popen(
+ command,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ creationflags=windows_hide_flags(),
+ )
+ try:
+ assert process.stdout is not None
+ while chunk := process.stdout.read(chunk_size):
+ yield chunk
+ finally:
+ if process.poll() is None:
+ process.terminate()
+ process.wait()
+
+ def write_text(self, path: str, content: str, *, max_bytes: int) -> tuple[str, int]:
+ target = self._normalize(path)
+ encoded_size = len(content.encode("utf-8"))
+ if encoded_size > max_bytes:
+ raise SshWorkspaceFsError("EFBIG")
+ parent = posixpath.dirname(target) or "/"
+ temp_path = posixpath.join(parent, f".{posixpath.basename(target)}.hermes-tmp-{uuid.uuid4().hex[:12]}")
+ q_target = shlex.quote(target)
+ q_parent = shlex.quote(parent)
+ q_temp = shlex.quote(temp_path)
+ command = f"""
+target={q_target}
+parent={q_parent}
+tmp={q_temp}
+if [ ! -d "$parent" ]; then printf '__HERMES_FS_ERROR__:ENOENT\\n'; exit 44; fi
+if [ -e "$target" ] && [ ! -f "$target" ]; then printf '__HERMES_FS_ERROR__:ENOTREG\\n'; exit 45; fi
+trap 'rm -f "$tmp"' EXIT HUP INT TERM
+cat > "$tmp" && mv -f "$tmp" "$target"
+"""
+ result = self._execute(command, stdin_data=content)
+ if result.get("returncode") != 0 or result.get("stdin_error"):
+ raise SshWorkspaceFsError(self._error_code(result.get("output", "")))
+ return target, encoded_size
+
+ def git_root(self, path: str) -> str | None:
+ target = self._normalize(path)
+ quoted = shlex.quote(target)
+ command = f"""
+p={quoted}
+[ -d "$p" ] || p=${{p%/*}}
+while [ -n "$p" ]; do
+ if [ -e "$p/.git" ]; then printf '%s\\n' "$p"; exit 0; fi
+ [ "$p" = / ] && break
+ p=${{p%/*}}; [ -n "$p" ] || p=/
+done
+exit 1
+"""
+ result = self._execute(command)
+ if result.get("returncode") != 0:
+ return None
+ return (result.get("output") or "").strip() or None
+
+ def git_branch(self, path: str) -> str:
+ target = self._normalize(path)
+ result = self._execute(f"git -C {shlex.quote(target)} branch --show-current 2>/dev/null")
+ return (result.get("output") or "").strip() if result.get("returncode") == 0 else ""
+
+
+def get_ssh_workspace_fs(profile_key: str, terminal_config: dict[str, Any]) -> SshWorkspaceFs | None:
+ """Return a cached adapter when this profile selects the SSH backend."""
+ if str(terminal_config.get("backend") or "local").strip().lower() != "ssh":
+ return None
+
+ config = _SshFsConfig(
+ host=str(terminal_config.get("ssh_host") or "").strip(),
+ user=str(terminal_config.get("ssh_user") or "").strip(),
+ port=int(terminal_config.get("ssh_port") or 22),
+ key_path=str(terminal_config.get("ssh_key") or "").strip(),
+ cwd=str(terminal_config.get("cwd") or "~").strip() or "~",
+ timeout=int(terminal_config.get("timeout") or 180),
+ )
+ if not config.host or not config.user:
+ raise SshWorkspaceFsError("ECONN", "SSH host and user are required")
+
+ with _CACHE_LOCK:
+ cached = _BACKENDS.get(profile_key)
+ if cached and cached[0] == config:
+ return cached[1]
+ if cached:
+ cached[1]._env.cleanup()
+ try:
+ env = SSHEnvironment(
+ host=config.host,
+ user=config.user,
+ cwd=config.cwd,
+ timeout=config.timeout,
+ port=config.port,
+ key_path=config.key_path,
+ sync_files=False,
+ )
+ except Exception as exc:
+ raise SshWorkspaceFsError("ECONN", "Could not connect to the SSH workspace") from exc
+ backend = SshWorkspaceFs(env)
+ _BACKENDS[profile_key] = (config, backend)
+ return backend
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 7d55ae923de..b6fc5f7ccfa 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -17,12 +17,13 @@ import stat
import subprocess
import sys
import tempfile
+import urllib.parse
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, Optional
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
-from fastapi.responses import FileResponse
+from fastapi.responses import FileResponse, StreamingResponse
from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_cli.sqlite_safe_read import LiveConnectionError, offline_file_access
@@ -40,6 +41,7 @@ router = APIRouter()
_profile_scope = late("_profile_scope", "hermes_cli.web_server_profiles")
get_hermes_home = late("get_hermes_home", "hermes_cli.config")
load_config = late("load_config", "hermes_cli.config")
+load_env = late("load_env", "hermes_cli.config")
# Image types GET /api/media serves — extension-allowlisted so an authenticated
# caller can't pull non-image files through it.
_MEDIA_CONTENT_TYPES = {
@@ -256,6 +258,51 @@ def _fs_git_branch(cwd: str) -> str:
return ""
+def _fs_backend(profile: Optional[str] = None):
+ """Return the profile's SSH workspace adapter, or None for host-local FS."""
+ from hermes_cli.ssh_workspace_fs import get_ssh_workspace_fs
+
+ with _profile_scope(profile):
+ terminal = dict(load_config().get("terminal") or {})
+ profile_env = load_env()
+ for key, env_name in {
+ "ssh_host": "TERMINAL_SSH_HOST",
+ "ssh_user": "TERMINAL_SSH_USER",
+ "ssh_port": "TERMINAL_SSH_PORT",
+ "ssh_key": "TERMINAL_SSH_KEY",
+ }.items():
+ if not terminal.get(key) and profile_env.get(env_name):
+ terminal[key] = profile_env[env_name]
+ profile_key = (profile or "current").strip().lower() or "current"
+ return get_ssh_workspace_fs(profile_key, terminal)
+
+
+def _raise_fs_backend_error(exc: Exception) -> None:
+ from hermes_cli.ssh_workspace_fs import SshWorkspaceFsError
+
+ if not isinstance(exc, SshWorkspaceFsError):
+ raise exc
+ status = {
+ "EACCES": 403,
+ "ECONN": 503,
+ "EFBIG": 413,
+ "EINVAL": 400,
+ "EIO": 502,
+ "ENOENT": 404,
+ "ENOTREG": 400,
+ }.get(exc.code, 400)
+ detail = {
+ "EACCES": "File is not readable",
+ "ECONN": "SSH workspace is unavailable",
+ "EFBIG": "File too large",
+ "EINVAL": "Invalid path",
+ "EIO": "SSH workspace request failed",
+ "ENOENT": "File not found",
+ "ENOTREG": "Only regular files can be read",
+ }.get(exc.code, str(exc) or "Filesystem request failed")
+ raise HTTPException(status_code=status, detail=detail)
+
+
def _media_serve_roots() -> list[Path]:
"""Directories GET /api/media may read: where the agent and attach pipeline
actually write media (images, screenshots, cache). Stops an authenticated
@@ -647,7 +694,13 @@ _FS_LIST_ERRNO = (
@router.get("/api/fs/list")
-async def fs_list(path: str):
+async def fs_list(path: str, profile: Optional[str] = None):
+ backend = await asyncio.to_thread(_fs_backend, profile)
+ if backend is not None:
+ try:
+ return await asyncio.to_thread(backend.list_dir, path, _FS_READDIR_HIDDEN)
+ except Exception as exc:
+ _raise_fs_backend_error(exc)
target = _fs_path(path)
try:
entries = []
@@ -670,7 +723,28 @@ async def fs_list(path: str):
@router.get("/api/fs/read-text")
-async def fs_read_text(path: str):
+async def fs_read_text(path: str, profile: Optional[str] = None):
+ backend = await asyncio.to_thread(_fs_backend, profile)
+ if backend is not None:
+ try:
+ data, size, target = await asyncio.to_thread(
+ backend.read_bytes,
+ path,
+ max_bytes=_FS_TEXT_SOURCE_MAX_BYTES,
+ read_limit=_FS_TEXT_PREVIEW_MAX_BYTES,
+ )
+ except Exception as exc:
+ _raise_fs_backend_error(exc)
+ target_path = Path(target)
+ return {
+ "binary": _fs_looks_binary(data[:4096]),
+ "byteSize": size,
+ "language": _FS_PREVIEW_LANGUAGE_BY_EXT.get(target_path.suffix.lower(), "text"),
+ "mimeType": _fs_mime_type(target_path),
+ "path": target,
+ "text": data.decode("utf-8", errors="replace"),
+ "truncated": size > _FS_TEXT_PREVIEW_MAX_BYTES,
+ }
target, st = _fs_regular_file(_fs_path(path))
if st.st_size > _FS_TEXT_SOURCE_MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
@@ -689,7 +763,7 @@ async def fs_read_text(path: str):
@router.post("/api/fs/write-text")
-async def fs_write_text(payload: FsWriteText):
+async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
"""Overwrite (or create) a UTF-8 text file for the in-app spot editor.
Mirrors the Electron ``hermes:fs:writeText`` hardening: path validated by
@@ -698,8 +772,21 @@ async def fs_write_text(payload: FsWriteText):
temp file and ``os.replace``-d so a crash can't truncate the original.
Stale-on-disk detection is the client's job (re-read before save).
"""
- target = _fs_path(payload.path)
text = payload.content or ""
+ backend = await asyncio.to_thread(_fs_backend, profile)
+ if backend is not None:
+ try:
+ target, byte_size = await asyncio.to_thread(
+ backend.write_text,
+ payload.path,
+ text,
+ max_bytes=_FS_TEXT_WRITE_MAX_BYTES,
+ )
+ except Exception as exc:
+ _raise_fs_backend_error(exc)
+ return {"ok": True, "path": target, "byteSize": byte_size}
+
+ target = _fs_path(payload.path)
if len(text.encode("utf-8")) > _FS_TEXT_WRITE_MAX_BYTES:
raise HTTPException(status_code=413, detail="Content too large")
@@ -753,6 +840,16 @@ async def fs_read_data_url(
path: str, profile: Optional[str] = None, session_id: Optional[str] = None,
):
from hermes_cli.web_server import _FS_DATA_URL_MAX_BYTES
+ backend = await asyncio.to_thread(_fs_backend, profile)
+ if backend is not None:
+ try:
+ data, _size, target = await asyncio.to_thread(
+ backend.read_bytes, path, max_bytes=_FS_DATA_URL_MAX_BYTES
+ )
+ except Exception as exc:
+ _raise_fs_backend_error(exc)
+ encoded = base64.b64encode(data).decode("ascii")
+ return {"dataUrl": f"data:{_fs_mime_type(Path(target))};base64,{encoded}"}
target, st = _fs_regular_file(await _fs_download_path(path, profile, session_id))
if st.st_size > _FS_DATA_URL_MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
@@ -766,6 +863,21 @@ async def fs_read_data_url(
async def fs_download(
path: str, profile: Optional[str] = None, session_id: Optional[str] = None,
):
+ backend = await asyncio.to_thread(_fs_backend, profile)
+ if backend is not None:
+ try:
+ target, _size = await asyncio.to_thread(backend.inspect_file, path)
+ except Exception as exc:
+ _raise_fs_backend_error(exc)
+ target_path = Path(target)
+ if _is_sensitive_path(target_path):
+ raise HTTPException(status_code=403, detail="Access to sensitive files is not allowed")
+ filename = urllib.parse.quote(target_path.name)
+ return StreamingResponse(
+ backend.stream_file(target),
+ media_type=_fs_mime_type(target_path),
+ headers={"Content-Disposition": f"attachment; filename*=UTF-8''{filename}"},
+ )
target, _st = _fs_regular_file(await _fs_download_path(path, profile, session_id))
await asyncio.to_thread(_refuse_live_database, target)
return FileResponse(
@@ -777,7 +889,13 @@ async def fs_download(
@router.get("/api/fs/git-root")
-async def fs_git_root(path: str):
+async def fs_git_root(path: str, profile: Optional[str] = None):
+ backend = await asyncio.to_thread(_fs_backend, profile)
+ if backend is not None:
+ try:
+ return {"root": await asyncio.to_thread(backend.git_root, path)}
+ except Exception as exc:
+ _raise_fs_backend_error(exc)
target = _fs_path(path)
try:
st = target.stat()
@@ -788,6 +906,14 @@ async def fs_git_root(path: str):
@router.get("/api/fs/default-cwd")
-async def fs_default_cwd():
+async def fs_default_cwd(profile: Optional[str] = None):
+ backend = await asyncio.to_thread(_fs_backend, profile)
+ if backend is not None:
+ cwd = backend.cwd
+ try:
+ branch = await asyncio.to_thread(backend.git_branch, cwd)
+ except Exception as exc:
+ _raise_fs_backend_error(exc)
+ return {"cwd": cwd, "branch": branch}
cwd = _fs_default_cwd()
return {"cwd": cwd, "branch": _fs_git_branch(cwd)}
diff --git a/tests/hermes_cli/test_ssh_workspace_fs.py b/tests/hermes_cli/test_ssh_workspace_fs.py
new file mode 100644
index 00000000000..ec00b86045c
--- /dev/null
+++ b/tests/hermes_cli/test_ssh_workspace_fs.py
@@ -0,0 +1,152 @@
+import base64
+import io
+
+import pytest
+
+from hermes_cli import ssh_workspace_fs
+from hermes_cli.ssh_workspace_fs import SshWorkspaceFs, SshWorkspaceFsError
+
+
+class FakeEnv:
+ cwd = "/srv/repos"
+ timeout = 30
+ _remote_home = "/home/dev"
+
+ def __init__(self, results):
+ self.results = list(results)
+ self.calls = []
+
+ def execute(self, command, **kwargs):
+ self.calls.append((command, kwargs))
+ return self.results.pop(0)
+
+
+def _entry(name: str, path: str, kind: str) -> str:
+ return "\t".join(
+ (
+ base64.b64encode(name.encode()).decode(),
+ base64.b64encode(path.encode()).decode(),
+ kind,
+ )
+ )
+
+
+def test_ssh_workspace_fs_lists_and_reads_remote_paths():
+ env = FakeEnv(
+ [
+ {
+ "returncode": 0,
+ "output": "\n".join(
+ [
+ _entry("z.txt", "/srv/repos/z.txt", "f"),
+ _entry("src", "/srv/repos/src", "d"),
+ _entry("node_modules", "/srv/repos/node_modules", "d"),
+ ]
+ ),
+ },
+ {
+ "returncode": 0,
+ "output": "__HERMES_FS_SIZE__:5\naGVsbG8=\n",
+ },
+ ]
+ )
+ backend = SshWorkspaceFs(env)
+
+ listing = backend.list_dir("/srv/repos", {"node_modules"})
+ data, size, path = backend.read_bytes("README.md", max_bytes=100, read_limit=50)
+
+ assert listing == {
+ "entries": [
+ {"name": "src", "path": "/srv/repos/src", "isDirectory": True},
+ {"name": "z.txt", "path": "/srv/repos/z.txt", "isDirectory": False},
+ ]
+ }
+ assert (data, size, path) == (b"hello", 5, "/srv/repos/README.md")
+ assert 'p=/srv/repos' in env.calls[0][0]
+ assert 'p=/srv/repos/README.md' in env.calls[1][0]
+ assert 'if [ "$size" -gt 100 ]' in env.calls[1][0]
+ assert 'set -o pipefail; head -c 50 < "$p" | base64' in env.calls[1][0]
+
+
+def test_ssh_workspace_fs_maps_remote_size_failure():
+ env = FakeEnv([{"returncode": 47, "output": "__HERMES_FS_ERROR__:EFBIG\n"}])
+ backend = SshWorkspaceFs(env)
+
+ with pytest.raises(SshWorkspaceFsError, match="EFBIG") as raised:
+ backend.read_bytes("/srv/repos/large.bin", max_bytes=3)
+
+ assert raised.value.code == "EFBIG"
+
+
+def test_ssh_workspace_fs_inspects_resolved_file_before_streaming(monkeypatch):
+ resolved = "/srv/repos/.env"
+ encoded = base64.b64encode(resolved.encode()).decode()
+ env = FakeEnv(
+ [{"returncode": 0, "output": f"__HERMES_FS_TARGET__:{encoded}\n__HERMES_FS_SIZE__:6\n"}]
+ )
+ backend = SshWorkspaceFs(env)
+
+ target, size = backend.inspect_file("safe-link")
+
+ assert (target, size) == (resolved, 6)
+ assert "realpath \"$p\"" in env.calls[0][0]
+
+ class FakeProcess:
+ def __init__(self):
+ self.stdout = io.BytesIO(b"streamed")
+
+ def poll(self):
+ return 0
+
+ def wait(self):
+ return 0
+
+ process = FakeProcess()
+ env._build_ssh_command = lambda: ["ssh", "[email protected]"]
+ monkeypatch.setattr(ssh_workspace_fs.subprocess, "Popen", lambda *args, **kwargs: process)
+
+ assert b"".join(backend.stream_file(target, chunk_size=3)) == b"streamed"
+
+
+def test_ssh_workspace_factory_disables_agent_file_sync(monkeypatch):
+ created = []
+
+ class FakeSshEnvironment:
+ def __init__(self, **kwargs):
+ created.append(kwargs)
+ self.cwd = kwargs["cwd"]
+ self.timeout = kwargs["timeout"]
+ self._remote_home = "/home/dev"
+
+ def cleanup(self):
+ pass
+
+ monkeypatch.setattr(ssh_workspace_fs, "SSHEnvironment", FakeSshEnvironment)
+ monkeypatch.setattr(ssh_workspace_fs, "_BACKENDS", {})
+
+ backend = ssh_workspace_fs.get_ssh_workspace_fs(
+ "remote-dev",
+ {
+ "backend": "ssh",
+ "cwd": "/srv/repos",
+ "ssh_host": "ssh.example",
+ "ssh_user": "dev",
+ "ssh_port": 2222,
+ "ssh_key": "/keys/id_ed25519",
+ "timeout": 45,
+ },
+ )
+
+ assert backend is not None
+ assert backend.cwd == "/srv/repos"
+ assert created == [
+ {
+ "host": "ssh.example",
+ "user": "dev",
+ "cwd": "/srv/repos",
+ "timeout": 45,
+ "port": 2222,
+ "key_path": "/keys/id_ed25519",
+ "sync_files": False,
+ }
+ ]
diff --git a/tests/hermes_cli/test_web_server_fs.py b/tests/hermes_cli/test_web_server_fs.py
index 74656fe5171..d5f72a7f21e 100644
--- a/tests/hermes_cli/test_web_server_fs.py
+++ b/tests/hermes_cli/test_web_server_fs.py
@@ -1,9 +1,11 @@
import base64
+from contextlib import nullcontext
from pathlib import Path
import pytest
-from hermes_cli import web_server
+from hermes_cli import ssh_workspace_fs, web_server
+from hermes_cli.web_routers import files as file_routes
pytest.importorskip("starlette.testclient")
from starlette.testclient import TestClient
@@ -45,6 +47,192 @@ def test_fs_list_sorts_and_hides_noise(client, tmp_path):
assert all(entry["name"] not in {".git", "node_modules"} for entry in entries)
+def test_fs_routes_workspace_reads_to_ssh_backend(client, monkeypatch):
+ calls = []
+
+ class FakeSshFs:
+ cwd = "/srv/repos"
+
+ def list_dir(self, path, _hidden_names):
+ calls.append(("list", path))
+ return {
+ "entries": [
+ {
+ "name": "project",
+ "path": "/srv/repos/project",
+ "isDirectory": True,
+ }
+ ]
+ }
+
+ def git_branch(self, path):
+ calls.append(("branch", path))
+ return "main"
+
+ def git_root(self, path):
+ calls.append(("git-root", path))
+ return "/srv/repos/project"
+
+ def read_bytes(self, path, *, max_bytes, read_limit=None):
+ calls.append(("read", path, max_bytes, read_limit))
+ return b"hello", 5, path
+
+ def write_text(self, path, content, *, max_bytes):
+ calls.append(("write", path, content, max_bytes))
+ return path, len(content.encode("utf-8"))
+
+ def inspect_file(self, path):
+ calls.append(("inspect", path))
+ return path, 5
+
+ def stream_file(self, path):
+ calls.append(("stream", path))
+ yield b"hello"
+
+ backend = FakeSshFs()
+ monkeypatch.setattr(file_routes, "_fs_backend", lambda profile=None: backend)
+
+ listing = client.get(
+ "/api/fs/list",
+ params={"path": "/srv/repos", "profile": "remote-dev"},
+ )
+ default_cwd = client.get(
+ "/api/fs/default-cwd",
+ params={"profile": "remote-dev"},
+ )
+ read_text = client.get(
+ "/api/fs/read-text",
+ params={"path": "/srv/repos/project/README.md", "profile": "remote-dev"},
+ )
+ read_data = client.get(
+ "/api/fs/read-data-url",
+ params={"path": "/srv/repos/project/logo.png", "profile": "remote-dev"},
+ )
+ write_text = client.post(
+ "/api/fs/write-text",
+ params={"profile": "remote-dev"},
+ json={"path": "/srv/repos/project/README.md", "content": "updated"},
+ )
+ git_root = client.get(
+ "/api/fs/git-root",
+ params={"path": "/srv/repos/project/src", "profile": "remote-dev"},
+ )
+ download = client.get(
+ "/api/fs/download",
+ params={"path": "/srv/repos/project/report.txt", "profile": "remote-dev"},
+ )
+
+ assert listing.status_code == 200
+ assert listing.json() == {
+ "entries": [
+ {
+ "name": "project",
+ "path": "/srv/repos/project",
+ "isDirectory": True,
+ }
+ ]
+ }
+ assert default_cwd.status_code == 200
+ assert default_cwd.json() == {"cwd": "/srv/repos", "branch": "main"}
+ assert read_text.json()["text"] == "hello"
+ assert read_data.json()["dataUrl"] == "data:image/png;base64,aGVsbG8="
+ assert write_text.json() == {"ok": True, "path": "/srv/repos/project/README.md", "byteSize": 7}
+ assert git_root.json() == {"root": "/srv/repos/project"}
+ assert download.content == b"hello"
+ assert calls == [
+ ("list", "/srv/repos"),
+ ("branch", "/srv/repos"),
+ (
+ "read",
+ "/srv/repos/project/README.md",
+ file_routes._FS_TEXT_SOURCE_MAX_BYTES,
+ file_routes._FS_TEXT_PREVIEW_MAX_BYTES,
+ ),
+ ("read", "/srv/repos/project/logo.png", web_server._FS_DATA_URL_MAX_BYTES, None),
+ ("write", "/srv/repos/project/README.md", "updated", file_routes._FS_TEXT_WRITE_MAX_BYTES),
+ ("git-root", "/srv/repos/project/src"),
+ ("inspect", "/srv/repos/project/report.txt"),
+ ("stream", "/srv/repos/project/report.txt"),
+ ]
+
+
+def test_fs_backend_resolves_ssh_connection_from_profile_env(monkeypatch):
+ captured = {}
+ expected = object()
+ monkeypatch.setattr(file_routes, "_profile_scope", lambda _profile: nullcontext())
+ monkeypatch.setattr(
+ file_routes,
+ "load_config",
+ lambda: {"terminal": {"backend": "ssh", "cwd": "/srv/repos"}},
+ )
+ monkeypatch.setattr(
+ file_routes,
+ "load_env",
+ lambda: {
+ "TERMINAL_SSH_HOST": "ssh.example",
+ "TERMINAL_SSH_USER": "dev",
+ "TERMINAL_SSH_PORT": "2222",
+ },
+ )
+
+ def fake_factory(profile_key, terminal):
+ captured.update(profile_key=profile_key, terminal=terminal)
+ return expected
+
+ monkeypatch.setattr(ssh_workspace_fs, "get_ssh_workspace_fs", fake_factory)
+
+ assert file_routes._fs_backend("Remote-Dev") is expected
+ assert captured == {
+ "profile_key": "remote-dev",
+ "terminal": {
+ "backend": "ssh",
+ "cwd": "/srv/repos",
+ "ssh_host": "ssh.example",
+ "ssh_user": "dev",
+ "ssh_port": "2222",
+ },
+ }
+
+
+def test_fs_download_rejects_sensitive_resolved_ssh_path_before_streaming(client, monkeypatch):
+ class FakeSshFs:
+ def inspect_file(self, _path):
+ return "/srv/repos/.env", 8
+
+ def stream_file(self, _path):
+ pytest.fail("sensitive SSH files must not be streamed")
+
+ monkeypatch.setattr(file_routes, "_fs_backend", lambda profile=None: FakeSshFs())
+
+ response = client.get(
+ "/api/fs/download",
+ params={"path": "/srv/repos/safe-link", "profile": "remote-dev"},
+ )
+
+ assert response.status_code == 403
+
+
+def test_fs_download_streams_ssh_files_without_preview_cap(client, monkeypatch):
+ class FakeSshFs:
+ def inspect_file(self, _path):
+ return "/srv/repos/report.txt", 6
+
+ def stream_file(self, _path):
+ yield b"123"
+ yield b"456"
+
+ monkeypatch.setattr(file_routes, "_FS_TEXT_SOURCE_MAX_BYTES", 3)
+ monkeypatch.setattr(file_routes, "_fs_backend", lambda profile=None: FakeSshFs())
+
+ response = client.get(
+ "/api/fs/download",
+ params={"path": "/srv/repos/report.txt", "profile": "remote-dev"},
+ )
+
+ assert response.status_code == 200
+ assert response.content == b"123456"
+
+
def test_fs_read_data_url_rejects_over_cap(client, tmp_path, monkeypatch):
monkeypatch.setattr(web_server, "_FS_DATA_URL_MAX_BYTES", 3)
target = tmp_path / "image.png"
diff --git a/tests/tools/test_ssh_environment.py b/tests/tools/test_ssh_environment.py
index 30dae4ff27d..514186d78ca 100644
--- a/tests/tools/test_ssh_environment.py
+++ b/tests/tools/test_ssh_environment.py
@@ -226,6 +226,31 @@ class TestSSHPreflight:
assert env.host == "example.com"
assert env.user == "alice"
+ def test_ssh_environment_can_skip_agent_file_sync(self, monkeypatch):
+ monkeypatch.setattr(ssh_env.shutil, "which", lambda _name: "/usr/bin/ssh")
+ monkeypatch.setattr(ssh_env.SSHEnvironment, "_establish_connection", lambda self: None)
+ monkeypatch.setattr(ssh_env.SSHEnvironment, "_detect_remote_home", lambda self: "/home/alice")
+ monkeypatch.setattr(ssh_env.SSHEnvironment, "init_session", lambda self: None)
+ monkeypatch.setattr(
+ ssh_env.SSHEnvironment,
+ "_ensure_remote_dirs",
+ lambda self: pytest.fail("workspace browsing must not mutate the SSH target"),
+ )
+ monkeypatch.setattr(
+ ssh_env,
+ "FileSyncManager",
+ lambda **_kw: pytest.fail("workspace browsing must not start agent file sync"),
+ )
+
+ env = ssh_env.SSHEnvironment(
+ host="example.com",
+ user="alice",
+ sync_files=False,
+ )
+
+ assert env._sync_manager is None
+ env._before_execute()
+
@pytest.fixture
def _mock_ssh_runtime(monkeypatch, tmp_path):
diff --git a/tools/environments/ssh.py b/tools/environments/ssh.py
index a79dafb937c..3a9f2907f08 100644
--- a/tools/environments/ssh.py
+++ b/tools/environments/ssh.py
@@ -57,7 +57,7 @@ class SSHEnvironment(BaseEnvironment):
def __init__(self, host: str, user: str, cwd: str = "~",
timeout: int = 60, port: int = 22, key_path: str = "",
- probe_only: bool = False):
+ probe_only: bool = False, sync_files: bool = True):
super().__init__(cwd=cwd, timeout=timeout)
self.host, self.user, self.port, self.key_path = host, user, port, key_path
self.control_dir = Path(tempfile.gettempdir()) / "hermes-ssh"
@@ -78,12 +78,14 @@ class SSHEnvironment(BaseEnvironment):
return
self._remote_home_detected = False
self._remote_home = self._detect_remote_home()
- self._ensure_remote_dirs()
- self._sync_manager = FileSyncManager(
- get_files_fn=lambda: iter_sync_files(f"{self._remote_home}/.hermes"),
- upload_fn=self._scp_upload, delete_fn=self._ssh_delete,
- bulk_upload_fn=self._ssh_bulk_upload, bulk_download_fn=self._ssh_bulk_download)
- self._sync_manager.sync(force=True)
+ self._sync_manager = None
+ if sync_files:
+ self._ensure_remote_dirs()
+ self._sync_manager = FileSyncManager(
+ get_files_fn=lambda: iter_sync_files(f"{self._remote_home}/.hermes"),
+ upload_fn=self._scp_upload, delete_fn=self._ssh_delete,
+ bulk_upload_fn=self._ssh_bulk_upload, bulk_download_fn=self._ssh_bulk_download)
+ self._sync_manager.sync(force=True)
self.init_session()
def _control_socket_for(self, send_env: tuple[str, ...]) -> Path: