From 05ca3ff3f32de9504688e58848434cf7165fbbdf Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 18:31:46 -0800 Subject: [PATCH 1/2] fix: handle file names that aren't valid UTF-8 asyncssh decodes SFTP names as strict UTF-8 by default, so listing a directory with a name that isn't valid UTF-8 failed with SFTPBadMessage("Unable to decode name"). path_errors now defaults to "surrogateescape": such names come back as str with surrogate escapes, the way os.listdir returns them, and encode back to the same bytes. Names that are valid UTF-8 decode as before, and a path_errors passed in sftp_client_kwargs still wins. cp_file and checksum send their commands as bytes, encoded with the same path_encoding and path_errors as the SFTP client. asyncssh encodes a str command as strict UTF-8, which failed for these names and named a different file when path_encoding isn't UTF-8. Their output is decoded with errors="replace", because failing to decode it strictly closes the SSH connection. Co-Authored-By: Claude Opus 5.5 --- sshfs/spec.py | 32 +++++++++++++++++---- tests/test_sshfs.py | 68 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 94 insertions(+), 6 deletions(-) diff --git a/sshfs/spec.py b/sshfs/spec.py index 6e196b2..e71226c 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -69,7 +69,7 @@ def __init__( sftp_client_kwargs: dict | None Options passed to `SSHClientConnection.start_sftp_client` (e.g. env, send_env, path_encoding, path_errors, - sftp_version). + sftp_version). path_errors defaults to "surrogateescape". Notes ----- @@ -77,10 +77,15 @@ def __init__( SSH connection. The host, username, and port in string URLs are ignored; operations use only the path on the connected server. + File names that aren't valid UTF-8 are returned as str with + surrogate escapes, the way ``os.listdir`` returns them, and such a + str names the same file when it is passed back. For a server whose + names use another encoding, set ``path_encoding``. + Bytes paths (and path-likes whose ``__fspath__`` returns bytes) are sent to the server unchanged: protocol prefixes are not stripped and trailing slashes are kept. With ``sftp_client_kwargs={"path_encoding": None}``, - paths must be bytes. + paths must be bytes, and only some methods support them. """ super().__init__(self, **kwargs) @@ -93,7 +98,15 @@ def __init__( ) _client_args = kwargs.copy() _client_args.setdefault("known_hosts", None) - sftp_client_kwargs = sftp_client_kwargs or {} + sftp_client_kwargs = { + "path_errors": "surrogateescape", + **(sftp_client_kwargs or {}), + } + # Shell commands encode paths the same way as the SFTP client + self._path_encoding = ( + sftp_client_kwargs.get("path_encoding") or "utf-8" + ) + self._path_errors = sftp_client_kwargs["path_errors"] self._stack = AsyncExitStack() self.active_executors = 0 @@ -291,7 +304,7 @@ async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) cmd = f"cp {_quote(lpath)} {_quote(rpath)}" - await self._execute(cmd) + await self._execute_with_paths(cmd) @wrap_exceptions async def _ls(self, path, detail=True, **kwargs): @@ -390,7 +403,7 @@ async def _checksum(self, path): raise ValueError(f"{system!r} doesn't support checksum operation") cmd = f"{command} {_quote(path)}" - result = await self._execute(cmd) + result = await self._execute_with_paths(cmd) parts = result.stdout.strip().split() assert len(parts) >= 1 @@ -416,6 +429,15 @@ async def _execute(self, *args, **kwargs): execute = sync_wrapper(_execute) + async def _execute_with_paths(self, command): + """Execute a shell command whose arguments are remote paths.""" + # asyncssh encodes a str command as strict UTF-8, which fails for + # names that aren't valid UTF-8 and differs from path_encoding. + command = command.encode(self._path_encoding, self._path_errors) + # The output can include those names, and failing to decode it + # strictly closes the SSH connection. + return await self._execute(command, errors="replace") + def _open(self, path, *args, **kwargs): path = self._strip_protocol(path) return SSHFile(self, path, *args, **kwargs) diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index 5899bc0..082cbbd 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -77,6 +77,19 @@ def fs_hard_queue(ssh_server, user="user"): ) +@pytest.fixture +def non_utf8_file(tmp_path): + # The mock server encodes SFTP names as strict UTF-8, so only the methods + # that run shell commands can be tested with names that aren't valid UTF-8 + path = os.fsencode(tmp_path) + b"/name-\xff" + try: + with open(path, "wb") as file: + file.write(b"data") + except OSError: + pytest.skip("the filesystem rejects names that aren't valid UTF-8") + return os.fsdecode(path) + + def strip_keys(info): for key in ["name", "time", "mtime", "atime"]: info.pop(key, None) @@ -130,13 +143,27 @@ def test_sftp_client_kwargs(ssh_server, tmp_path, user="user"): client_keys=[USERS[user]], sftp_client_kwargs={"sftp_version": 3}, ) - assert fs._pool.sftp_client_kwargs == {"sftp_version": 3} + assert fs._pool.sftp_client_kwargs == { + "path_errors": "surrogateescape", + "sftp_version": 3, + } file = posixpath.join(tmp_path, "sftp_client_kwargs_probe") fs.touch(file) assert fs.exists(file) +def test_sftp_client_kwargs_path_errors(ssh_server, user="user"): + fs = SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username=user, + client_keys=[USERS[user]], + sftp_client_kwargs={"path_errors": "strict"}, + ) + assert fs._pool.sftp_client_kwargs == {"path_errors": "strict"} + + def test_sftp_client_kwargs_path_encoding(ssh_server, tmp_path, user="user"): # path_encoding=None makes asyncssh deliver remote paths as raw # bytes instead of str, for servers with non-UTF-8 file names (#39). @@ -264,6 +291,20 @@ def test_cp_file_leading_dash(fs, tmp_path, monkeypatch): assert (tmp_path / "-r-copy").read_bytes() == b"data" +def test_cp_file_non_utf8_name(fs, non_utf8_file): + fs.cp_file(non_utf8_file, non_utf8_file + "-copy") + with open(non_utf8_file + "-copy", "rb") as file: + assert file.read() == b"data" + + +def test_cp_file_missing_non_utf8_name(fs, tmp_path): + path = str(tmp_path) + "/missing-\udcff" + with pytest.raises(FileNotFoundError): + fs.cp_file(path, path + "-copy") + # The error output must not close the connection + assert fs.ls(str(tmp_path)) == [] + + def test_rm(fs, remote_dir): fs.touch(remote_dir + "/a.txt") fs.rm(remote_dir + "/a.txt") @@ -304,6 +345,31 @@ def test_checksum_leading_dash(fs, tmp_path, monkeypatch, name): assert checksum == hashlib.md5(b"data").hexdigest() +def test_checksum_non_utf8_name(fs, non_utf8_file): + checksum = hashlib.md5(b"data").hexdigest() + assert fs.checksum(non_utf8_file) == checksum + + +def test_checksum_missing_non_utf8_name(fs, tmp_path): + with pytest.raises(FileNotFoundError): + fs.checksum(str(tmp_path) + "/missing-\udcff") + # The error output must not close the connection + assert fs.ls(str(tmp_path)) == [] + + +def test_checksum_path_encoding(ssh_server, non_utf8_file, user="user"): + fs = SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username=user, + client_keys=[USERS[user]], + sftp_client_kwargs={"path_encoding": "latin-1"}, + ) + # Latin-1 decodes the file name b"name-\xff" as "name-ÿ" + path = os.fsencode(non_utf8_file).decode("latin-1") + assert fs.checksum(path) == hashlib.md5(b"data").hexdigest() + + def test_ls(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "dir/") files = set() From 4778da6d932457958e6ab8df182b5f46a9297f52 Mon Sep 17 00:00:00 2001 From: Ivan Shcheklein Date: Sat, 28 Nov 2026 19:01:10 -0800 Subject: [PATCH 2/2] fix: encode each path before quoting it for the shell The command was quoted as str and then encoded with path_encoding. Some encodings, such as HZ and ISO-2022-JP, encode non-ASCII characters as ASCII bytes that include a quote, so a name could end the quoted argument and run the rest as a command. Each path is now encoded first and the bytes are quoted, with the program name and shell syntax kept as ASCII bytes. Co-Authored-By: Claude Opus 5.5 --- sshfs/spec.py | 33 +++++++++++++++++---------------- tests/test_sshfs.py | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 16 deletions(-) diff --git a/sshfs/spec.py b/sshfs/spec.py index e71226c..62ca757 100644 --- a/sshfs/spec.py +++ b/sshfs/spec.py @@ -1,6 +1,5 @@ import asyncio import posixpath -import shlex import stat import weakref from contextlib import AsyncExitStack, suppress @@ -35,11 +34,11 @@ def _quote(path): - """Quote a path for a POSIX shell as a command's file argument.""" + """Quote an encoded path as a shell command's file argument.""" # Without "./", commands read "-r" as an option and "-" as stdin - if path.startswith("-"): - path = "./" + path - return shlex.quote(path) + if path.startswith(b"-"): + path = b"./" + path + return b"'" + path.replace(b"'", b"'\\''") + b"'" class SSHFileSystem(AsyncFileSystem): @@ -303,8 +302,7 @@ async def _get_file( async def _cp_file(self, lpath, rpath, **kwargs): lpath = self._strip_protocol(lpath) rpath = self._strip_protocol(rpath) - cmd = f"cp {_quote(lpath)} {_quote(rpath)}" - await self._execute_with_paths(cmd) + await self._execute_with_paths(b"cp", lpath, rpath) @wrap_exceptions async def _ls(self, path, detail=True, **kwargs): @@ -394,16 +392,15 @@ async def _checksum(self, path): path = self._strip_protocol(path) system = await self._get_system() if system == "Linux": - command = "md5sum" + program = b"md5sum" part = 0 elif system == "Darwin": - command = "md5" + program = b"md5" part = -1 else: raise ValueError(f"{system!r} doesn't support checksum operation") - cmd = f"{command} {_quote(path)}" - result = await self._execute_with_paths(cmd) + result = await self._execute_with_paths(program, path) parts = result.stdout.strip().split() assert len(parts) >= 1 @@ -429,11 +426,15 @@ async def _execute(self, *args, **kwargs): execute = sync_wrapper(_execute) - async def _execute_with_paths(self, command): - """Execute a shell command whose arguments are remote paths.""" - # asyncssh encodes a str command as strict UTF-8, which fails for - # names that aren't valid UTF-8 and differs from path_encoding. - command = command.encode(self._path_encoding, self._path_errors) + async def _execute_with_paths(self, program, *paths): + """Run a program with remote paths as its arguments.""" + # The paths are encoded the same way as for the SFTP client, before + # quoting, since some encodings produce quote characters. asyncssh + # would encode a str command as strict UTF-8 instead. + paths = [ + p.encode(self._path_encoding, self._path_errors) for p in paths + ] + command = b" ".join([program, *map(_quote, paths)]) # The output can include those names, and failing to decode it # strictly closes the SSH connection. return await self._execute(command, errors="replace") diff --git a/tests/test_sshfs.py b/tests/test_sshfs.py index 082cbbd..1e3857d 100644 --- a/tests/test_sshfs.py +++ b/tests/test_sshfs.py @@ -370,6 +370,24 @@ def test_checksum_path_encoding(ssh_server, non_utf8_file, user="user"): assert fs.checksum(path) == hashlib.md5(b"data").hexdigest() +def test_checksum_path_encoding_quoting( + ssh_server, tmp_path, monkeypatch, user="user" +): + # HZ encodes "А" as b"~{'!~}", so quoting the path before encoding it + # would end the shell argument early and run the rest as a command + monkeypatch.chdir(tmp_path) + fs = SSHFileSystem( + host=ssh_server.host, + port=ssh_server.port, + username=user, + client_keys=[USERS[user]], + sftp_client_kwargs={"path_encoding": "hz"}, + ) + with pytest.raises(FileNotFoundError): + fs.checksum("А;touch injected;#") + assert not (tmp_path / "injected").exists() + + def test_ls(fs, remote_dir, plain_remote_dir): fs.mkdir(remote_dir + "dir/") files = set()