From 4eb1573a88dd4307b8b2265408feba2f1a45e00b Mon Sep 17 00:00:00 2001 From: leddele <202502799+leddele@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:34:24 +0800 Subject: [PATCH] fix(ssh): use POSIX shell quoting for MSYS/Cygwin ProxyCommand on Windows --- docs/06_ssh_access.md | 8 +++-- src/colab_cli/commands/ssh.py | 33 +++++++++++------- tests/test_windows_ssh.py | 66 +++++++++++++++++++++++++---------- 3 files changed, 74 insertions(+), 33 deletions(-) diff --git a/docs/06_ssh_access.md b/docs/06_ssh_access.md index b659c5ab..6f02c5eb 100644 --- a/docs/06_ssh_access.md +++ b/docs/06_ssh_access.md @@ -1,5 +1,6 @@ --- log: +2026-12-03: Fixed `ProxyCommand` shell quoting under Git for Windows' MSYS/Cygwin `ssh`: `_proxy_command` now uses `shlex.join` when `_is_msys_ssh()` detects `msys-2.0.dll`/`cygwin1.dll` next to `ssh.exe`, preventing bash expansion or splitting of shell metacharacters while keeping `subprocess.list2cmdline` for native Windows OpenSSH. Expanded `tests/test_windows_ssh.py` MSYS coverage to all literal-argument cases plus portable quoting tests. 2026-11-27: Fixed `colab ssh` under Git for Windows' MSYS `ssh` (`/usr/bin/ssh` in Git Bash): ProxyCommand path arguments now use forward slashes on Windows (bash stripped the backslashes, failing with `D:Projects...python.exe: not found`), and `UserKnownHostsFile` is `/dev/null` when `ssh.exe` is an MSYS/Cygwin build (it wrote the host key to a `./nul` file). Native Windows OpenSSH keeps `nul`. Verified live from Git Bash and PowerShell (OpenSSH_for_Windows 9.5), and `integration/repro_windows_ssh/test.py` passed. 2026-11-23: Updated `integration/repro_windows_ssh/test.py` to check cached OAuth2 credentials via the OS `keyring` (`KEYRING_SERVICE_NAME` / `KEYRING_USERNAME`) instead of the removed `TOKEN_CONFIG_PATH`, and added portable import and prerequisite-skip regression tests in `tests/test_windows_ssh.py`. 2026-11-09: `--identity/-i` now accepts either a `.pub` public key or a private key path: `_resolve_pubkey` reads the `.pub` file directly when present before falling back to `_pubkey_from_identity` (`ssh-keygen -y -f`), and `_ssh_base_args` strips `.pub` for `ssh -i` when the sibling private key exists on disk. @@ -201,9 +202,10 @@ preservation for spaces, quotes, shell punctuation, backslashes, Unicode, and identity paths. A separate test launches the real Windows OpenSSH client with a local stub ProxyCommand and verifies its argv, without contacting Colab. When Git for Windows is installed, the ProxyCommand is also run through its -`bash -c "exec ..."` (how MSYS `ssh` launches it) with interpreters under -paths with and without spaces. The null-device choice is checked for native -OpenSSH and for MSYS/Cygwin `ssh.exe` layouts. +`bash -c "exec ..."` (how MSYS `ssh` launches it) across the same literal +argument cases with interpreters under paths with and without spaces. Both +quoting and null-device choices are checked for native OpenSSH and for +MSYS/Cygwin `ssh.exe` layouts. Portable tests also check registration without SIGHUP, the local null device, and `integration/repro_windows_ssh/test.py` import and prerequisite skip paths across platforms. Existing POSIX shell quoting and teardown tests diff --git a/src/colab_cli/commands/ssh.py b/src/colab_cli/commands/ssh.py index cbf6a42b..cf641b8a 100644 --- a/src/colab_cli/commands/ssh.py +++ b/src/colab_cli/commands/ssh.py @@ -471,6 +471,25 @@ def stdin_to_ws(): return 0 +def _is_msys_ssh() -> bool: + """True when the ``ssh`` on PATH is an MSYS/Cygwin build. + + Git for Windows' ``/usr/bin/ssh`` ships ``msys-2.0.dll`` or ``cygwin1.dll`` + next to ``ssh.exe``, runs ``ProxyCommand`` through POSIX ``bash -c``, and + expects ``/dev/null`` instead of Windows' ``nul``. + """ + if sys.platform != "win32": + return False + ssh_path = shutil.which("ssh") + if not ssh_path: + return False + bin_dir = os.path.dirname(ssh_path) + return any( + os.path.exists(os.path.join(bin_dir, dll)) + for dll in ("msys-2.0.dll", "cygwin1.dll") + ) + + def _proxy_command(session: SessionState, identity: Optional[str], mode: str) -> str: """Builds the OpenSSH ProxyCommand that bridges this session's WebSocket. @@ -498,7 +517,7 @@ def path_arg(p: str) -> str: if identity: argv += ["--identity", path_arg(identity)] argv += ["--colab-internal-mode", mode] - if win: + if win and not _is_msys_ssh(): return subprocess.list2cmdline(argv) return shlex.join(argv) @@ -511,17 +530,7 @@ def _ssh_null_device() -> str: host key into ``./nul``. Those builds ship ``msys-2.0.dll`` or ``cygwin1.dll`` next to ``ssh.exe`` and understand ``/dev/null``. """ - if sys.platform != "win32": - return os.devnull - ssh_path = shutil.which("ssh") - if ssh_path: - bin_dir = os.path.dirname(ssh_path) - if any( - os.path.exists(os.path.join(bin_dir, dll)) - for dll in ("msys-2.0.dll", "cygwin1.dll") - ): - return "/dev/null" - return os.devnull + return "/dev/null" if _is_msys_ssh() else os.devnull def _ssh_base_args(proxy_command: str, identity: Optional[str]) -> list[str]: diff --git a/tests/test_windows_ssh.py b/tests/test_windows_ssh.py index 1f9b15a0..9694c0a2 100644 --- a/tests/test_windows_ssh.py +++ b/tests/test_windows_ssh.py @@ -46,25 +46,26 @@ def windows_python_nospace(tmp_path_factory): return str(path / "Scripts" / "python.exe") +_LITERAL_SESSION_NAMES = [ + "simple", + "with space", + "a'b", + 'a"b', + "$(echo test)", + "a;b", + "a&b", + "a\\b\\", + "\u6d4b\u8bd5", +] + + @pytest.mark.skipif(sys.platform != "win32", reason="requires CreateProcessW") -@pytest.mark.parametrize( - "name", - [ - "simple", - "with space", - "a'b", - 'a"b', - "$(echo test)", - "a;b", - "a&b", - "a\\b\\", - "\u6d4b\u8bd5", - ], -) +@pytest.mark.parametrize("name", _LITERAL_SESSION_NAMES) @pytest.mark.parametrize("identity", [None, "C:\\SSH keys\\id_ed25519"]) def test_proxy_command_launches_with_literal_arguments( tmp_path, windows_python, monkeypatch, name, identity ): + monkeypatch.setattr(ssh.shutil, "which", lambda _: None) # A real child process parses the command using Windows argument rules. package = tmp_path / "colab_cli" package.mkdir() @@ -103,7 +104,7 @@ def _git_bash() -> str | None: @pytest.mark.skipif( sys.platform != "win32" or not _git_bash(), reason="requires Git for Windows" ) -@pytest.mark.parametrize("name", ["simple", "with space"]) +@pytest.mark.parametrize("name", _LITERAL_SESSION_NAMES) @pytest.mark.parametrize("identity", [None, "C:\\SSH keys\\id_ed25519"]) @pytest.mark.parametrize("python_fixture", ["windows_python", "windows_python_nospace"]) def test_proxy_command_survives_msys_ssh_shell( @@ -111,20 +112,27 @@ def test_proxy_command_survives_msys_ssh_shell( ): """Git for Windows' ssh runs ProxyCommand as `bash -c "exec "`. - Backslash paths from list2cmdline are eaten as escapes by that shell, so - `colab ssh` from Git Bash failed with `D:Projects...python.exe: not found`. + POSIX shell quoting is required so paths and arguments containing shell + metacharacters are passed literally instead of being expanded or split by + bash. """ + msys_bin = tmp_path / "msys_bin" + msys_bin.mkdir() + (msys_bin / "ssh.exe").write_bytes(b"") + (msys_bin / "msys-2.0.dll").write_bytes(b"") package = tmp_path / "colab_cli" package.mkdir() (package / "__init__.py").write_text("", encoding="utf-8") (package / "cli.py").write_text( "import json, sys; print(json.dumps(sys.argv[1:]))", encoding="utf-8" ) + bash = _git_bash() + monkeypatch.setattr(ssh.shutil, "which", lambda _: str(msys_bin / "ssh.exe")) monkeypatch.setattr(ssh.sys, "executable", request.getfixturevalue(python_fixture)) command = ssh._proxy_command(SimpleNamespace(name=name), identity, "cmd") env = {**os.environ, "PYTHONPATH": str(tmp_path)} result = subprocess.run( - [_git_bash(), "-c", f"exec {command}"], + [bash, "-c", f"exec {command}"], cwd=tmp_path, env=env, capture_output=True, @@ -235,6 +243,28 @@ def test_native_windows_ssh_keeps_nul(tmp_path, monkeypatch): assert "UserKnownHostsFile=nul" in args +@pytest.mark.parametrize("dll", ["msys-2.0.dll", "cygwin1.dll"]) +def test_msys_ssh_proxy_command_uses_posix_quoting(tmp_path, monkeypatch, dll): + (tmp_path / "ssh.exe").write_bytes(b"") + (tmp_path / dll).write_bytes(b"") + monkeypatch.setattr(ssh.sys, "platform", "win32") + monkeypatch.setattr(ssh.sys, "executable", r"D:\Python with spaces\python.exe") + monkeypatch.setattr(ssh.shutil, "which", lambda _: str(tmp_path / "ssh.exe")) + command = ssh._proxy_command(SimpleNamespace(name="$(echo test);a&b"), None, "cmd") + assert "'$(echo test);a&b'" in command + assert "'D:/Python with spaces/python.exe'" in command + + +def test_native_windows_ssh_proxy_command_uses_list2cmdline(tmp_path, monkeypatch): + (tmp_path / "ssh.exe").write_bytes(b"") + monkeypatch.setattr(ssh.sys, "platform", "win32") + monkeypatch.setattr(ssh.sys, "executable", r"D:\Python with spaces\python.exe") + monkeypatch.setattr(ssh.shutil, "which", lambda _: str(tmp_path / "ssh.exe")) + command = ssh._proxy_command(SimpleNamespace(name="$(echo test)"), None, "cmd") + assert '"$(echo test)"' in command + assert '"D:/Python with spaces/python.exe"' in command + + def test_rm_handlers_register_available_signals(mocker): register = mocker.patch.object(ssh.signal, "signal") ssh._install_rm_signal_handlers(mocker.Mock())