Skip to content

The agent that grows with you

fix(windows): elevated ACL grants never follow a junction or link out of the home

Tekniumb6cfdb1059a3
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index 80419ba6dd1..ca385ba4b24 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -5,9 +5,7 @@ still resolves/monkeypatches. Origin helpers are imported lazily per function (n
test patches on ``update_cmd`` stay effective).
"""
-import csv
import logging
-import re
from contextlib import suppress
import os
import subprocess
@@ -22,55 +20,37 @@ from datetime import UTC
# Log-record parity with the origin module.
logger = logging.getLogger("hermes_cli.update_cmd")
-_WINDOWS_SID = re.compile(r"S-\d+(?:-\d+)+\Z", re.IGNORECASE)
-
-
-def _windows_home_acl_grant_command(home: Path, sid: str) -> list[str]:
- """Grant the calling user inherited access to an elevated update's home tree."""
- return ["icacls", str(home), "/grant", f"*{sid}:(OI)(CI)F", "/T", "/C", "/Q"]
-
-
-def _current_windows_user_sid() -> str:
- """Return the process user's SID without depending on localized account names."""
- result = subprocess.run(
- ["whoami", "/user", "/fo", "csv", "/nh"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", check=False, timeout=30,
- )
- if result.returncode:
- detail = result.stderr.strip() or f"whoami exited {result.returncode}"
- raise RuntimeError(f"could not resolve the current Windows user SID: {detail}")
- for row in csv.reader(result.stdout.splitlines()):
- for value in row:
- if _WINDOWS_SID.fullmatch(value.strip()):
- return value.strip()
- raise RuntimeError("could not parse the current Windows user SID")
-
def _repair_windows_home_acl() -> None:
"""Restore access for the filtered UAC token after an elevated update.
An elevated process can create home-tree entries whose DACL only grants
Administrators and SYSTEM. Administrators is deny-only in the normal UAC
- token, so grant the actual user SID explicitly and recurse over entries
- already created by the update.
+ token, so grant the actual user SID explicitly on every entry under the home.
+
+ The walk never descends into or grants through a junction, symlink or hard link
+ (``hermes_dir_acl.grant_tree_user_access``): ``icacls /T`` follows junctions, so a
+ same-user junction inside the home would have turned the elevated grant into full
+ control of e.g. ``C:\\Program Files\\X``.
"""
if sys.platform != "win32":
return
- from hermes_dir_acl import process_is_elevated
+ from hermes_dir_acl import grant_tree_user_access, process_is_elevated
if not process_is_elevated():
# Only an elevated update leaves Administrators-only entries, and only an elevated token
- # can rewrite them; a recursive icacls over the whole home on every update costs minutes.
+ # can rewrite them; a recursive grant over the whole home on every update costs minutes.
return
from hermes_constants import get_hermes_home
home = get_hermes_home()
- result = subprocess.run(
- _windows_home_acl_grant_command(home, _current_windows_user_sid()),
- capture_output=True, text=True, encoding="utf-8", errors="replace", check=False, timeout=900,
- )
- if result.returncode:
- detail = result.stderr.strip() or result.stdout.strip() or f"icacls exited {result.returncode}"
- raise RuntimeError(f"could not restore user access to {home}: {detail}")
+ granted, _skipped, failed = grant_tree_user_access(home)
+ if failed and not granted:
+ path, reason = failed[0]
+ raise RuntimeError(f"could not restore user access to {home}: {path}: {reason}")
+ if failed:
+ # Like icacls /C: keep going, report the first few; the step stays owed only when nothing took.
+ logger.warning("Restoring user access under %s failed for %d entr%s, e.g. %s: %s", home, len(failed),
+ "y" if len(failed) == 1 else "ies", failed[0][0], failed[0][1])
def _prepare_updated_checkout(project_root: Path, *, desktop: bool) -> None:
diff --git a/hermes_dir_acl.py b/hermes_dir_acl.py
index bfcd0bf9ce0..f352160b670 100644
--- a/hermes_dir_acl.py
+++ b/hermes_dir_acl.py
@@ -15,14 +15,24 @@ and every child created later stay usable by that user after elevation ends. An
existing directory re-grants the same ACE, which repairs a directory an earlier elevated run left
behind. A non-elevated process cannot change such a DACL; callers that hit one report it once with
:func:`unusable_dir_remedy`.
+
+An elevated grant never goes through a junction, symlink or other reparse point (nor a hard-linked
+file): same-user medium-integrity code can swap any entry under the home for a junction to e.g.
+``C:\\Program Files\\X``, and a grant that followed it would hand the user full control of the
+target across the UAC boundary. The path is lstat-checked first, and the pywin32 grant opens it with
+``FILE_FLAG_OPEN_REPARSE_POINT`` and re-checks the handle, so a swap after the check is not followed
+either; the icacls fallback passes ``/L``. :func:`grant_tree_user_access` is the recursive form
+(the post-update repair), pruning every reparse point instead of descending into it.
"""
from __future__ import annotations
import functools
import logging
import os
+import stat
import subprocess
import sys
+from collections.abc import Iterator
from pathlib import Path
log = logging.getLogger(__name__)
@@ -31,6 +41,32 @@ _TOKEN_QUERY = 0x0008
_TOKEN_USER = 1
_TOKEN_ELEVATION = 20
+FILE_ATTRIBUTE_DIRECTORY = 0x10
+FILE_ATTRIBUTE_REPARSE_POINT = 0x400
+_READ_CONTROL = 0x00020000
+_WRITE_DAC = 0x00040000
+_FILE_SHARE_ALL = 0x7 # read | write | delete: never block another Hermes process
+_OPEN_EXISTING = 3
+_FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 # needed to open a directory handle
+_FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 # open the link itself, never its target
+
+
+class ReparsePointRefused(OSError):
+ """The grant target is (or became) a junction, symlink, other reparse point or hard link."""
+
+
+def is_reparse_point(path: str | Path) -> bool:
+ """True when *path* itself is a symlink, junction or other reparse point (never followed), or
+ cannot be lstat-ed at all; the safe answer for "may an elevated grant act on this path"."""
+ try:
+ st = os.lstat(path)
+ except OSError:
+ return True
+ if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & FILE_ATTRIBUTE_REPARSE_POINT:
+ return True
+ isjunction = getattr(os.path, "isjunction", None) # 3.12+; st_file_attributes covers 3.11
+ return bool(isjunction and isjunction(path))
+
@functools.lru_cache(maxsize=1)
def process_is_elevated() -> bool:
@@ -60,53 +96,149 @@ def process_is_elevated() -> bool:
kernel.CloseHandle(token)
-def _grant_with_pywin32(path: Path) -> None:
+def _strip_win32_prefix(path: str) -> str:
+ if path.startswith("\\\\?\\UNC\\"):
+ return "\\\\" + path[8:]
+ return path.removeprefix("\\\\?\\")
+
+
+def _grant_with_pywin32(path: Path, is_dir: bool, expected: str | None = None) -> None:
import ntsecuritycon
import win32api
+ import win32file
import win32security
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32security.TOKEN_QUERY)
user_sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
- descriptor = win32security.GetFileSecurity(str(path), win32security.DACL_SECURITY_INFORMATION)
- dacl = descriptor.GetSecurityDescriptorDacl()
- inherit = win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE
- if dacl is not None:
- for index in range(dacl.GetAceCount()):
- (ace_type, flags, *_), mask, sid = dacl.GetAce(index)[:3]
- if (ace_type == win32security.ACCESS_ALLOWED_ACE_TYPE and sid == user_sid
- and mask & ntsecuritycon.FILE_ALL_ACCESS == ntsecuritycon.FILE_ALL_ACCESS
- and flags & inherit == inherit and not flags & win32security.INHERIT_ONLY_ACE):
- return # already granted: never grow the DACL on repeat calls
- else:
- dacl = win32security.ACL()
- dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, inherit, ntsecuritycon.FILE_ALL_ACCESS, user_sid)
- descriptor.SetSecurityDescriptorDacl(True, dacl, False)
- win32security.SetFileSecurity(str(path), win32security.DACL_SECURITY_INFORMATION, descriptor)
-
-
-def _grant_with_icacls(path: Path) -> None:
+ # Act on the handle, never the name: GetFileSecurity/SetFileSecurity resolve a junction or symlink
+ # to its target, so a swap after the lstat check would still redirect the grant.
+ handle = win32file.CreateFile(str(path), _READ_CONTROL | _WRITE_DAC, _FILE_SHARE_ALL, None, _OPEN_EXISTING,
+ _FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT, None)
+ try:
+ if expected is not None:
+ # A parent swapped for a junction after the lstat checks resolves the name elsewhere.
+ final = _strip_win32_prefix(win32file.GetFinalPathNameByHandle(handle, 0))
+ if os.path.normcase(final.rstrip("\\")) != os.path.normcase(expected.rstrip("\\")):
+ raise ReparsePointRefused(f"{path} resolves to {final}, not {expected}")
+ info = win32file.GetFileInformationByHandle(handle)
+ attributes, links = info[0], info[7]
+ if attributes & FILE_ATTRIBUTE_REPARSE_POINT:
+ raise ReparsePointRefused(f"{path} is a junction, symlink or other reparse point")
+ if not attributes & FILE_ATTRIBUTE_DIRECTORY and links > 1:
+ raise ReparsePointRefused(f"{path} is a hard link ({links} names); its other names may be outside")
+ is_dir = bool(attributes & FILE_ATTRIBUTE_DIRECTORY)
+ descriptor = win32security.GetKernelObjectSecurity(handle, win32security.DACL_SECURITY_INFORMATION)
+ dacl = descriptor.GetSecurityDescriptorDacl()
+ inherit = (win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE) if is_dir else 0
+ if dacl is not None:
+ for index in range(dacl.GetAceCount()):
+ (ace_type, flags, *_), mask, sid = dacl.GetAce(index)[:3]
+ if (ace_type == win32security.ACCESS_ALLOWED_ACE_TYPE and sid == user_sid
+ and mask & ntsecuritycon.FILE_ALL_ACCESS == ntsecuritycon.FILE_ALL_ACCESS
+ and flags & inherit == inherit and not flags & win32security.INHERIT_ONLY_ACE):
+ return # already granted: never grow the DACL on repeat calls
+ else:
+ dacl = win32security.ACL()
+ dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, inherit, ntsecuritycon.FILE_ALL_ACCESS, user_sid)
+ descriptor.SetSecurityDescriptorDacl(True, dacl, False)
+ # The handle form of SetFileSecurity: same semantics (no propagation walk), no name resolution.
+ win32security.SetKernelObjectSecurity(handle, win32security.DACL_SECURITY_INFORMATION, descriptor)
+ finally:
+ handle.Close()
+
+
[email protected]_cache(maxsize=1)
+def _whoami_sid() -> str:
whoami = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"], capture_output=True, text=True,
check=True, encoding="utf-8", errors="replace", timeout=30)
sid = whoami.stdout.strip().rsplit(",", 1)[-1].strip().strip('"')
if not sid.upper().startswith("S-1-"):
raise OSError(f"could not resolve the current user SID from whoami: {whoami.stdout!r}")
- subprocess.run(["icacls", str(path), "/grant", f"*{sid}:(OI)(CI)F", "/Q"], capture_output=True,
+ return sid
+
+
+def _grant_with_icacls(path: Path, is_dir: bool, expected: str | None = None) -> None:
+ if is_dir:
+ # icacls applies an inheritable ACE through SetNamedSecurityInfo, which also propagates it
+ # down the existing subtree; refuse when that subtree holds a link it could descend into.
+ nested: list[Path] = []
+ for _ in iter_tree_without_reparse_points(path, nested):
+ if nested:
+ raise ReparsePointRefused(f"{nested[0]} under {path} is a junction or link (icacls fallback)")
+ ace = f"*{_whoami_sid()}:(OI)(CI)F" if is_dir else f"*{_whoami_sid()}:F"
+ # /L: act on a symbolic link or junction itself, not its target (the lstat check already refused
+ # one; this covers a swap between that check and icacls opening the path). Without pywin32 there
+ # is no handle to pin, so *expected* cannot be re-checked here.
+ subprocess.run(["icacls", str(path), "/grant", ace, "/Q", "/L"], capture_output=True,
check=True, timeout=60)
+def _hard_linked_file(path: Path) -> bool:
+ try:
+ st = os.lstat(path)
+ except OSError:
+ return True
+ return not stat.S_ISDIR(st.st_mode) and st.st_nlink > 1
+
+
+def _grant(path: Path, is_dir: bool = True, expected: str | None = None) -> None:
+ """Grant the token's user full control on *path* itself; raise :class:`ReparsePointRefused`
+ for a reparse point or hard-linked file (or, with *expected*, a handle that resolves anywhere
+ else) and anything else on failure."""
+ if is_reparse_point(path) or _hard_linked_file(path):
+ raise ReparsePointRefused(f"{path} is a junction, symlink, other reparse point or hard link")
+ try:
+ _grant_with_pywin32(path, is_dir, expected)
+ except ImportError:
+ _grant_with_icacls(path, is_dir, expected)
+
+
+def _components_below_home(path: Path) -> list[Path]:
+ """*path* and each ancestor of it strictly below the Hermes home (lexically), outermost first;
+ empty when *path* is not under the home. The home itself (and above) is the user's own choice
+ and may legitimately be a link; an entry INSIDE it is what same-user code can swap."""
+ try:
+ from hermes_constants import get_hermes_home
+ home = Path(os.path.abspath(get_hermes_home()))
+ rel = Path(os.path.abspath(path)).relative_to(home)
+ except (ImportError, ValueError, OSError):
+ return []
+ return [home.joinpath(*rel.parts[:i]) for i in range(1, len(rel.parts) + 1)]
+
+
+def _expected_final(path: Path) -> str | None:
+ """Where *path* must resolve when nothing below the home is a link: the home's real path plus
+ the relative parts. None off-home (only the leaf's own open-reparse check applies there)."""
+ components = _components_below_home(path)
+ if not components:
+ return None
+ home = components[0].parent
+ return os.path.join(os.path.realpath(home), *Path(os.path.abspath(path)).relative_to(home).parts)
+
+
+def _warn_refused(path: Path, exc: BaseException) -> None:
+ log.warning("Not granting the current user access to %s while elevated (%s): an elevated grant "
+ "never follows a junction or link out of the Hermes home. If this is your own link, "
+ "point HERMES_HOME (or the link) at the real directory.", path, exc)
+
+
def grant_user_access(path: str | Path) -> bool:
"""Give the token's user an inheriting full-control ACE on *path* when this process is elevated.
- True when a grant was attempted and did not fail; False off Windows, when not elevated, or when
- the grant failed (logged; the directory itself still exists)."""
+ True when a grant was attempted and did not fail; False off Windows, when not elevated, when
+ *path* is a junction/symlink/reparse point (refused, one warning), or when the grant failed
+ (logged; the directory itself still exists)."""
if sys.platform != "win32" or not process_is_elevated():
return False
target = Path(path)
try:
- try:
- _grant_with_pywin32(target)
- except ImportError:
- _grant_with_icacls(target)
+ for component in _components_below_home(target):
+ if is_reparse_point(component):
+ raise ReparsePointRefused(f"{component} is a junction, symlink or other reparse point")
+ _grant(target, expected=_expected_final(target))
+ except ReparsePointRefused as exc:
+ _warn_refused(target, exc)
+ return False
except Exception as exc: # health: allow BLE001 -- pywintypes.error is not an OSError; never fail the mkdir
log.warning("Could not grant the current user access to %s created while elevated (%s); a "
"non-elevated Hermes may not be able to use it. To repair, from an elevated prompt run: "
@@ -115,6 +247,62 @@ def grant_user_access(path: str | Path) -> bool:
return True
+def iter_tree_without_reparse_points(root: str | Path, skipped: list[Path]) -> Iterator[tuple[Path, bool]]:
+ """Yield ``(path, is_dir)`` for *root* and everything under it, never entering or yielding a
+ junction, symlink or other reparse point (each one is appended to *skipped* instead).
+
+ ``os.walk`` is not enough: it follows directory junctions (``os.path.islink`` is False for one).
+ Unreadable directories are skipped silently, like ``icacls /C``."""
+ root = Path(root)
+ if is_reparse_point(root):
+ skipped.append(root)
+ return
+ stack = [root]
+ while stack:
+ directory = stack.pop()
+ yield directory, True
+ try:
+ with os.scandir(directory) as entries:
+ children = [Path(entry.path) for entry in entries]
+ except OSError:
+ continue
+ for child in sorted(children):
+ if is_reparse_point(child):
+ skipped.append(child)
+ elif child.is_dir():
+ stack.append(child)
+ else:
+ yield child, False
+
+
+def grant_tree_user_access(root: str | Path) -> tuple[int, list[Path], list[tuple[Path, str]]]:
+ """Recursive :func:`grant_user_access` (the elevated post-update repair): grant the token's user
+ full control on *root* and every directory and file under it, inheriting on directories.
+
+ Returns ``(granted, skipped, failed)``: *skipped* are the reparse points (and hard-linked files)
+ that were neither granted nor entered, *failed* the ``(path, reason)`` grants that raised. A
+ no-op ``(0, [], [])`` off Windows or when not elevated."""
+ if sys.platform != "win32" or not process_is_elevated():
+ return 0, [], []
+ root = Path(os.path.abspath(root))
+ real_root = os.path.realpath(root)
+ granted, skipped, failed = 0, [], []
+ for path, is_dir in iter_tree_without_reparse_points(root, skipped):
+ try:
+ _grant(path, is_dir, os.path.join(real_root, *path.relative_to(root).parts))
+ except ReparsePointRefused:
+ skipped.append(path)
+ except Exception as exc: # health: allow BLE001 -- pywintypes.error is not an OSError; keep going like /C
+ failed.append((path, str(exc) or type(exc).__name__))
+ else:
+ granted += 1
+ if skipped:
+ log.warning("Elevated ACL repair skipped %d junction/symlink/hard-link entr%s under %s (never "
+ "granted through): %s", len(skipped), "y" if len(skipped) == 1 else "ies", root,
+ ", ".join(str(p) for p in skipped[:5]) + (" ..." if len(skipped) > 5 else ""))
+ 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()
@@ -126,7 +314,8 @@ def make_user_dir(path: str | Path, mode: int = 0o777, *, parents: bool = False,
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."""
+ repair case), get the user's inheriting full-control ACE once per process, except that a
+ component that is a junction/symlink/reparse point stops the grants with one warning."""
target = Path(path)
if sys.platform != "win32" or not process_is_elevated():
target.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
@@ -137,7 +326,14 @@ def make_user_dir(path: str | Path, mode: int = 0o777, *, parents: bool = False,
created.append(probe)
probe = probe.parent
target.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
- for directory in reversed(created or [target]):
+ to_grant = list(reversed(created or [target]))
+ # 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]):
+ if is_reparse_point(component):
+ _warn_refused(component, ReparsePointRefused("junction, symlink or other reparse point"))
+ return target
+ for directory in to_grant:
if directory not in _granted and grant_user_access(directory):
_granted.add(directory)
return target
diff --git a/tests/hermes_cli/test_update_windows_home_acl.py b/tests/hermes_cli/test_update_windows_home_acl.py
index 43b6f085fdf..428c62f02f7 100644
--- a/tests/hermes_cli/test_update_windows_home_acl.py
+++ b/tests/hermes_cli/test_update_windows_home_acl.py
@@ -1,40 +1,65 @@
-"""Windows update ACL repair command contracts."""
+"""Windows update ACL repair contracts (the Windows ACL effect: ``tests/test_hermes_dir_acl_windows.py``)."""
-from hermes_cli.update_cmd_maint import _windows_home_acl_grant_command
+import os
+import subprocess
+import sys
+import hermes_dir_acl
+from hermes_cli import update_cmd_maint as maint
-def test_windows_home_acl_grant_targets_the_current_user_sid_recursively(tmp_path):
- home = tmp_path / "hermes home"
- assert _windows_home_acl_grant_command(home, "S-1-5-21-100-200-300-400") == [
- "icacls",
- str(home),
- "/grant",
- "*S-1-5-21-100-200-300-400:(OI)(CI)F",
- "/T",
- "/C",
- "/Q",
- ]
+def _fake_elevated_windows(monkeypatch, tmp_path, elevated=True):
+ granted, runs = [], []
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ sid_row = '"host\\\\user","S-1-5-21-1-2-3-1001"\n' # whoami /user /fo csv /nh
+ def run(argv, **kw):
+ runs.append(argv)
+ return subprocess.CompletedProcess(argv, 0, sid_row if argv[0] == "whoami" else "", "")
-def test_repair_runs_only_from_an_elevated_update(monkeypatch, tmp_path):
- """A non-elevated update created nothing Administrators-only and could not rewrite it anyway;
- the recursive icacls over the whole home is skipped there."""
- import subprocess
- import sys
+ monkeypatch.setattr(subprocess, "run", run)
+ monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: elevated)
+ monkeypatch.setattr(hermes_dir_acl, "_grant_with_pywin32",
+ lambda path, *_a, **_k: granted.append(os.path.realpath(path)))
+ return granted, runs
- import hermes_dir_acl
- from hermes_cli import update_cmd_maint as maint
- calls = []
- monkeypatch.setattr(sys, "platform", "win32")
- monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- monkeypatch.setattr(maint, "_current_windows_user_sid", lambda: "S-1-5-21-1-2-3-1001")
- monkeypatch.setattr(subprocess, "run", lambda argv, **kw: calls.append((argv, kw)) or
- subprocess.CompletedProcess(argv, 0, "", ""))
- monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: False)
+def test_repair_runs_only_from_an_elevated_update(monkeypatch, tmp_path):
+ """A non-elevated update created nothing Administrators-only and could not rewrite it anyway;
+ the recursive grant over the whole home is skipped there."""
+ (tmp_path / "home").mkdir()
+ granted, runs = _fake_elevated_windows(monkeypatch, tmp_path, elevated=False)
maint._repair_windows_home_acl()
- assert calls == []
+ assert granted == [] and runs == []
monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: True)
maint._repair_windows_home_acl()
- assert calls and calls[0][0][0] == "icacls" and calls[0][1]["timeout"]
+ assert granted == [str(tmp_path / "home")]
+
+
+def test_repair_never_recurses_through_a_link_inside_the_home(monkeypatch, tmp_path):
+ """P2-5: ``icacls HOME /grant ... /T`` follows junctions inside the home, so an elevated update
+ granted the user full control of whatever a same-user junction pointed at."""
+ home = tmp_path / "home"
+ (home / "cache").mkdir(parents=True)
+ outside = tmp_path / "Program Files" / "X"
+ (outside / "bin").mkdir(parents=True)
+ (home / "cache" / "images").symlink_to(outside, target_is_directory=True)
+ granted, runs = _fake_elevated_windows(monkeypatch, tmp_path)
+ maint._repair_windows_home_acl()
+ assert not any(argv and argv[0] == "icacls" and "/T" in argv for argv in runs), runs
+ assert granted == [str(home), str(home / "cache")]
+
+
+def test_repair_stays_owed_when_nothing_could_be_granted(monkeypatch, tmp_path):
+ import pytest
+
+ (tmp_path / "home").mkdir()
+ _fake_elevated_windows(monkeypatch, tmp_path)
+
+ def denied(path, *_a, **_k):
+ raise OSError("access denied")
+
+ monkeypatch.setattr(hermes_dir_acl, "_grant_with_pywin32", denied)
+ with pytest.raises(RuntimeError, match="could not restore user access"):
+ maint._repair_windows_home_acl()
diff --git a/tests/test_hermes_dir_acl.py b/tests/test_hermes_dir_acl.py
index e0fe38bad56..cc828c9aaa2 100644
--- a/tests/test_hermes_dir_acl.py
+++ b/tests/test_hermes_dir_acl.py
@@ -44,7 +44,7 @@ def test_a_failed_grant_never_fails_the_mkdir_and_is_retried(tmp_path, monkeypat
monkeypatch.setattr(hermes_dir_acl, "_granted", set())
attempts = []
- def boom(path):
+ def boom(path, *_a, **_k):
attempts.append(path)
raise OSError("access denied")
@@ -59,3 +59,127 @@ def test_remedy_names_the_platform_repair(monkeypatch):
assert hermes_dir_acl.unusable_dir_remedy("C:\\x") == 'from an elevated prompt run: icacls "C:\\x" /reset /t'
monkeypatch.setattr(hermes_dir_acl.os, "name", "posix")
assert "chown" in hermes_dir_acl.unusable_dir_remedy("/x")
+
+
+# ── P2-5: an elevated grant never follows a junction/symlink out of the Hermes home ──────────────
+
+
+def elevated_windows(tmp_path, monkeypatch):
+ """Fake an elevated Windows process; record what the native grant would have touched."""
+ home = tmp_path / "home"
+ home.mkdir()
+ outside = tmp_path / "Program Files" / "X"
+ outside.mkdir(parents=True)
+ (outside / "app.exe").write_text("x")
+ 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())
+ touched = []
+ monkeypatch.setattr(hermes_dir_acl, "_grant_with_pywin32",
+ lambda path, *_a, **_k: touched.append(os.path.realpath(path)))
+ return home, outside, touched
+
+
+def _escapes(touched, outside):
+ return [p for p in touched if p == str(outside) or p.startswith(str(outside) + os.sep)]
+
+
+def test_make_user_dir_refuses_an_existing_leaf_that_is_a_link(elevated_windows, caplog):
+ home, outside, touched = elevated_windows
+ (home / "cache").mkdir()
+ planted = home / "cache" / "images"
+ planted.symlink_to(outside, target_is_directory=True)
+ with caplog.at_level("WARNING", logger="hermes_dir_acl"):
+ hermes_dir_acl.make_user_dir(planted, parents=True, exist_ok=True)
+ hermes_dir_acl.make_user_dir(planted, parents=True, exist_ok=True)
+ assert touched == []
+ assert [r for r in caplog.records if "never follows a junction" in r.getMessage()]
+
+
+def test_make_user_dir_refuses_a_link_among_its_ancestors_in_the_home(elevated_windows):
+ home, outside, touched = elevated_windows
+ (home / "cache").symlink_to(outside, target_is_directory=True)
+ made = hermes_dir_acl.make_user_dir(home / "cache" / "images" / "x", parents=True, exist_ok=True)
+ assert made.is_dir() # the mkdir itself still happens (it lands where the user's own link points)
+ assert touched == [], "a grant went through a planted link"
+
+
+def test_grant_user_access_refuses_a_link_directly(elevated_windows):
+ home, outside, touched = elevated_windows
+ link = home / "logs"
+ link.symlink_to(outside, target_is_directory=True)
+ assert hermes_dir_acl.grant_user_access(link) is False
+ assert hermes_dir_acl.grant_user_access(link / "deeper") is False
+ assert touched == []
+
+
+def test_make_user_dir_still_grants_real_dirs_under_a_linked_home(tmp_path, monkeypatch):
+ """HERMES_HOME itself is the user's own choice; only entries INSIDE it are swappable."""
+ real = tmp_path / "real-home"
+ real.mkdir()
+ linked = tmp_path / "linked-home"
+ linked.symlink_to(real, target_is_directory=True)
+ monkeypatch.setenv("HERMES_HOME", str(linked))
+ 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())
+ calls = []
+ monkeypatch.setattr(hermes_dir_acl, "_grant_with_pywin32",
+ lambda path, is_dir, expected=None: calls.append((path, expected)))
+ hermes_dir_acl.make_user_dir(linked / "state", exist_ok=True)
+ assert calls == [(linked / "state", os.path.join(str(real), "state"))]
+
+
+def test_tree_walk_skips_symlinks_and_never_enters_them(tmp_path):
+ root = tmp_path / "home"
+ (root / "a" / "b").mkdir(parents=True)
+ (root / "a" / "f.txt").write_text("x")
+ outside = tmp_path / "outside"
+ (outside / "deep").mkdir(parents=True)
+ (root / "a" / "jn").symlink_to(outside, target_is_directory=True)
+ (root / "flink").symlink_to(outside / "deep")
+ skipped = []
+ seen = {p.relative_to(root).as_posix(): d for p, d in hermes_dir_acl.iter_tree_without_reparse_points(root, skipped)}
+ assert seen == {".": True, "a": True, "a/b": True, "a/f.txt": False}
+ assert sorted(p.name for p in skipped) == ["flink", "jn"]
+
+
+def test_tree_walk_treats_a_reparse_attribute_as_a_link(tmp_path, monkeypatch):
+ """A Windows directory junction is not S_ISLNK on every Python; the reparse attribute decides."""
+ root = tmp_path / "home"
+ (root / "junction").mkdir(parents=True)
+ real_lstat = os.lstat
+
+ class Junction:
+ def __init__(self, st):
+ self._st = st
+ self.st_file_attributes = hermes_dir_acl.FILE_ATTRIBUTE_REPARSE_POINT | hermes_dir_acl.FILE_ATTRIBUTE_DIRECTORY
+
+ def __getattr__(self, name):
+ return getattr(self._st, name)
+
+ monkeypatch.setattr(hermes_dir_acl.os, "lstat",
+ lambda p, *a, **k: Junction(real_lstat(p)) if str(p).endswith("junction") else real_lstat(p))
+ skipped = []
+ seen = [p for p, _ in hermes_dir_acl.iter_tree_without_reparse_points(root, skipped)]
+ assert seen == [root] and skipped == [root / "junction"]
+
+
+def test_tree_grant_never_touches_a_target_outside_the_home(elevated_windows):
+ home, outside, touched = elevated_windows
+ (home / "sessions").mkdir()
+ (home / "sessions" / "s.json").write_text("{}")
+ (home / "sessions" / "jn").symlink_to(outside, target_is_directory=True)
+ (home / "hardlink.exe").hardlink_to(outside / "app.exe")
+ granted, skipped, failed = hermes_dir_acl.grant_tree_user_access(home)
+ assert _escapes(touched, outside) == [] and failed == []
+ assert sorted(p.name for p in skipped) == ["hardlink.exe", "jn"]
+ assert granted == 3 # home, sessions, s.json
+
+
+def test_tree_grant_is_a_noop_unelevated(tmp_path, monkeypatch):
+ monkeypatch.setattr(hermes_dir_acl.sys, "platform", "win32")
+ monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: False)
+ assert hermes_dir_acl.grant_tree_user_access(tmp_path) == (0, [], [])
diff --git a/tests/test_hermes_dir_acl_windows.py b/tests/test_hermes_dir_acl_windows.py
index 42d85f20ab5..ca45cd52001 100644
--- a/tests/test_hermes_dir_acl_windows.py
+++ b/tests/test_hermes_dir_acl_windows.py
@@ -201,3 +201,58 @@ def _w2(lock_dir):
assert (ok, code, retryable) == (False, "lock_dir_unusable", False)
assert "icacls" in message and "/reset" in message and str(lock_dir) in message
assert len(result["warnings"]) == 1, result
+
+
+# ── P2-5: an elevated grant never follows a junction out of the Hermes home ──────────────────────
+
+
+def home_with_junction_out(tmp_path, monkeypatch):
+ """A Hermes home holding a directory junction (what same-user medium-integrity code can plant)
+ to a directory outside it, standing in for ``C:\\Program Files\\<app>``."""
+ if not _elevated():
+ pytest.skip("needs an elevated token: only an elevated run grants")
+ import _winapi
+
+ home = tmp_path / "hermes"
+ (home / "cache").mkdir(parents=True)
+ outside = tmp_path / "Program Files" / "App"
+ (outside / "bin").mkdir(parents=True)
+ (outside / "bin" / "app.exe").write_text("x")
+ subprocess.run(["icacls", str(outside), *_REPORTERS_DACL], check=True, capture_output=True)
+ junction = home / "cache" / "images"
+ _winapi.CreateJunction(str(outside), str(junction))
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ yield home, outside, junction
+ junction.rmdir() # removes the junction itself, not the target
+ subprocess.run(["icacls", str(outside), "/reset", "/t", "/c", "/q"], check=False, capture_output=True)
+
+
+def _dacls(paths):
+ """icacls text of each of *paths*, path-normalized for comparison."""
+ return [subprocess.run(["icacls", str(path)], capture_output=True, text=True, check=True).stdout
+ .replace(str(path), "<p>") for path in paths]
+
+
+def test_elevated_grants_never_reach_a_junction_target_outside_the_home(home_with_junction_out):
+ import hermes_dir_acl
+ from hermes_cli import update_cmd_maint
+
+ home, outside, junction = home_with_junction_out
+ assert hermes_dir_acl.is_reparse_point(junction)
+ watched = [outside, *sorted(outside.rglob("*"))]
+ before = _dacls(watched)
+ hermes_dir_acl._granted.clear()
+ hermes_dir_acl.make_user_dir(junction, parents=True, exist_ok=True) # the existing-leaf "repair" case
+ hermes_dir_acl.make_user_dir(junction / "thumbs", parents=True, exist_ok=True) # through the junction
+ assert hermes_dir_acl.grant_user_access(junction) is False
+ granted, skipped, failed = hermes_dir_acl.grant_tree_user_access(home)
+ update_cmd_maint._repair_windows_home_acl() # the post-update repair that used icacls /T
+ assert junction in skipped and not failed and granted >= 2
+ assert _dacls(watched) == before, "an elevated grant followed the junction out of the home"
+ # The real entries in the home still got the grant.
+ whoami = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"], capture_output=True, text=True, check=True)
+ sid = whoami.stdout.strip().rsplit(",", 1)[-1].strip().strip('"')
+ home_acl = subprocess.run(["icacls", str(home / "cache")], capture_output=True, text=True, check=True).stdout
+ user = subprocess.run(["whoami"], capture_output=True, text=True, check=True).stdout.strip()
+ assert sid in home_acl or user.lower() in home_acl.lower(), home_acl