hermes_dir_acl.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. """Directories an elevated Windows process creates must stay usable by the same user unelevated.
  2. Since CPython 3.13, ``os.mkdir(path, 0o700)`` on Windows applies a protected DACL of exactly
  3. SYSTEM, Administrators and OWNER RIGHTS. An elevated process's default owner is
  4. ``BUILTIN\\Administrators``, so OWNER RIGHTS resolves to Administrators too, and the user's own
  5. non-elevated token (where Administrators is deny-only) gets ``WinError 5`` on the directory and on
  6. everything created inside it (#139845, #139485, the ``gateway-locks`` reports in #134889 W2). A plain
  7. ``mkdir`` inherits its parent's ACL instead, which under ``%LOCALAPPDATA%`` names the user, so the
  8. ``mode=0o700`` sites are the ones that strand the user.
  9. :func:`make_user_dir` is the one place Hermes state/lock/log directories are created. Off Windows,
  10. or in a non-elevated process, it is exactly ``Path.mkdir``. In an elevated Windows process it adds
  11. an explicit, inheriting full-control ACE for the token's user SID to the directory, so the directory
  12. and every child created later stay usable by that user after elevation ends. An elevated call on an
  13. existing directory re-grants the same ACE, which repairs a directory an earlier elevated run left
  14. behind; the pywin32 write does not propagate, so when it had to write, the entries already inside
  15. (an old token lock) are granted too, once, never through a link. A non-elevated process cannot change such a DACL; callers that hit one report it once with
  16. :func:`unusable_dir_remedy`.
  17. An elevated grant never goes through a junction, symlink or other reparse point (nor a hard-linked
  18. file): same-user medium-integrity code can swap any entry under the home for a junction to e.g.
  19. ``C:\\Program Files\\X``, and a grant that followed it would hand the user full control of the
  20. target across the UAC boundary. The path is lstat-checked first, and the pywin32 grant opens it with
  21. ``FILE_FLAG_OPEN_REPARSE_POINT`` and re-checks the handle, so a swap after the check is not followed
  22. either; the icacls fallback passes ``/L``. :func:`grant_tree_user_access` is the recursive form
  23. (the post-update repair), pruning every reparse point instead of descending into it.
  24. """
  25. from __future__ import annotations
  26. import functools
  27. import logging
  28. import os
  29. import stat
  30. import subprocess
  31. import sys
  32. from collections.abc import Iterator
  33. from pathlib import Path
  34. log = logging.getLogger(__name__)
  35. _TOKEN_QUERY = 0x0008
  36. _TOKEN_USER = 1
  37. _TOKEN_ELEVATION = 20
  38. FILE_ATTRIBUTE_DIRECTORY = 0x10
  39. FILE_ATTRIBUTE_REPARSE_POINT = 0x400
  40. _READ_CONTROL = 0x00020000
  41. _WRITE_DAC = 0x00040000
  42. _FILE_SHARE_ALL = 0x7 # read | write | delete: never block another Hermes process
  43. _OPEN_EXISTING = 3
  44. _FILE_FLAG_BACKUP_SEMANTICS = 0x02000000 # needed to open a directory handle
  45. _FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 # open the link itself, never its target
  46. class ReparsePointRefused(OSError):
  47. """The grant target is (or became) a junction, symlink, other reparse point or hard link."""
  48. def is_reparse_point(path: str | Path) -> bool:
  49. """True when *path* itself is a symlink, junction or other reparse point (never followed), or
  50. cannot be lstat-ed at all; the safe answer for "may an elevated grant act on this path"."""
  51. try:
  52. st = os.lstat(path)
  53. except OSError:
  54. return True
  55. if stat.S_ISLNK(st.st_mode) or getattr(st, "st_file_attributes", 0) & FILE_ATTRIBUTE_REPARSE_POINT:
  56. return True
  57. isjunction = getattr(os.path, "isjunction", None) # 3.12+; st_file_attributes covers 3.11
  58. return bool(isjunction and isjunction(path))
  59. _PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
  60. def process_elevation(pid: int | None = None) -> bool | None:
  61. """``TokenElevation`` of *pid*'s token (default: this process). The ONE elevation probe: the
  62. grants below, the refused-owner naming in ``gateway.runtime_bootstrap_windows`` and the
  63. Windows service installer all read it. None when the process or its token cannot be opened
  64. (across an elevation boundary that refusal is itself an answer the caller interprets)."""
  65. import ctypes
  66. from ctypes import wintypes
  67. advapi = ctypes.WinDLL("advapi32", use_last_error=True)
  68. kernel = ctypes.WinDLL("kernel32", use_last_error=True)
  69. kernel.GetCurrentProcess.restype = wintypes.HANDLE
  70. kernel.OpenProcess.restype = wintypes.HANDLE
  71. kernel.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
  72. advapi.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)]
  73. advapi.GetTokenInformation.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD,
  74. ctypes.POINTER(wintypes.DWORD)]
  75. kernel.CloseHandle.argtypes = [wintypes.HANDLE]
  76. own = pid is None
  77. process = kernel.GetCurrentProcess() if own else kernel.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION,
  78. False, pid)
  79. if not process:
  80. return None
  81. token = wintypes.HANDLE()
  82. try:
  83. if not advapi.OpenProcessToken(process, _TOKEN_QUERY, ctypes.byref(token)):
  84. return None
  85. elevated, size = wintypes.DWORD(), wintypes.DWORD()
  86. if not advapi.GetTokenInformation(token, _TOKEN_ELEVATION, ctypes.byref(elevated),
  87. ctypes.sizeof(elevated), ctypes.byref(size)):
  88. return None
  89. return bool(elevated.value)
  90. finally:
  91. if token:
  92. kernel.CloseHandle(token)
  93. if not own: # the pseudo-handle of GetCurrentProcess is never closed
  94. kernel.CloseHandle(process)
  95. @functools.lru_cache(maxsize=1)
  96. def process_is_elevated() -> bool:
  97. """True for an elevated (UAC full-token) Windows process; False elsewhere or on any error."""
  98. if sys.platform != "win32":
  99. return False
  100. return bool(process_elevation())
  101. def _strip_win32_prefix(path: str) -> str:
  102. if path.startswith("\\\\?\\UNC\\"):
  103. return "\\\\" + path[8:]
  104. return path.removeprefix("\\\\?\\")
  105. def _grant_with_pywin32(path: Path, is_dir: bool, expected: str | None = None) -> bool:
  106. """Write the ACE on the handle; True when it was written (False: already present). The write
  107. does NOT propagate (``SetKernelObjectSecurity``), so a written dir's existing children are owed."""
  108. import ntsecuritycon
  109. import win32api
  110. import win32file
  111. import win32security
  112. token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32security.TOKEN_QUERY)
  113. user_sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
  114. # Act on the handle, never the name: GetFileSecurity/SetFileSecurity resolve a junction or symlink
  115. # to its target, so a swap after the lstat check would still redirect the grant.
  116. handle = win32file.CreateFile(str(path), _READ_CONTROL | _WRITE_DAC, _FILE_SHARE_ALL, None, _OPEN_EXISTING,
  117. _FILE_FLAG_BACKUP_SEMANTICS | _FILE_FLAG_OPEN_REPARSE_POINT, None)
  118. try:
  119. if expected is not None:
  120. # A parent swapped for a junction after the lstat checks resolves the name elsewhere.
  121. final = _strip_win32_prefix(win32file.GetFinalPathNameByHandle(handle, 0))
  122. if os.path.normcase(final.rstrip("\\")) != os.path.normcase(expected.rstrip("\\")):
  123. raise ReparsePointRefused(f"{path} resolves to {final}, not {expected}")
  124. info = win32file.GetFileInformationByHandle(handle)
  125. attributes, links = info[0], info[7]
  126. if attributes & FILE_ATTRIBUTE_REPARSE_POINT:
  127. raise ReparsePointRefused(f"{path} is a junction, symlink or other reparse point")
  128. if not attributes & FILE_ATTRIBUTE_DIRECTORY and links > 1:
  129. raise ReparsePointRefused(f"{path} is a hard link ({links} names); its other names may be outside")
  130. is_dir = bool(attributes & FILE_ATTRIBUTE_DIRECTORY)
  131. descriptor = win32security.GetKernelObjectSecurity(handle, win32security.DACL_SECURITY_INFORMATION)
  132. dacl = descriptor.GetSecurityDescriptorDacl()
  133. inherit = (win32security.OBJECT_INHERIT_ACE | win32security.CONTAINER_INHERIT_ACE) if is_dir else 0
  134. if dacl is not None:
  135. for index in range(dacl.GetAceCount()):
  136. (ace_type, flags, *_), mask, sid = dacl.GetAce(index)[:3]
  137. if (ace_type == win32security.ACCESS_ALLOWED_ACE_TYPE and sid == user_sid
  138. and mask & ntsecuritycon.FILE_ALL_ACCESS == ntsecuritycon.FILE_ALL_ACCESS
  139. and flags & inherit == inherit and not flags & win32security.INHERIT_ONLY_ACE):
  140. return False # already granted: never grow the DACL on repeat calls
  141. else:
  142. dacl = win32security.ACL()
  143. dacl.AddAccessAllowedAceEx(win32security.ACL_REVISION_DS, inherit, ntsecuritycon.FILE_ALL_ACCESS, user_sid)
  144. descriptor.SetSecurityDescriptorDacl(True, dacl, False)
  145. # The handle form of SetFileSecurity: same semantics (no propagation walk), no name resolution.
  146. win32security.SetKernelObjectSecurity(handle, win32security.DACL_SECURITY_INFORMATION, descriptor)
  147. return True
  148. finally:
  149. handle.Close()
  150. @functools.lru_cache(maxsize=1)
  151. def _whoami_sid() -> str:
  152. whoami = subprocess.run(["whoami", "/user", "/fo", "csv", "/nh"], capture_output=True, text=True,
  153. check=True, encoding="utf-8", errors="replace", timeout=30)
  154. sid = whoami.stdout.strip().rsplit(",", 1)[-1].strip().strip('"')
  155. if not sid.upper().startswith("S-1-"):
  156. raise OSError(f"could not resolve the current user SID from whoami: {whoami.stdout!r}")
  157. return sid
  158. def _grant_with_icacls(path: Path, is_dir: bool, expected: str | None = None,
  159. subtree_has_link: bool | None = None) -> None:
  160. """*subtree_has_link*: the caller's own walk already answered it (None: walk here)."""
  161. if expected is None:
  162. # icacls opens by name, so nothing pins the object between the checks and the write. Inside
  163. # the home the components were lstat-checked against a known root; with no expected root
  164. # (off-home, or a path whose home provenance was lost) there is nothing to check: refuse.
  165. raise ReparsePointRefused(f"{path} has no trusted root to check (icacls fallback, no pywin32)")
  166. if is_dir and subtree_has_link:
  167. raise ReparsePointRefused(f"{path} holds a junction, symlink or hard link (icacls fallback)")
  168. if is_dir and subtree_has_link is None:
  169. # icacls applies an inheritable ACE through SetNamedSecurityInfo, which also propagates it
  170. # down the existing subtree; refuse when that subtree holds a link it could descend into.
  171. # Walk the WHOLE subtree before judging: the generator appends a link it meets after its
  172. # last yield, so checking inside the loop admitted a tree whose only link came last. A
  173. # hard-linked file is refused too: the inherited ACE lands on its other names outside.
  174. nested: list[Path] = []
  175. linked = [entry for entry, entry_is_dir in iter_tree_without_reparse_points(path, nested)
  176. if not entry_is_dir and _hard_linked_file(entry)]
  177. if nested or linked:
  178. raise ReparsePointRefused(f"{(nested + linked)[0]} under {path} is a junction, symlink or hard "
  179. "link (icacls fallback)")
  180. ace = f"*{_whoami_sid()}:(OI)(CI)F" if is_dir else f"*{_whoami_sid()}:F"
  181. # /L: act on a symbolic link or junction itself, not its target (the lstat check already refused
  182. # one; this covers a swap between that check and icacls opening the path). Without pywin32 there
  183. # is no handle to pin, so *expected* cannot be re-checked here.
  184. subprocess.run(["icacls", str(path), "/grant", ace, "/Q", "/L"], capture_output=True,
  185. check=True, timeout=60)
  186. def _hard_linked_file(path: Path) -> bool:
  187. try:
  188. st = os.lstat(path)
  189. except OSError:
  190. return True
  191. return not stat.S_ISDIR(st.st_mode) and st.st_nlink > 1
  192. def _grant(path: Path, is_dir: bool = True, expected: str | None = None,
  193. subtree_has_link: bool | None = None) -> bool:
  194. """Grant the token's user full control on *path* itself; raise :class:`ReparsePointRefused`
  195. for a reparse point or hard-linked file (or, with *expected*, a handle that resolves anywhere
  196. else) and anything else on failure.
  197. Returns True when the existing children are still owed: the pywin32 write does not propagate,
  198. while the icacls fallback (``SetNamedSecurityInfo``) does, and refuses a dir holding a link."""
  199. if is_reparse_point(path) or _hard_linked_file(path):
  200. raise ReparsePointRefused(f"{path} is a junction, symlink, other reparse point or hard link")
  201. try:
  202. return _grant_with_pywin32(path, is_dir, expected) and is_dir
  203. except ImportError:
  204. _grant_with_icacls(path, is_dir, expected, subtree_has_link)
  205. return False
  206. def _components_below_home(path: Path) -> list[Path]:
  207. """*path* and each ancestor of it strictly below the Hermes home (lexically), outermost first;
  208. empty when *path* is not under the home. The home itself (and above) is the user's own choice
  209. and may legitimately be a link; an entry INSIDE it is what same-user code can swap."""
  210. try:
  211. from hermes_constants import get_hermes_home
  212. home = Path(os.path.abspath(get_hermes_home()))
  213. rel = Path(os.path.abspath(path)).relative_to(home)
  214. except (ImportError, ValueError, OSError):
  215. return []
  216. return [home.joinpath(*rel.parts[:i]) for i in range(1, len(rel.parts) + 1)]
  217. def _expected_final(path: Path) -> str | None:
  218. """Where *path* must resolve when nothing below the home is a link: the home's real path plus
  219. the relative parts. None off-home (only the leaf's own open-reparse check applies there)."""
  220. components = _components_below_home(path)
  221. if not components:
  222. return None
  223. home = components[0].parent
  224. return os.path.join(os.path.realpath(home), *Path(os.path.abspath(path)).relative_to(home).parts)
  225. def _warn_refused(path: Path, exc: BaseException) -> None:
  226. log.warning("Not granting the current user access to %s while elevated (%s): an elevated grant "
  227. "never follows a junction or link out of the Hermes home. If this is your own link, "
  228. "point HERMES_HOME (or the link) at the real directory.", path, exc)
  229. def _elevated(elevated: bool | None) -> bool:
  230. """The host fact every grant decision takes: *elevated* as passed, else probed (an elevated
  231. Windows process; :func:`process_is_elevated` is False on every other host)."""
  232. return process_is_elevated() if elevated is None else elevated
  233. def grant_user_access(path: str | Path, *, elevated: bool | None = None, repair_children: bool = False) -> bool:
  234. """Give the token's user an inheriting full-control ACE on *path* when this process is elevated.
  235. True when a grant was attempted and did not fail; False off Windows, when not elevated, when
  236. *path* is a junction/symlink/reparse point (refused, one warning), or when the grant failed
  237. (logged; the directory itself still exists). *elevated* defaults to the probed host fact.
  238. With *repair_children* (an existing dir an earlier elevated run may have filled), a write that
  239. does not propagate is followed by the same grant on everything already below *path*, never
  240. through a link; children are best-effort and never change the result."""
  241. if not _elevated(elevated):
  242. return False
  243. target = Path(path)
  244. try:
  245. for component in _components_below_home(target):
  246. if is_reparse_point(component):
  247. raise ReparsePointRefused(f"{component} is a junction, symlink or other reparse point")
  248. expected = _expected_final(target)
  249. children_owed = _grant(target, expected=expected)
  250. except ReparsePointRefused as exc:
  251. _warn_refused(target, exc)
  252. return False
  253. except Exception as exc: # health: allow BLE001 -- pywintypes.error is not an OSError; never fail the mkdir
  254. log.warning("Could not grant the current user access to %s created while elevated (%s); a "
  255. "non-elevated Hermes may not be able to use it. To repair, from an elevated prompt run: "
  256. 'icacls "%s" /reset /t', target, exc, target)
  257. return False
  258. if repair_children and children_owed:
  259. real = expected or os.path.realpath(target)
  260. skipped: list[Path] = []
  261. entries = [(p, d) for p, d in iter_tree_without_reparse_points(target, skipped) if p != target]
  262. _, _, failed = _grant_entries(target, real, entries, skipped)
  263. if failed:
  264. log.debug("Granting the existing entries under %s failed for %d, e.g. %s: %s",
  265. target, len(failed), *failed[0])
  266. return True
  267. def iter_tree_without_reparse_points(root: str | Path, skipped: list[Path]) -> Iterator[tuple[Path, bool]]:
  268. """Yield ``(path, is_dir)`` for *root* and everything under it, never entering or yielding a
  269. junction, symlink or other reparse point (each one is appended to *skipped* instead).
  270. ``os.walk`` is not enough: it follows directory junctions (``os.path.islink`` is False for one).
  271. Unreadable directories are skipped silently, like ``icacls /C``."""
  272. root = Path(root)
  273. if is_reparse_point(root):
  274. skipped.append(root)
  275. return
  276. stack = [root]
  277. while stack:
  278. directory = stack.pop()
  279. yield directory, True
  280. try:
  281. with os.scandir(directory) as entries:
  282. children = [Path(entry.path) for entry in entries]
  283. except OSError:
  284. continue
  285. for child in sorted(children):
  286. if is_reparse_point(child):
  287. skipped.append(child)
  288. elif child.is_dir():
  289. stack.append(child)
  290. else:
  291. yield child, False
  292. def grant_tree_user_access(root: str | Path, *, pin_root: bool = False,
  293. elevated: bool | None = None) -> tuple[int, list[Path], list[tuple[Path, str]]]:
  294. """Recursive :func:`grant_user_access` (the elevated post-update repair): grant the token's user
  295. full control on *root* and every directory and file under it, inheriting on directories.
  296. With *pin_root*, *root* is the operator's own choice (``HERMES_HOME``) and may itself be a link:
  297. it is resolved once and the walk runs below the real directory. A link BELOW it is still never
  298. entered or granted through.
  299. Returns ``(granted, skipped, failed)``: *skipped* are the reparse points (and hard-linked files)
  300. that were neither granted nor entered, *failed* the ``(path, reason)`` grants that raised. A
  301. no-op ``(0, [], [])`` off Windows or when not elevated (*elevated* defaults to the probe)."""
  302. if not _elevated(elevated):
  303. return 0, [], []
  304. root = Path(os.path.realpath(root) if pin_root else os.path.abspath(root))
  305. skipped: list[Path] = []
  306. entries = list(iter_tree_without_reparse_points(root, skipped))
  307. granted, skipped, failed = _grant_entries(root, os.path.realpath(root), entries, skipped)
  308. if skipped:
  309. log.warning("Elevated ACL repair skipped %d junction/symlink/hard-link entr%s under %s (never "
  310. "granted through): %s", len(skipped), "y" if len(skipped) == 1 else "ies", root,
  311. ", ".join(str(p) for p in skipped[:5]) + (" ..." if len(skipped) > 5 else ""))
  312. return granted, skipped, failed
  313. def _grant_entries(root: Path, real_root: str, entries: list[tuple[Path, bool]],
  314. skipped: list[Path]) -> tuple[int, list[Path], list[tuple[Path, str]]]:
  315. """Grant each walked entry on its own (the pywin32 write does not propagate). The ONE walk
  316. that produced *entries* and *skipped* also decides which dirs hold a link, so the icacls
  317. fallback never re-walks a subtree per directory (it refuses exactly those dirs, as before)."""
  318. linked = {root, *skipped} # a skipped link, or the root itself when it was skipped
  319. linked.update(p for p, is_dir in entries if not is_dir and _hard_linked_file(p))
  320. holds_link: set[Path] = set()
  321. for bad in linked - {root}:
  322. holds_link.update(parent for parent in bad.parents if parent == root or root in parent.parents)
  323. if root in skipped:
  324. holds_link.add(root)
  325. granted, failed = 0, []
  326. for path, is_dir in entries:
  327. try:
  328. _grant(path, is_dir, os.path.join(real_root, *path.relative_to(root).parts),
  329. subtree_has_link=is_dir and path in holds_link)
  330. except ReparsePointRefused:
  331. skipped.append(path)
  332. except Exception as exc: # health: allow BLE001 -- pywintypes.error is not an OSError; keep going like /C
  333. failed.append((path, str(exc) or type(exc).__name__))
  334. else:
  335. granted += 1
  336. return granted, skipped, failed
  337. # Dir OBJECTS this elevated process already granted, as ``(path, volume serial, file id)`` from
  338. # ``os.lstat`` (st_dev / st_ino are exactly those on Windows): the grant reads and may rewrite a
  339. # DACL, and the callers (log handlers, lock acquires) re-enter on hot paths. Keyed by identity, not
  340. # name: media release deletes a digest dir and the next capture recreates it at the same path.
  341. _granted: set[tuple[Path, int, int]] = set()
  342. def _identity(path: Path) -> tuple[Path, int, int] | None:
  343. try:
  344. st = os.lstat(path)
  345. except OSError:
  346. return None
  347. return path, st.st_dev, st.st_ino
  348. def make_user_dir(path: str | Path, mode: int = 0o777, *, parents: bool = False, exist_ok: bool = False,
  349. elevated: bool | None = None) -> Path:
  350. """``Path.mkdir`` (same arguments and defaults) that keeps an elevated Windows creation usable
  351. by the same user unelevated.
  352. Off Windows or unelevated this is ``Path.mkdir`` and nothing else. Elevated, every directory
  353. this call created (missing parents included) is granted the user's inheriting full-control ACE,
  354. and an existing leaf (the repair case) once per directory object per process, except that a
  355. component that is a junction/symlink/reparse point stops the grants with one warning. An
  356. existing leaf without ``exist_ok`` is still granted before the ``FileExistsError``. *elevated*
  357. is the host fact (default: probed); production passes nothing."""
  358. target = Path(path)
  359. if not _elevated(elevated):
  360. target.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
  361. return target
  362. created = []
  363. probe = target
  364. while not probe.exists() and probe.parent != probe:
  365. created.append(probe)
  366. probe = probe.parent
  367. try:
  368. target.mkdir(mode=mode, parents=parents, exist_ok=exist_ok)
  369. except FileExistsError:
  370. # ``Path.mkdir`` contract: an existing leaf still raises without exist_ok. The directory an
  371. # earlier elevated run left is repaired first, so the caller's error is never the reason a
  372. # non-elevated Hermes stays locked out of it.
  373. if target.is_dir() and not is_reparse_point(target):
  374. _grant_dirs(target, [target])
  375. raise
  376. _grant_dirs(target, list(reversed(created or [target])), fresh=set(created))
  377. return target
  378. def _grant_dirs(target: Path, to_grant: list[Path], fresh: set[Path] = frozenset()) -> None:
  379. """Grant *to_grant*; a dir in *fresh* (this call created it) is always granted, an existing
  380. one once per verified object identity."""
  381. # A junction/symlink planted at (or swapped in for) the leaf, a created component, or any
  382. # existing ancestor inside the home: grant nothing, one warning (nothing past it is in the home).
  383. for component in dict.fromkeys([*_components_below_home(target), *to_grant]):
  384. if is_reparse_point(component):
  385. _warn_refused(component, ReparsePointRefused("junction, symlink or other reparse point"))
  386. return
  387. for directory in to_grant:
  388. key = _identity(directory)
  389. if key is None or (directory not in fresh and key in _granted):
  390. continue
  391. if grant_user_access(directory, elevated=True, repair_children=directory not in fresh):
  392. _granted.add(key)
  393. def unusable_dir_remedy(path: str | Path, *, windows: bool | None = None) -> str:
  394. """The one-line repair for a directory this process may not use (owner from an elevated run).
  395. *windows* is the host fact (default: this host)."""
  396. if (os.name == "nt") if windows is None else windows:
  397. return f'from an elevated prompt run: icacls "{path}" /reset /t'
  398. return f'run: sudo chown -R "$(id -un)" "{path}"'