Skip to content

The agent that grows with you

fix(windows): a recreated dir gets the elevated grant again

Tekniume336eaaca48e
diff --git a/hermes_dir_acl.py b/hermes_dir_acl.py
index 4d48a3a8c5a..b97da0e8e3e 100644
--- a/hermes_dir_acl.py
+++ b/hermes_dir_acl.py
@@ -313,9 +313,19 @@ def grant_tree_user_access(root: str | Path) -> tuple[int, list[Path], list[tupl
return granted, skipped, failed
-# Dirs this elevated process already granted: the grant reads and may rewrite a DACL, and the
-# callers (log handlers, lock acquires) re-enter on hot paths.
-_granted: set[Path] = set()
+# Dir OBJECTS this elevated process already granted, as ``(path, volume serial, file id)`` from
+# ``os.lstat`` (st_dev / st_ino are exactly those on Windows): the grant reads and may rewrite a
+# DACL, and the callers (log handlers, lock acquires) re-enter on hot paths. Keyed by identity, not
+# name: media release deletes a digest dir and the next capture recreates it at the same path.
+_granted: set[tuple[Path, int, int]] = set()
+
+
+def _identity(path: Path) -> tuple[Path, int, int] | None:
+ try:
+ st = os.lstat(path)
+ except OSError:
+ return None
+ return path, st.st_dev, st.st_ino
def make_user_dir(path: str | Path, mode: int = 0o777, *, parents: bool = False, exist_ok: bool = False) -> Path:
@@ -323,8 +333,8 @@ def make_user_dir(path: str | Path, mode: int = 0o777, *, parents: bool = False,
by the same user unelevated.
Off Windows or unelevated this is ``Path.mkdir`` and nothing else. Elevated, every directory
- this call created (missing parents included) and the leaf, even when it already existed (the
- repair case), get the user's inheriting full-control ACE once per process, except that a
+ this call created (missing parents included) is granted the user's inheriting full-control ACE,
+ and an existing leaf (the repair case) once per directory object per process, except that a
component that is a junction/symlink/reparse point stops the grants with one warning. An
existing leaf without ``exist_ok`` is still granted before the ``FileExistsError``."""
target = Path(path)
@@ -345,11 +355,13 @@ def make_user_dir(path: str | Path, mode: int = 0o777, *, parents: bool = False,
if target.is_dir() and not is_reparse_point(target):
_grant_dirs(target, [target])
raise
- _grant_dirs(target, list(reversed(created or [target])))
+ _grant_dirs(target, list(reversed(created or [target])), fresh=set(created))
return target
-def _grant_dirs(target: Path, to_grant: list[Path]) -> None:
+def _grant_dirs(target: Path, to_grant: list[Path], fresh: set[Path] = frozenset()) -> None:
+ """Grant *to_grant*; a dir in *fresh* (this call created it) is always granted, an existing
+ one once per verified object identity."""
# A junction/symlink planted at (or swapped in for) the leaf, a created component, or any
# existing ancestor inside the home: grant nothing, one warning (nothing past it is in the home).
for component in dict.fromkeys([*_components_below_home(target), *to_grant]):
@@ -357,8 +369,11 @@ def _grant_dirs(target: Path, to_grant: list[Path]) -> None:
_warn_refused(component, ReparsePointRefused("junction, symlink or other reparse point"))
return
for directory in to_grant:
- if directory not in _granted and grant_user_access(directory):
- _granted.add(directory)
+ key = _identity(directory)
+ if key is None or (directory not in fresh and key in _granted):
+ continue
+ if grant_user_access(directory):
+ _granted.add(key)
def unusable_dir_remedy(path: str | Path) -> str:
diff --git a/tests/test_hermes_dir_acl.py b/tests/test_hermes_dir_acl.py
index 0c677c306a4..05f83bb04f3 100644
--- a/tests/test_hermes_dir_acl.py
+++ b/tests/test_hermes_dir_acl.py
@@ -1,6 +1,7 @@
"""``make_user_dir`` contract off Windows and its grant selection (the Windows ACL effect itself is
proved by ``test_hermes_dir_acl_windows.py`` on Windows CI)."""
import os
+from pathlib import Path
import pytest
@@ -236,3 +237,47 @@ def test_icacls_fallback_still_grants_a_plain_subtree(tmp_path, monkeypatch):
monkeypatch.setattr(hermes_dir_acl.subprocess, "run", lambda argv, **_k: calls.append(argv))
hermes_dir_acl._grant_with_icacls(root, True, str(root))
assert [c[0] for c in calls] == ["icacls"] and "/L" in calls[0]
+
+
+def test_a_recreated_dir_is_granted_again(tmp_path, monkeypatch):
+ """Review-9 (c): the grant memo was keyed by pathname, so media release deleting a digest dir
+ and the next capture recreating it at the same path left the new dir without the grant."""
+ granted = []
+ monkeypatch.setattr(hermes_dir_acl.sys, "platform", "win32")
+ monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: True)
+ monkeypatch.setattr(hermes_dir_acl, "grant_user_access", lambda p: granted.append(p) or True)
+ monkeypatch.setattr(hermes_dir_acl, "_granted", set())
+ target = tmp_path / "native-inputs" / ("0" * 64)
+ hermes_dir_acl.make_user_dir(target, 0o700, parents=True, exist_ok=True)
+ hermes_dir_acl.make_user_dir(target, 0o700, exist_ok=True)
+ assert granted.count(target) == 1 # existing object: memoized
+ target.rmdir()
+ hermes_dir_acl.make_user_dir(target, 0o700, exist_ok=True)
+ assert granted.count(target) == 2, "the recreated directory never got the grant"
+
+
+def test_media_release_then_recapture_grants_the_recreated_digest_dir(tmp_path, monkeypatch):
+ """The production lifecycle behind (c): capture -> release_unheld_media -> capture again."""
+ from gateway import session_ingress_media as media
+ from hermes_state import SessionDB
+
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(hermes_dir_acl.sys, "platform", "win32")
+ monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: True)
+ monkeypatch.setattr(hermes_dir_acl, "_granted", set())
+ grants = []
+ monkeypatch.setattr(hermes_dir_acl, "_grant_with_pywin32", lambda path, *_a, **_k: grants.append(str(path)))
+ source = tmp_path / "sample.txt"
+ source.write_text("same attachment bytes")
+ db = SessionDB(db_path=home / "state.db")
+ try:
+ first = media.capture_native_media([source])
+ directory = str(Path(first[0]["path"]).parent)
+ assert media.release_unheld_media(db, first, retain_history=False) == 1
+ assert not Path(directory).exists()
+ assert media.capture_native_media([source]) == first
+ finally:
+ db.close()
+ assert grants.count(directory) == 2