Skip to content

The agent that grows with you

fix(update): the ZIP journal writer never writes through a pre-existing temp link (review F31, F14)

Tekniume19836a37b53
diff --git a/hermes_cli/_early_recovery.py b/hermes_cli/_early_recovery.py
index a85f0f5e735..a5f67e28813 100644
--- a/hermes_cli/_early_recovery.py
+++ b/hermes_cli/_early_recovery.py
@@ -681,8 +681,19 @@ def write_zip_swap_journal(root: Path, phase: str, entries: list) -> None:
journal = Path(root) / ZIP_SWAP_JOURNAL
tmp = journal.with_name(journal.name + ".tmp")
- tmp.write_text(json.dumps({"pid": os.getpid(), "phase": phase, "entries": entries}), encoding="utf-8")
- os.replace(tmp, journal)
+ # A fresh inode every time: writing into a pre-existing temp would follow its symlink or hardlink
+ # onto another file (.env). fsync before the rename: an empty journal over a mixed tree is no record.
+ tmp.unlink(missing_ok=True)
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o644)
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(json.dumps({"pid": os.getpid(), "phase": phase, "entries": entries}))
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp, journal)
+ except BaseException:
+ tmp.unlink(missing_ok=True)
+ raise
def _drop_path(path: Path) -> None:
diff --git a/tests/hermes_cli/test_early_recovery.py b/tests/hermes_cli/test_early_recovery.py
index b7943cf03de..d33cc24a4da 100644
--- a/tests/hermes_cli/test_early_recovery.py
+++ b/tests/hermes_cli/test_early_recovery.py
@@ -190,11 +190,22 @@ def _project(tmp_path: Path, *, pyproject: bool = True) -> Path:
return root
-
-
-
-
-
-
-
-
[email protected]("link", ["hardlink", "symlink"])
+def test_zip_journal_writer_never_writes_through_a_preexisting_temp(tmp_path, link):
+ """A temp left at the journal's fixed temp name as a link must not carry the journal into its target."""
+ root = tmp_path / "install"
+ root.mkdir()
+ secret = root / ".env"
+ secret.write_text("API_KEY=keep\n", encoding="utf-8")
+ tmp = root / (er.ZIP_SWAP_JOURNAL + ".tmp")
+ if link == "hardlink":
+ os.link(secret, tmp)
+ else:
+ try:
+ tmp.symlink_to(secret)
+ except OSError:
+ pytest.skip("symlinks need privileges here")
+ er.write_zip_swap_journal(root, "staging", [["a.py", True]])
+ assert secret.read_text(encoding="utf-8") == "API_KEY=keep\n"
+ journal = root / er.ZIP_SWAP_JOURNAL
+ assert not journal.is_symlink() and '"phase": "staging"' in journal.read_text(encoding="utf-8")