Skip to content

The agent that grows with you

fix(update): ZIP staging creates its file copies exclusively and never writes through a planted link

Tekniumb034c8e578d4
diff --git a/hermes_cli/update_cmd_zip.py b/hermes_cli/update_cmd_zip.py
index f0a346552cc..a67d3a0339d 100644
--- a/hermes_cli/update_cmd_zip.py
+++ b/hermes_cli/update_cmd_zip.py
@@ -90,10 +90,38 @@ def _stage_replacement(src: str, dst: str) -> str:
_drop_path(Path(leftover))
if os.path.lexists(leftover):
raise OSError(f"could not remove the leftover {leftover}")
- (shutil.copytree if os.path.isdir(src) else shutil.copy2)(src, staging)
+ # Never through the reusable pathname: copy2 opens it following a symlink planted after the sweep
+ # (review Z2). copytree's own os.mkdir is exclusive and never follows; a file is created the same way.
+ if os.path.isdir(src):
+ shutil.copytree(src, staging)
+ else:
+ _copy_file_exclusive(src, staging)
return staging
+def _copy_file_exclusive(src: str, dst: str, *, sync: bool = False) -> None:
+ """``copy2`` that only ever creates ``dst``: O_CREAT|O_EXCL (+O_NOFOLLOW) fails on any entry there
+ (symlink, hardlink, file) instead of writing through it, and the bytes and mode go through the held
+ fd. Times are copied only where that can be done without following ``dst``."""
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_BINARY", 0)
+ st = os.stat(src)
+ fd = os.open(dst, flags, 0o600)
+ try:
+ with os.fdopen(fd, "wb") as out, open(src, "rb") as source:
+ shutil.copyfileobj(source, out, 1 << 20)
+ out.flush()
+ if os.chmod in os.supports_fd:
+ os.chmod(out.fileno(), st.st_mode & 0o7777)
+ if os.utime in os.supports_fd:
+ os.utime(out.fileno(), ns=(st.st_atime_ns, st.st_mtime_ns))
+ if sync:
+ os.fsync(out.fileno())
+ except BaseException:
+ with suppress(OSError): # our own half-written create: never leave it for the swap to install
+ os.remove(dst)
+ raise
+
+
def _discard_staged(staged) -> None:
"""Remove staging paths for never-committed entries; otherwise a phase-1 failure (disk exhaustion)
orphans up to a full second tree and the advised retry fails harder with less free space."""
@@ -123,9 +151,7 @@ def _file_backup(path: str, backup: str) -> None:
return
tmp = f"{backup}.tmp"
try:
- shutil.copy2(path, tmp)
- with open(tmp, "rb+") as handle:
- os.fsync(handle.fileno())
+ _copy_file_exclusive(path, tmp, sync=True) # never through a planted <backup>.tmp link (Z2)
os.replace(tmp, backup)
except OSError:
with suppress(OSError):
diff --git a/tests/hermes_cli/test_update_zip_completion.py b/tests/hermes_cli/test_update_zip_completion.py
index 8898cde5128..42fe31b6deb 100644
--- a/tests/hermes_cli/test_update_zip_completion.py
+++ b/tests/hermes_cli/test_update_zip_completion.py
@@ -358,8 +358,9 @@ def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, mo
target.rename(backup)
leftover = root / (entry + ".hermes-update-staging")
leftover.write_text("interrupted copy", encoding="utf-8")
- function = "copytree" if entry == "tools" else "copy2"
- original = getattr(shutil, function)
+ # The file copy is update_cmd_zip's exclusive create (review Z2), no longer shutil.copy2.
+ owner, function = (shutil, "copytree") if entry == "tools" else (update_cmd_zip, "_copy_file_exclusive")
+ original = getattr(owner, function)
def fail(src, dst, *args, **kwargs):
if str(dst) == str(leftover):
@@ -367,7 +368,7 @@ def test_zip_recovers_crashed_backup_before_failed_copy_and_retry(zip_update, mo
return original(src, dst, *args, **kwargs)
with monkeypatch.context() as fault:
- fault.setattr(shutil, function, fail)
+ fault.setattr(owner, function, fail)
with pytest.raises(SystemExit) as error:
update_cmd_zip._download_and_swap_zip("main", "local fixture")
assert error.value.code == 1
diff --git a/tests/hermes_cli/test_update_zip_two_phase.py b/tests/hermes_cli/test_update_zip_two_phase.py
index f1f93b787ae..d4cb0d0f39d 100644
--- a/tests/hermes_cli/test_update_zip_two_phase.py
+++ b/tests/hermes_cli/test_update_zip_two_phase.py
@@ -304,6 +304,48 @@ def test_staging_restores_a_dangling_symlink_backup_instead_of_deleting_it(tmp_p
assert not os.path.lexists(backup)
[email protected]("kind", ["file", "dir"])
+def test_a_symlink_planted_at_the_staging_path_after_the_sweep_is_never_written_through(tmp_path, monkeypatch, kind):
+ """_stage_replacement swept the fixed staging name, checked it was gone, then copy2'd to that same
+ path: a symlink planted in between carried the extracted bytes outside the install (review Z2).
+ The stage now fails closed on the planted entry; the external file keeps its bytes."""
+ live, new, outside = tmp_path / "live", tmp_path / "new", tmp_path / "outside"
+ for d in (live, new, outside):
+ d.mkdir()
+ victim = outside / ("sentinel.txt" if kind == "file" else "sentinel")
+ if kind == "file":
+ victim.write_text("SENTINEL")
+ (new / "alpha").write_text("NEW")
+ else:
+ victim.mkdir()
+ (new / "alpha").mkdir()
+ (new / "alpha" / "x.py").write_text("NEW")
+ (live / "alpha").write_text("OLD") if kind == "file" else (live / "alpha").mkdir()
+ staging = live / "alpha.hermes-update-staging"
+ real_isdir = os.path.isdir
+
+ def plant_then_isdir(path): # the barrier: after the sweep and its lexists check, before the copy
+ if str(path) == str(new / "alpha") and not os.path.lexists(staging):
+ try:
+ staging.symlink_to(victim)
+ except OSError:
+ pytest.skip("symlinks need privileges here")
+ return real_isdir(path)
+
+ monkeypatch.setattr(update_cmd_zip.os.path, "isdir", plant_then_isdir)
+ with pytest.raises(OSError):
+ update_cmd._stage_replacement(str(new / "alpha"), str(live / "alpha"))
+ monkeypatch.undo()
+ if kind == "file":
+ assert victim.read_text() == "SENTINEL"
+ else:
+ assert list(victim.iterdir()) == []
+ staging.unlink() # the planted link (only the link) goes; a healthy stage then proceeds
+ update_cmd._commit_staged_replacements([(update_cmd._stage_replacement(str(new / "alpha"), str(live / "alpha")),
+ str(live / "alpha"))])
+ assert (live / "alpha" if kind == "file" else live / "alpha" / "x.py").read_text() == "NEW"
+
+
def test_commit_failure_plus_discard_leaves_no_staging_litter(tmp_path, monkeypatch):
"""Phase-2 failure must not orphan staging copies for unswapped entries.