Skip to content

The agent that grows with you

fix(file_operations): reject unencodable surrogates early, hash with surrogateescape (#79178)

Theophilus Chinomonad6eda8d9c578
diff --git a/tests/tools/test_file_write_surrogate_roundtrip.py b/tests/tools/test_file_write_surrogate_roundtrip.py
index 52e36821c75..03d6e014b3a 100644
--- a/tests/tools/test_file_write_surrogate_roundtrip.py
+++ b/tests/tools/test_file_write_surrogate_roundtrip.py
@@ -3,8 +3,7 @@
These tests exercise the REAL `_pipe_stdin` writer thread against a real
subprocess — no mocks. They pin the round-trip byte contract (utf-8 +
surrogateescape is the inverse of the decode that produced the content) and
-the always-close / error-capture guarantees of the writer thread. Later
-tasks in this plan append propagation and write_file tests to this file.
+the always-close / error-capture guarantees of the writer thread.
"""
import shlex
import subprocess
@@ -89,6 +88,65 @@ def env(tmp_path):
return LocalEnvironment(cwd=str(tmp_path), timeout=15)
+def ops(env, tmp_path):
+ """ShellFileOperations wired to the real local environment."""
+ return ShellFileOperations(env, cwd=str(tmp_path))
+
+
+class TestWriteFileSurrogates:
+ def test_roundtrip_preserves_bytes_count_and_hash(self, ops, tmp_path):
+ p = tmp_path / "surrogate.bin"
+ res = ops.write_file(str(p), b"\xff\x00\xfe".decode("utf-8", "surrogateescape"))
+ assert res.error is None
+ assert res.bytes_written == 3
+ assert res.verified is True
+ assert p.read_bytes() == b"\xff\x00\xfe"
+ assert not list(tmp_path.glob(".hermes-tmp*"))
+
+ def test_roundtrip_mixed_normal_and_surrogate(self, ops, tmp_path):
+ content = "head\n" + b"\xff".decode("utf-8", "surrogateescape") + "\ntail\n"
+ p = tmp_path / "mixed.bin"
+ res = ops.write_file(str(p), content)
+ assert res.error is None
+ assert res.verified is True
+ assert p.read_bytes() == b"head\n\xff\ntail\n"
+
+ @pytest.mark.parametrize("bad", ["\ud800", "\udc7f", "\udd00"])
+ def test_unencodable_surrogate_rejected_before_write(self, ops, tmp_path, bad):
+ p = tmp_path / "reject.bin"
+ res = ops.write_file(str(p), bad)
+ assert res.error and "surrogate" in res.error
+ assert "NOT created or modified" in res.error
+ assert "timed out" not in res.error
+ assert not p.exists()
+
+ def test_rejected_write_leaves_existing_target_unchanged(self, ops, tmp_path):
+ p = tmp_path / "keep.bin"
+ p.write_bytes(b"precious original bytes")
+ res = ops.write_file(str(p), "\ud800")
+ assert res.error and "NOT created or modified" in res.error
+ assert p.read_bytes() == b"precious original bytes"
+
+ def test_patch_replace_funnel_rejects_surrogate_new_string(self, ops, tmp_path):
+ p = tmp_path / "patchme.txt"
+ p.write_text("old\n")
+ # \udc7f is OUTSIDE the surrogateescape round-trip range (U+DC80–U+DCFF)
+ # — unencodable even with surrogateescape — so write_file's early
+ # rejection must catch it through the patch funnel. (An in-range
+ # surrogate like \udcff legitimately round-trips, per the spec.)
+ res = ops.patch_replace(str(p), "old", "new" + "\udc7f")
+ assert res.error and "surrogate" in res.error
+ assert p.read_text() == "old\n"
+
+ def test_normal_content_verified(self, ops, tmp_path):
+ p = tmp_path / "normal.txt"
+ res = ops.write_file(str(p), "hello\nworld\n")
+ assert res.error is None
+ assert res.verified is True
+ assert p.read_bytes() == b"hello\nworld\n"
+
+
class TestStdinErrorPropagation:
def test_execute_surfaces_stdin_error_without_hanging(self, env):
t0 = time.monotonic()
@@ -100,6 +158,12 @@ class TestStdinErrorPropagation:
assert "stdin write failed" in result["output"]
assert elapsed < 5.0, f"stdin failure path hung for {elapsed:.1f}s"
+ def test_normal_path_result_has_no_stdin_error_key(self, env):
+ result = env.execute("echo hi")
+ assert "stdin_error" not in result
+ assert result["returncode"] == 0
+ assert "hi" in result["output"]
+
class TestExecStdinErrorMapping:
def test_exec_maps_stdin_error_to_failure(self):
diff --git a/tools/file_operations.py b/tools/file_operations.py
index 3a152106c51..0c139385e3d 100644
--- a/tools/file_operations.py
+++ b/tools/file_operations.py
@@ -1502,6 +1502,22 @@ class ShellFileOperations(FileOperations):
if denied:
return WriteResult(error=denied)
+ # Reject lone surrogates up front with a regex scan (no encode, no
+ # subprocess). surrogateescape-decoded content (U+DC80–U+DCFF)
+ # round-trips through the pipe fine, but surrogates outside that
+ # range cannot be encoded at all — and letting them reach the pipe
+ # would spawn a child that then hangs, or truncates the target via
+ # empty-stdin `cat`. Refuse synchronously before any subprocess.
+ m = re.search(r"[\ud800-\udc7f\udd00-\udfff]", content)
+ if m:
+ return WriteResult(
+ error=(
+ f"Refusing to write '{path}': content contains a lone "
+ f"surrogate character ({m.group(0)!r}) that cannot be "
+ "encoded as UTF-8. The file was NOT created or modified."
+ )
+ )
+
# ── Fail-closed pre-write syntax gate ───────────────────────────
# Validate the CANDIDATE content BEFORE any bytes touch disk —
# previously this only ran as a post-write lint *report* that the
@@ -1626,20 +1642,32 @@ class ShellFileOperations(FileOperations):
# the atomic swap doesn't silently widen or narrow permissions, and
# clean the temp up on any failure so we never leak a ``.hermes-tmp``
# turd next to the user's file.
+ # Encode once for byte count + sha256. surrogateescape is the exact
+ # inverse of the decode that may have produced this content, so these
+ # are the bytes the pipe transmits and the bytes on disk. The early
+ # rejection above guarantees this cannot raise; the try/except is
+ # defense for future callers that bypass it.
+ try:
+ content_bytes = content.encode("utf-8", "surrogateescape")
+ except UnicodeEncodeError as exc:
+ return WriteResult(
+ error=(
+ f"Refusing to write '{path}': content contains a lone "
+ f"surrogate character ({exc}) that cannot be encoded as "
+ "UTF-8. The file was NOT created or modified."
+ )
+ )
write_result = self._atomic_write(path, content)
if write_result.exit_code != 0:
return WriteResult(error=f"Failed to write file: {write_result.stdout}")
- # Get bytes written — compute from the content we just wrote
- # (len of the UTF-8 encoding matches wc -c) instead of spawning a
- # ``wc -c`` subprocess. ``surrogatepass`` matches the sha256
- # verification below: content that flowed through a surrogateescape
- # decode (backend output via patch_replace) may carry lone
- # surrogates a strict encode would reject. Encode ONCE and share
- # the bytes with the sha256 block — a second full encode of a
- # multi-MB file is measurable.
- content_bytes = content.encode('utf-8', 'surrogatepass')
+ # Bytes written — computed from the exact bytes we just wrote (len
+ # matches wc -c) instead of spawning a ``wc -c`` subprocess. The
+ # encode happened up front with surrogateescape — the inverse of the
+ # decode that produces surrogate content — so content_bytes == what
+ # rode stdin == what is on disk, and the sha256 below compares like
+ # with like.
bytes_written = len(content_bytes)
# Post-write content verification (cheap, one shell call): compare