Skip to content

The agent that grows with you

fix(ssh): forward skill/config env passthrough over SendEnv (#14091)

sgaofen7456081d2a64
diff --git a/tests/tools/test_ssh_environment.py b/tests/tools/test_ssh_environment.py
index 7cc769795f7..25aac71b112 100644
--- a/tests/tools/test_ssh_environment.py
+++ b/tests/tools/test_ssh_environment.py
@@ -76,6 +76,53 @@ class TestBuildSSHCommand:
env = SSHEnvironment(host="h", user="u")
assert env._build_ssh_command()[-1] == "u@h"
+ def _bare_env(self):
+ env = SSHEnvironment.__new__(SSHEnvironment)
+ env.control_socket, env.host, env.user, env.port, env.key_path = "/tmp/hermes-ssh-test.sock", "h", "u", 22, ""
+ return env
+
+ def _capture_run_bash(self, monkeypatch, env, cmd="echo ok"):
+ captured = {}
+
+ def _fake_popen(cmd, stdin_data=None, **kwargs):
+ captured["cmd"], captured["env"] = cmd, kwargs.get("env")
+ return MagicMock()
+
+ monkeypatch.setattr(ssh_env, "_popen_bash", _fake_popen)
+ env._run_bash(cmd)
+ return captured
+
+ def test_run_bash_forwards_passthrough_by_sendenv_never_in_remote_argv(self, monkeypatch):
+ """#14091: allowlisted names travel as ``-o SendEnv=NAME`` with values only in the ssh client env;
+ provider credentials on the allowlist stay behind; a .env value fills an unset shell var."""
+ import tools.env_passthrough as env_passthrough
+
+ env = self._bare_env()
+ monkeypatch.setenv("NEXTCLOUD_URL", "https://next.example")
+ monkeypatch.delenv("NEXTCLOUD_PASS", raising=False)
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-must-not-forward")
+ monkeypatch.setattr(env_passthrough, "get_all_passthrough",
+ lambda: frozenset({"NEXTCLOUD_URL", "NEXTCLOUD_PASS", "OPENAI_API_KEY"}))
+ monkeypatch.setattr(ssh_env, "_load_hermes_env_vars", lambda: {"NEXTCLOUD_PASS": "from-dotenv"})
+
+ captured = self._capture_run_bash(monkeypatch, env)
+
+ sent = {a.split("=", 1)[1] for a in captured["cmd"] if a.startswith("SendEnv=")}
+ assert sent == {"NEXTCLOUD_URL", "NEXTCLOUD_PASS"}
+ assert captured["env"]["NEXTCLOUD_URL"] == "https://next.example"
+ assert captured["env"]["NEXTCLOUD_PASS"] == "from-dotenv"
+ remote_text = " ".join(captured["cmd"])
+ assert "https://next.example" not in remote_text and "from-dotenv" not in remote_text
+ assert "sk-must-not-forward" not in remote_text
+
+ def test_run_bash_without_passthrough_inherits_env_unchanged(self, monkeypatch):
+ import tools.env_passthrough as env_passthrough
+
+ monkeypatch.setattr(env_passthrough, "get_all_passthrough", lambda: frozenset())
+ captured = self._capture_run_bash(monkeypatch, self._bare_env())
+ assert not any(a.startswith("SendEnv=") for a in captured["cmd"])
+ assert captured["env"] is None
+
class TestControlSocketPath:
"""Regression tests for issue #11840.
@@ -250,3 +297,4 @@ class TestPersistentSSH:
assert len(lines) == 1000
assert lines[0] == "1"
assert lines[-1] == "1000"
+
diff --git a/tools/environments/ssh.py b/tools/environments/ssh.py
index f773005c1ab..b967896b7b9 100644
--- a/tools/environments/ssh.py
+++ b/tools/environments/ssh.py
@@ -9,12 +9,13 @@ import shutil
import subprocess
import tempfile
from pathlib import Path
+from typing import Iterable
from tools.environments.base import BaseEnvironment, EnvironmentConnectionError
from tools.environments.base_output import _popen_bash
from tools.environments.file_sync import (
FileSyncManager, iter_sync_files, quoted_mkdir_command, quoted_rm_command, unique_parent_dirs)
-from tools.environments.remote_common import bash_argv, run_capture
+from tools.environments.remote_common import bash_argv, load_hermes_env_vars, resolve_passthrough_env, run_capture
logger = logging.getLogger(__name__)
@@ -23,6 +24,9 @@ logger = logging.getLogger(__name__)
# Skip multiplexing there; each command pays a fresh connection but the backend works. See #73927.
_SSH_MULTIPLEX = os.name != "nt"
+# Module-level binding: tests patch ``ssh._load_hermes_env_vars`` to fake the .env file.
+_load_hermes_env_vars = load_hermes_env_vars
+
def _ensure_ssh_available() -> None:
"""Fail fast with a clear error when the SSH client is unavailable."""
@@ -45,6 +49,10 @@ class SSHEnvironment(BaseEnvironment):
stdout markers. Uses SSH ControlMaster for connection reuse.
"""
+ # Passthrough values are re-forwarded on every command (see _run_bash), so like docker/local
+ # they stay out of the remote snapshot under multiplex.
+ _profile_scoped_passthrough = True
+
def __init__(self, host: str, user: str, cwd: str = "~",
timeout: int = 60, port: int = 22, key_path: str = ""):
super().__init__(cwd=cwd, timeout=timeout)
@@ -67,17 +75,38 @@ class SSHEnvironment(BaseEnvironment):
self._sync_manager.sync(force=True)
self.init_session()
+ def _control_socket_for(self, send_env: tuple[str, ...]) -> Path:
+ """One ControlMaster per SendEnv name-set, beside the plain target socket: a mux master only
+ relays the env names it was itself started with and silently drops the rest, so a passthrough
+ command must ride a master that knows its names. scp/sync/probes keep the plain socket."""
+ plain = Path(self.control_socket)
+ if not send_env:
+ return plain
+ # <target-id[:8]><names-hash[:8]>.sock: same length as the plain socket (macOS's 104-byte
+ # sun_path cap) and prefix-globbable so cleanup() finds every sibling without extra state.
+ digest = hashlib.sha256(" ".join(send_env).encode()).hexdigest()[:8]
+ return plain.with_name(f"{plain.stem[:8]}{digest}.sock")
+
+ def _control_sockets(self) -> list[Path]:
+ """The plain socket plus every SendEnv-set sibling (shared 8-char target prefix)."""
+ plain = Path(self.control_socket)
+ siblings = sorted(plain.parent.glob(f"{plain.stem[:8]}*.sock")) if plain.parent.is_dir() else []
+ return [plain, *(s for s in siblings if s != plain)]
+
def _target_flags(self, port_flag: str) -> list:
"""Port/key flags shared by ssh (``-p``) and scp (``-P``)."""
flags = [port_flag, str(self.port)] if self.port != 22 else []
return flags + (["-i", self.key_path] if self.key_path else [])
- def _build_ssh_command(self, extra_args: list | None = None) -> list:
+ def _build_ssh_command(self, extra_args: list | None = None, send_env: Iterable[str] = ()) -> list:
+ send_env = tuple(sorted(send_env))
cmd = ["ssh"]
if _SSH_MULTIPLEX:
- cmd.extend(["-o", f"ControlPath={self.control_socket}",
+ cmd.extend(["-o", f"ControlPath={self._control_socket_for(send_env)}",
"-o", "ControlMaster=auto", "-o", "ControlPersist=300"])
cmd.extend(["-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=accept-new", "-o", "ConnectTimeout=10"])
+ # Names only; values ride the ssh client's own environment (never the remote command text).
+ cmd.extend(arg for name in send_env for arg in ("-o", f"SendEnv={name}"))
cmd.extend(self._target_flags("-p"))
cmd.extend(extra_args or [])
cmd.append(f"{self.user}@{self.host}")
@@ -221,15 +250,26 @@ class SSHEnvironment(BaseEnvironment):
def _run_bash(self, cmd_string: str, *, login: bool = False, timeout: int = 120,
stdin_data: str | None = None) -> subprocess.Popen:
- return _popen_bash(self._build_ssh_command() + bash_argv(shlex.quote(cmd_string), login), stdin_data)
+ """Forward the passthrough allowlist (skill ``required_environment_variables`` +
+ ``terminal.env_passthrough``) the way docker does: ``SendEnv`` carries the names, the ssh
+ client's env carries the values, so secrets never enter the remote ``bash -c`` argv. The
+ remote sshd must ``AcceptEnv`` them (#14091). Profile-scoped names missing from the active
+ scope are unset remotely so a shared host cannot serve another profile's value."""
+ values, unset_names = resolve_passthrough_env(hermes_env_loader=lambda: _load_hermes_env_vars())
+ if unset_names:
+ cmd_string = f"unset {' '.join(shlex.quote(n) for n in sorted(unset_names))} 2>/dev/null || true\n{cmd_string}"
+ cmd = self._build_ssh_command(send_env=sorted(values)) + bash_argv(shlex.quote(cmd_string), login)
+ return _popen_bash(cmd, stdin_data, env={**os.environ, **values}) if values else _popen_bash(cmd, stdin_data)
def cleanup(self):
if self._sync_manager:
logger.info("SSH: syncing files from sandbox...")
self._sync_manager.sync_back()
- if self.control_socket.exists():
+ for socket in self._control_sockets():
+ if not socket.exists():
+ continue
with contextlib.suppress(OSError, subprocess.SubprocessError):
- cmd = ["ssh", "-o", f"ControlPath={self.control_socket}", "-O", "exit", f"{self.user}@{self.host}"]
+ cmd = ["ssh", "-o", f"ControlPath={socket}", "-O", "exit", f"{self.user}@{self.host}"]
subprocess.run(cmd, capture_output=True, timeout=5, stdin=subprocess.DEVNULL)
with contextlib.suppress(OSError):
- self.control_socket.unlink()
+ socket.unlink()