Skip to content

The agent that grows with you

fix(update): restore Windows user ACL after elevation

KoNit-K665ccdfebbea
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index 5b756f9f8b4..a3f7e0e1f57 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -5,7 +5,9 @@ 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
@@ -20,6 +22,51 @@ 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,
+ )
+ 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.
+ """
+ if sys.platform != "win32":
+ 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,
+ )
+ 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}")
+
def _prepare_updated_checkout(project_root: Path, *, desktop: bool) -> None:
"""Historical updater hook: never complete inside the pre-swap interpreter."""
@@ -976,6 +1023,7 @@ def _run_post_update_maintenance(
followups.append((name, reason))
from hermes_cli.update_cmd import _check_and_apply_config_migration, _m
+ owed_step("windows_home_acl", _repair_windows_home_acl)
# macOS TCC: Desktop bundles are re-signed each update, so old grants can go stale
# (toggle ON, yet macOS re-prompts with no Allow button). Tell users how to re-grant.
# With the post-#73681 identifier-pinned DR, new grants survive rebuilds — but a grant made to a pre-fix
diff --git a/tests/hermes_cli/test_update_post_commit_followups.py b/tests/hermes_cli/test_update_post_commit_followups.py
index 0cd8bfa2546..6d4112394dd 100644
--- a/tests/hermes_cli/test_update_post_commit_followups.py
+++ b/tests/hermes_cli/test_update_post_commit_followups.py
@@ -133,7 +133,7 @@ def test_failed_config_migration_is_owed_and_later_maintenance_runs(tmp_path, mo
calls = []
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
- for name in ("_verify_and_restore_state_dbs_post_update", "_invalidate_live_plugin_catalog_caches",
+ for name in ("_repair_windows_home_acl", "_verify_and_restore_state_dbs_post_update", "_invalidate_live_plugin_catalog_caches",
"_print_bundled_skills_sync_report", "_sync_profiles_after_update"):
monkeypatch.setattr(maint, name, lambda name=name: calls.append(name))
monkeypatch.setattr("hermes_cli.gitlock.fetch_full_commit_graph", lambda *a, **kw: False)
@@ -151,6 +151,7 @@ def test_failed_config_migration_is_owed_and_later_maintenance_runs(tmp_path, mo
assume_yes=True, gateway_mode=False, pre_update_snapshot_id=None,
had_desktop_app_before_update=False, pre_update_version=None, followups=owed) is True
assert [step for step, _ in owed] == ["config_migration"]
+ assert calls[0] == "_repair_windows_home_acl"
assert calls[-2:] == ["verdict", "notices"]
assert "⚠ Update follow-up 'config_migration'" in capsys.readouterr().out
update_receipt.finalize_update_receipt("success")
diff --git a/tests/hermes_cli/test_update_windows_home_acl.py b/tests/hermes_cli/test_update_windows_home_acl.py
new file mode 100644
index 00000000000..4d304f189af
--- /dev/null
+++ b/tests/hermes_cli/test_update_windows_home_acl.py
@@ -0,0 +1,17 @@
+"""Windows update ACL repair command contracts."""
+
+from hermes_cli.update_cmd_maint import _windows_home_acl_grant_command
+
+
+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",
+ ]