diff --git a/CHANGELOG.md b/CHANGELOG.md index fd88d27..dc6047b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +**`reuse_connection` per-server option (default `true`).** Setting `reuse_connection = false` on a `[servers.*]` block makes every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server open a brand-new SSH connection and close it, waiting for the close, right after the operation — on success or error — without ever storing it in the connection pool. It governs only operations run on that host itself: a jump host used as a tunnel is still reached through the shared pool and stays cached (tunnels use direct-tcpip channels, not exec channels). This is needed for Windows OpenSSH hosts that run a `ForceCommand` wrapper: Windows OpenSSH hands every exec channel after the first on one connection the first channel's `SSH_ORIGINAL_COMMAND`, so with a cached connection every command after the first returned the first command's output. The key must be a TOML boolean; a non-boolean value is rejected at load. With the default `true`, behaviour is unchanged. + ## [0.9.3] - 2026-12-01 > **Why 0.9.3 and not 0.10.0:** nothing here makes a configuration that started on 0.9.2 refuse to start. The runtime dependency changes are lockfile-only patches (`opentelemetry-api`, `pydantic`); the only new declared floor is a uv constraint, and the container image's interpreter move adds no configuration surface. diff --git a/README.md b/README.md index 4978089..aadd43c 100644 --- a/README.md +++ b/README.md @@ -353,6 +353,15 @@ Note two things about the timeouts, because the names invite confusion: Per-server overrides (`hostname`, `port`, `user`, `identity_file`, `jump_host`, `default_dir`, `timeout`) take precedence over `~/.ssh/config`. See [config/servers.example.toml](https://github.com/blackaxgit/ssh-mcp/blob/main/config/servers.example.toml) for the annotated reference. +`reuse_connection` (boolean, default `true`) controls connection caching for one server. With `reuse_connection = false`, every `execute`, `execute_on_group`, `upload_file` and `download_file` operation on that server opens a brand-new SSH connection and closes it as soon as the operation finishes (success or error); nothing is cached, so each call pays a full connect and handshake. The setting governs only operations run on that host itself: a jump host used as a tunnel is always reached through the shared connection pool and stays cached whatever its own `reuse_connection` says (tunnels use direct-tcpip channels, not exec channels, so the Windows issue below does not apply to them). Set it to `false` on **Windows hosts whose `sshd` uses a `ForceCommand` wrapper**: Windows OpenSSH gives every exec channel after the first on one SSH connection the *first* channel's `SSH_ORIGINAL_COMMAND`, so over a cached connection every command after the first would silently return the first command's output. Linux and MikroTik hosts are unaffected and should keep the default. + +```toml +[servers.win-app-01] +description = "Windows app server behind a ForceCommand wrapper" +groups = ["windows"] +reuse_connection = false +``` + Restrict config file permissions to your user: ```bash diff --git a/config/servers.example.toml b/config/servers.example.toml index c24ea4a..5d63bc2 100644 --- a/config/servers.example.toml +++ b/config/servers.example.toml @@ -97,6 +97,16 @@ jump_host = "bastion" default_dir = "/srv/app" timeout = 120 +# Server whose sshd forces a wrapper command (e.g. Windows OpenSSH with a +# ForceCommand script). Windows OpenSSH gives every exec channel after the +# first on one connection the FIRST channel's SSH_ORIGINAL_COMMAND, so the +# cached connection must not be reused: reuse_connection = false opens a new +# connection per execute/upload/download and closes it afterwards (default true). +[servers.win-app-01] +description = "Windows app server behind a ForceCommand wrapper" +groups = ["staging"] +reuse_connection = false + # Server with multiple groups and custom user [servers.monitor-01] description = "Monitoring: Prometheus, Grafana, Alertmanager (Ubuntu 22.04)" diff --git a/src/ssh_mcp/models.py b/src/ssh_mcp/models.py index b3206da..8370f9c 100644 --- a/src/ssh_mcp/models.py +++ b/src/ssh_mcp/models.py @@ -169,6 +169,13 @@ class ServerConfig: default_dir: Default working directory for commands timeout: Override command timeout for this server, in seconds (1..3600) + reuse_connection: Keep one cached SSH connection for this server and + reuse it across operations (default True). False opens a + brand-new connection for every execute / group execute / + upload / download and closes it right after, never caching it. + Needed for Windows OpenSSH forced-command wrappers, which hand + every exec channel after the first on one connection the FIRST + channel's ``SSH_ORIGINAL_COMMAND``. """ name: str @@ -181,6 +188,7 @@ class ServerConfig: jump_host: str | None = None default_dir: str | None = None timeout: int | None = Field(default=None, ge=1, le=3600) + reuse_connection: bool = Field(default=True, strict=True) @field_validator("groups", mode="before") @classmethod diff --git a/src/ssh_mcp/ssh.py b/src/ssh_mcp/ssh.py index e5896b6..77be7c1 100644 --- a/src/ssh_mcp/ssh.py +++ b/src/ssh_mcp/ssh.py @@ -1554,6 +1554,7 @@ async def _execute_impl( stays thin and the complex exit-path logic below does not need per-branch tracing glue. """ + fresh_conn: asyncssh.SSHClientConnection | None = None try: server = self.registry.get_server(server_name) @@ -1619,7 +1620,7 @@ async def _execute_impl( effective_command = f"cd {shlex.quote(cd_dir)} && {command}" # Get or create connection - conn = await self._get_connection(server_name) + conn, _, fresh_conn = await self._open_connection(server_name) # S10: conn.run() buffers the ENTIRE remote output before # max_output_bytes truncates it — the setting bounded the @@ -1875,6 +1876,10 @@ async def _execute_impl( error=f"Unexpected error: {redacted}", ) + finally: + if fresh_conn is not None: + await self._close_fresh_connection(server_name, fresh_conn) + async def execute_on_group( self, group_name: str, @@ -2169,9 +2174,12 @@ async def _upload_impl( ) ) local_fd: int | None = None + fresh_conn: asyncssh.SSHClientConnection | None = None try: try: - conn = await self._get_connection(server_name) + conn, connection_id, fresh_conn = await self._open_connection( + server_name + ) except KeyError as e: # N1: get_server() raises a raw KeyError for an unknown # server name, outside the documented ValueError/RuntimeError @@ -2183,7 +2191,7 @@ async def _upload_impl( # start/complete/failed lines all share the connection_id. ctx_tokens.update( structlog.contextvars.bind_contextvars( - connection_id=self._connection_ids.get(server_name, "unknown"), + connection_id=connection_id, ) ) self._audit.info("sftp.upload.start") @@ -2329,6 +2337,8 @@ async def _upload_impl( finally: if local_fd is not None: os.close(local_fd) + if fresh_conn is not None: + await self._close_fresh_connection(server_name, fresh_conn) structlog.contextvars.reset_contextvars(**ctx_tokens) async def download( @@ -2409,16 +2419,19 @@ async def _download_impl( # is created (below) so the cleanup unlink can prove IDENTITY, not # just path confinement — see _unlink_beneath's docstring. created_ino: tuple[int, int] | None = None + fresh_conn: asyncssh.SSHClientConnection | None = None try: try: - conn = await self._get_connection(server_name) + conn, connection_id, fresh_conn = await self._open_connection( + server_name + ) except KeyError as e: # N1: see _upload_impl — convert to the documented contract. raise ValueError(f"Server not found: {e}") from e ctx_tokens.update( structlog.contextvars.bind_contextvars( - connection_id=self._connection_ids.get(server_name, "unknown"), + connection_id=connection_id, ) ) self._audit.info("sftp.download.start") @@ -2593,6 +2606,8 @@ async def _download_impl( finally: if local_fd is not None: os.close(local_fd) + if fresh_conn is not None: + await self._close_fresh_connection(server_name, fresh_conn) structlog.contextvars.reset_contextvars(**ctx_tokens) async def close_all(self) -> None: @@ -2663,6 +2678,65 @@ async def close_all(self) -> None: os.close(self._transfer_root_fd) self._transfer_root_fd = None + async def _open_connection( + self, server_name: str + ) -> tuple[asyncssh.SSHClientConnection, str, asyncssh.SSHClientConnection | None]: + """Return a connection for one operation, honouring ``reuse_connection``. + + With ``reuse_connection=True`` (the default) this is exactly + ``_get_connection``: the cached connection is returned and the third + tuple element is ``None``. With ``reuse_connection=False`` a brand-new + connection is built via ``_create_connection``, is never stored in + ``_connections``, and is returned as the third element so the caller + can hand it to + ``_close_fresh_connection`` once the operation ends. No server lock + is held while the operation runs, same as the cached path. + + A jump host, if any, is still reached through ``_get_connection`` + (see ``_create_connection``), so its tunnel connection stays pooled + whatever its own ``reuse_connection`` says: tunnels use direct-tcpip + channels, not exec channels, so the forced-command problem does not + apply to them. + + Why: Windows OpenSSH hands every exec channel after the first on one + connection the FIRST channel's ``SSH_ORIGINAL_COMMAND``, so a + forced-command wrapper there must see one connection per command. + + Returns: + ``(connection, connection_id, fresh_connection_or_None)`` + + Raises: + KeyError: If server not found in registry + Various SSH exceptions on connection failure + """ + server = self.registry.get_server(server_name) + if server.reuse_connection: + conn = await self._get_connection(server_name) + return conn, self._connection_ids.get(server_name, "unknown"), None + + conn = await self._create_connection(server) + connection_id = _make_connection_id(server_name) + logger.info( + "Created one-shot connection to %s (id=%s)", + _safe_log_value(server_name), + connection_id, + ) + return conn, connection_id, conn + + async def _close_fresh_connection( + self, server_name: str, conn: asyncssh.SSHClientConnection + ) -> None: + """Close a one-shot connection and wait for the close to finish.""" + try: + conn.close() + await conn.wait_closed() + except Exception as e: # noqa: BLE001 - cleanup of a one-shot connection must never mask the operation's own result or error + logger.warning( + "Error closing one-shot connection to %s: %s", + _safe_log_value(server_name), + _safe_exc(e), + ) + async def _get_connection( self, server_name: str, _depth: int = 0 ) -> asyncssh.SSHClientConnection: diff --git a/tests/test_config.py b/tests/test_config.py index c50ca47..64462c7 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -434,3 +434,48 @@ def test_non_list_groups_rejected_not_coerced( def test_config_error_is_valueerror_subclass(self) -> None: """ConfigError must remain a ValueError subclass for backward compat.""" assert issubclass(ConfigError, ValueError) + + +class TestReuseConnectionKey: + """TOML parsing of the per-server ``reuse_connection`` key.""" + + _TEMPLATE = """ +[groups] +win = {{ description = "Windows" }} + +[servers.win1] +description = "Windows host" +groups = ["win"] +{extra} + +[servers.lin1] +description = "Linux host" +groups = ["win"] +""" + + def _load(self, tmp_path: Path, extra: str) -> ServerRegistry: + f = tmp_path / "reuse.toml" + f.write_text(self._TEMPLATE.format(extra=extra)) + return ServerRegistry(str(f)) + + def test_false_is_parsed_and_default_stays_true(self, tmp_path: Path) -> None: + registry = self._load(tmp_path, "reuse_connection = false") + + assert registry.get_server("win1").reuse_connection is False + assert registry.get_server("lin1").reuse_connection is True + + def test_omitted_defaults_to_true(self, tmp_path: Path) -> None: + registry = self._load(tmp_path, "") + + assert registry.get_server("win1").reuse_connection is True + + @pytest.mark.parametrize("raw", ['"false"', "0", "1", '"yes"']) + def test_non_bool_rejected_naming_key_and_server( + self, tmp_path: Path, raw: str + ) -> None: + with pytest.raises(ConfigError) as exc_info: + self._load(tmp_path, f"reuse_connection = {raw}") + + msg = str(exc_info.value) + assert "reuse_connection" in msg + assert "win1" in msg diff --git a/tests/test_models.py b/tests/test_models.py index 36dcaae..f327b83 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -297,3 +297,28 @@ def test_exec_result_with_stderr(self) -> None: assert result.stderr == "cat: missing.txt: No such file or directory" assert result.exit_code == 1 + + +class TestServerConfigReuseConnection: + """``reuse_connection`` toggles one-shot connections per operation.""" + + def test_defaults_to_true(self) -> None: + server = ServerConfig(name="web1", description="Web server 1") + + assert server.reuse_connection is True + + def test_accepts_false(self) -> None: + server = ServerConfig( + name="win1", description="Windows", reuse_connection=False + ) + + assert server.reuse_connection is False + + @pytest.mark.parametrize("bad_value", ["false", "yes", 0, 1, None]) + def test_rejects_non_bool(self, bad_value: object) -> None: + with pytest.raises(ValueError, match="reuse_connection"): + ServerConfig( + name="win1", + description="Windows", + reuse_connection=bad_value, # type: ignore[arg-type] + ) diff --git a/tests/test_ssh.py b/tests/test_ssh.py index cac0f85..5ef5d0f 100644 --- a/tests/test_ssh.py +++ b/tests/test_ssh.py @@ -4265,3 +4265,246 @@ async def _tracking_to_thread(func, /, *args, **kwargs): "asyncio.to_thread — Defect 3" ) assert (root / "dest2.bin").read_bytes() == b"hello" + + +class TestReuseConnection: + """``reuse_connection`` per-server option: cached vs one-shot connections.""" + + def _make_manager(self, tmp_path, *, transfer_root: bool = False) -> SSHManager: + config = tmp_path / "servers.toml" + config.write_text( + """ +[groups] +g = { description = "g" } + +[servers.cached] +description = "Cached connection (default)" +groups = ["g"] + +[servers.fresh1] +description = "One-shot connections" +groups = ["g"] +reuse_connection = false + +[servers.fresh2] +description = "One-shot connections" +groups = ["g"] +reuse_connection = false +""" + ) + settings = Settings() + if transfer_root: + root = tmp_path / "transfers" + root.mkdir(mode=0o700) + settings = Settings(transfer_root=str(root)) + return SSHManager(ServerRegistry(str(config)), settings) + + @staticmethod + def _make_conn(*, create_process_error: Exception | None = None): + from unittest.mock import AsyncMock, MagicMock + + process = TestAuditLogRedaction._make_mock_process(stdout_chunks=(b"ok",)) + conn = MagicMock() + if create_process_error is None: + conn.create_process = AsyncMock(return_value=process) + else: + conn.create_process = AsyncMock(side_effect=create_process_error) + conn.is_closed = MagicMock(return_value=False) + conn.close = MagicMock() + conn.wait_closed = AsyncMock(return_value=None) + return conn + + async def test_default_true_reuses_cached_connection(self, tmp_path) -> None: + from unittest.mock import AsyncMock, patch + + manager = self._make_manager(tmp_path) + conn = self._make_conn() + + with patch.object( + manager, "_create_connection", AsyncMock(return_value=conn) + ) as create: + first = await manager.execute("cached", "true") + second = await manager.execute("cached", "true") + + assert first.error is None and second.error is None + assert create.await_count == 1 + assert manager._connections["cached"] is conn + conn.close.assert_not_called() + + async def test_false_creates_and_closes_a_connection_per_execute( + self, tmp_path + ) -> None: + from unittest.mock import AsyncMock, patch + + manager = self._make_manager(tmp_path) + conns = [self._make_conn(), self._make_conn()] + + with patch.object( + manager, "_create_connection", AsyncMock(side_effect=conns) + ) as create: + first = await manager.execute("fresh1", "true") + second = await manager.execute("fresh1", "true") + + assert first.error is None and second.error is None + assert create.await_count == 2 + for conn in conns: + conn.create_process.assert_awaited_once() + conn.close.assert_called_once() + conn.wait_closed.assert_awaited_once() + assert "fresh1" not in manager._connections + assert "fresh1" not in manager._last_used + + async def test_false_closes_connection_when_command_raises(self, tmp_path) -> None: + from unittest.mock import AsyncMock, patch + + manager = self._make_manager(tmp_path) + conn = self._make_conn(create_process_error=RuntimeError("boom")) + + with patch.object(manager, "_create_connection", AsyncMock(return_value=conn)): + result = await manager.execute("fresh1", "true") + + assert result.error is not None and "boom" in result.error + conn.close.assert_called_once() + conn.wait_closed.assert_awaited_once() + assert "fresh1" not in manager._connections + + async def test_false_closes_connection_on_command_timeout(self, tmp_path) -> None: + from unittest.mock import AsyncMock, patch + + manager = self._make_manager(tmp_path) + conn = self._make_conn() + conn.create_process = AsyncMock( + return_value=TestAuditLogRedaction._make_mock_process(hang=True) + ) + + with patch.object(manager, "_create_connection", AsyncMock(return_value=conn)): + result = await manager.execute("fresh1", "true", timeout=0.05) + + assert result.error is not None and "timeout" in result.error.lower() + conn.close.assert_called_once() + conn.wait_closed.assert_awaited_once() + + async def test_close_failure_does_not_mask_result(self, tmp_path) -> None: + from unittest.mock import AsyncMock, patch + + manager = self._make_manager(tmp_path) + conn = self._make_conn() + conn.wait_closed = AsyncMock(side_effect=OSError("already gone")) + + with patch.object(manager, "_create_connection", AsyncMock(return_value=conn)): + result = await manager.execute("fresh1", "true") + + assert result.error is None + assert result.stdout == "ok" + + async def test_group_execute_uses_one_connection_per_server(self, tmp_path) -> None: + from unittest.mock import AsyncMock, patch + + manager = self._make_manager(tmp_path) + by_name: dict[str, object] = {} + + async def _create(server, _depth: int = 0): + conn = self._make_conn() + by_name[server.name] = conn + return conn + + with patch.object( + manager, "_create_connection", AsyncMock(side_effect=_create) + ): + results = await manager.execute_on_group("g", "true") + + assert len(results) == 3 + assert all(r.error is None for r in results) + fresh = [by_name["fresh1"], by_name["fresh2"]] + for conn in fresh: + conn.close.assert_called_once() # type: ignore[attr-defined] + conn.wait_closed.assert_awaited_once() # type: ignore[attr-defined] + assert set(manager._connections) == {"cached"} + + async def test_download_false_closes_connection_on_error(self, tmp_path) -> None: + from unittest.mock import AsyncMock, MagicMock, patch + + manager = self._make_manager(tmp_path, transfer_root=True) + conn = self._make_conn() + sftp = MagicMock() + sftp.stat = AsyncMock(side_effect=OSError("no such file")) + sftp_ctx = MagicMock() + sftp_ctx.__aenter__ = AsyncMock(return_value=sftp) + sftp_ctx.__aexit__ = AsyncMock(return_value=None) + conn.start_sftp_client = MagicMock(return_value=sftp_ctx) + + with patch.object(manager, "_create_connection", AsyncMock(return_value=conn)): + with pytest.raises(RuntimeError, match="Download failed"): + await manager.download("fresh1", "/tmp/x.bin", "x.bin") + + conn.close.assert_called_once() + conn.wait_closed.assert_awaited_once() + assert "fresh1" not in manager._connections + + async def test_upload_false_closes_connection_on_error(self, tmp_path) -> None: + from unittest.mock import AsyncMock, MagicMock, patch + + manager = self._make_manager(tmp_path, transfer_root=True) + (tmp_path / "transfers" / "up.bin").write_bytes(b"data") + conn = self._make_conn() + sftp_ctx = MagicMock() + sftp_ctx.__aenter__ = AsyncMock(side_effect=OSError("sftp unavailable")) + sftp_ctx.__aexit__ = AsyncMock(return_value=None) + conn.start_sftp_client = MagicMock(return_value=sftp_ctx) + + with patch.object(manager, "_create_connection", AsyncMock(return_value=conn)): + with pytest.raises(RuntimeError, match="Upload failed"): + await manager.upload("fresh1", "up.bin", "/tmp/up.bin") + + conn.close.assert_called_once() + conn.wait_closed.assert_awaited_once() + assert "fresh1" not in manager._connections + + async def test_false_target_behind_jump_host_keeps_jump_connection_cached( + self, tmp_path + ) -> None: + from unittest.mock import AsyncMock, patch + + config = tmp_path / "jump.toml" + config.write_text( + """ +[groups] +g = { description = "g" } + +[servers.bastion] +description = "Jump host" +groups = ["g"] + +[servers.target] +description = "One-shot target behind the bastion" +groups = ["g"] +jump_host = "bastion" +reuse_connection = false +""" + ) + manager = SSHManager(ServerRegistry(str(config)), Settings()) + jump_conn = self._make_conn() + target_conn = self._make_conn() + + async def _connect(host, **kwargs): + return target_conn if "tunnel" in kwargs else jump_conn + + get_connection = AsyncMock(wraps=manager._get_connection) + with ( + patch( + "ssh_mcp.ssh.asyncssh.connect", AsyncMock(side_effect=_connect) + ) as connect, + patch.object(manager, "_get_connection", get_connection), + ): + result = await manager.execute("target", "true") + + assert result.error is None + # The jump host is reached through the pool, at depth 1... + get_connection.assert_awaited_once_with("bastion", 1) + assert connect.await_args_list[-1].kwargs["tunnel"] is jump_conn + assert manager._connections == {"bastion": jump_conn} + # ...and only the one-shot target connection is closed. + target_conn.close.assert_called_once() + target_conn.wait_closed.assert_awaited_once() + jump_conn.close.assert_not_called() + jump_conn.wait_closed.assert_not_awaited()