runtime_self_protection.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. """The running Hermes runtime's own interpreter/venv is not agent-deletable.
  2. Deleting the Python interpreter the current process boots from — or the base
  3. interpreter its venv depends on — bricks the install: the next boot fails with
  4. ``uv trampoline failed to spawn Python child process`` and no amount of agent
  5. work can repair it, because the agent itself no longer starts (#58748). The
  6. same applies to overwriting the interpreter through the file tools.
  7. Two questions, one coordinate system:
  8. * :func:`command_deletes_runtime` — would a shell command delete a protected
  9. path? Wired into the approval floor (``tools.approval._floor_block``), so it
  10. cannot be bypassed by yolo / approvals.mode=off / cron approve mode.
  11. * :func:`is_protected_path` — is a filesystem path protected? Wired into the
  12. file-safety write classifier, covering write/patch/move/delete.
  13. Protected set (all resolved through the same normalizer so shell spellings —
  14. native, git-bash ``/c/...``, WSL ``/mnt/c/...``, ``$HOME`` — compare equal):
  15. * ``sys.executable`` and ``sys.prefix`` (the runtime's own venv),
  16. * the base interpreter from ``pyvenv.cfg``'s ``home =`` / ``sys._base_executable``,
  17. * the uv-managed install directory holding that base (matched by version for
  18. ``uv python uninstall``).
  19. Deliberately NOT protected: any other venv or interpreter on the machine — the
  20. agent may freely manage project environments. Only the runtime it is itself
  21. running from is off-limits.
  22. """
  23. from __future__ import annotations
  24. import os
  25. import re
  26. import shlex
  27. import sys
  28. from functools import lru_cache
  29. from pathlib import Path
  30. from typing import Optional
  31. # Split a command line into individually-analyzable commands. Newlines, `;`,
  32. # `&&`, `||` and `|` each start a fresh command whose own name decides whether
  33. # it deletes anything.
  34. _SEGMENT_SPLIT_RE = re.compile(r"\n|&&|\|\||[;|]")
  35. # Words whose argument tail is a *different* command (sudo rm ...) or an
  36. # environment assignment prefix (FOO=1 rm ...).
  37. _COMMAND_PREFIXES = frozenset({"sudo", "command", "nohup", "exec", "env", "nice", "time"})
  38. # Direct-deletion command names (basename, lowercase). `rm` covers POSIX and
  39. # git-bash; the Windows-native spellings cover cmd (`rd`, `del`, `rmdir /s`)
  40. # and PowerShell (`Remove-Item`, and its `ri`/`rm`/`del`/`erase` aliases).
  41. _DELETING_COMMANDS = frozenset({
  42. "rm", "rmdir", "rd", "del", "erase", "remove-item", "ri",
  43. })
  44. # `find <roots...> -delete` (or `-exec rm ...`) deletes its search roots.
  45. _FIND_DELETE_RE = re.compile(r"(?:^|\s)-(?:delete|exec\s+rm\b)", re.IGNORECASE)
  46. # uv-managed install layout: .../uv/python/cpython-3.14.7-arm64-apple-darwin/...
  47. _UV_INSTALL_DIR_RE = re.compile(
  48. r"(?i)(?P<root>.*[/\\](?:uv[/\\])?python[/\\]cpython-(?P<version>\d+(?:\.\d+)*)(?:[-_][^/\\]*)?)(?:[/\\].*)?$"
  49. )
  50. _WIN_DRIVE_FROM_POSIX_RE = re.compile(r"^/(?:(mnt)/)?([a-zA-Z])/(.+)$")
  51. def _normalize_path(raw: str) -> str:
  52. """One canonical form for both shell spellings and runtime paths.
  53. Expands ``~``/``$HOME``, maps git-bash (``/c/...``) and WSL (``/mnt/c/...``)
  54. drive forms to native Windows paths, then ``realpath``s so symlink mirrors
  55. (macOS ``/private``) and relocated installs compare equal. Missing tails are
  56. fine: POSIX ``realpath`` resolves the existing prefix lexically.
  57. """
  58. path = str(raw or "").strip()
  59. if not path:
  60. return ""
  61. if len(path) >= 2 and path[0] == path[-1] and path[0] in "\"'":
  62. path = path[1:-1]
  63. try:
  64. path = os.path.expandvars(os.path.expanduser(path))
  65. except Exception:
  66. try:
  67. path = os.path.expanduser(path)
  68. except Exception:
  69. pass
  70. if os.name == "nt":
  71. m = _WIN_DRIVE_FROM_POSIX_RE.match(path)
  72. if m:
  73. path = f"{m.group(2)}:\\{m.group(3)}"
  74. path = path.replace("/", "\\")
  75. try:
  76. return os.path.normcase(os.path.realpath(os.path.normpath(path)))
  77. except Exception:
  78. return os.path.normcase(os.path.normpath(path))
  79. def _pyvenv_home(prefix: str) -> str:
  80. """The ``home =`` base-interpreter directory from ``<prefix>/pyvenv.cfg``."""
  81. try:
  82. lines = (Path(prefix) / "pyvenv.cfg").read_text(encoding="utf-8-sig", errors="replace").splitlines()
  83. except Exception:
  84. return ""
  85. for line in lines:
  86. if "=" not in line:
  87. continue
  88. key, value = line.split("=", 1)
  89. if key.strip().lower() == "home":
  90. return value.strip()
  91. return ""
  92. @lru_cache(maxsize=8)
  93. def _protected_snapshot(executable: str, prefix: str) -> tuple[tuple[str, str], ...]:
  94. """Resolved ``(path, description)`` pairs for the runtime's own interpreter.
  95. Cached per (executable, prefix) — the pair cannot change while a process
  96. runs, and keying on the inputs lets tests swap ``sys`` attributes freely.
  97. """
  98. entries: list[tuple[str, str]] = []
  99. exe = _normalize_path(executable)
  100. if exe:
  101. entries.append((exe, "the Python interpreter this Hermes runtime is running from"))
  102. venv = _normalize_path(prefix)
  103. if venv and venv != exe:
  104. entries.append((venv, "this Hermes runtime's own virtualenv"))
  105. base_dir = _normalize_path(_pyvenv_home(prefix)) or _normalize_path(getattr(sys, "_base_executable", "") or "")
  106. if base_dir:
  107. entries.append((base_dir, "the base interpreter this Hermes venv depends on"))
  108. m = _UV_INSTALL_DIR_RE.match(base_dir.replace("\\", "/"))
  109. if m:
  110. uv_root = _normalize_path(m.group("root"))
  111. if uv_root:
  112. entries.append((uv_root, f"the uv-managed Python install this Hermes venv depends on ({m.group('version')})"))
  113. return tuple((path, desc) for path, desc in entries if path)
  114. def _protected() -> tuple[tuple[str, str], ...]:
  115. return _protected_snapshot(getattr(sys, "executable", "") or "", getattr(sys, "prefix", "") or "")
  116. def _overlaps(a: str, b: str) -> bool:
  117. """True when ``a`` and ``b`` are the same path or one is an ancestor of the other."""
  118. if not a or not b:
  119. return False
  120. sep = os.sep
  121. return a == b or a.startswith(b + sep) or b.startswith(a + sep)
  122. def split_entry(path: str) -> tuple[str, str]:
  123. """``os.path.split`` for a directory entry, trailing separators and ``.`` components
  124. dropped first: an empty or ``.`` leaf (``dir/link/``, ``dir/link/.``) would make entry
  125. checks degenerate to the link's target, while pathlib/rm still act on ``link``.
  126. A bare root (``/``, ``C:\\``) is kept as is."""
  127. drive, tail = os.path.splitdrive(path)
  128. parent, leaf = os.path.split(drive + (tail.rstrip(os.sep + (os.altsep or "")) or tail[:1]))
  129. if leaf == "." and parent:
  130. return split_entry(parent)
  131. return parent, leaf
  132. def is_protected_path(path: str, *, follow: bool = True) -> Optional[str]:
  133. """Description of the protected runtime path ``path`` touches, else ``None``.
  134. ``follow=False`` keeps the final component unresolved (the entry itself, for
  135. ops that unlink/rename a symlink rather than its target)."""
  136. if follow:
  137. resolved = _normalize_path(path)
  138. else:
  139. parent, leaf = split_entry(path)
  140. resolved = _normalize_path(parent or ".")
  141. resolved = resolved and os.path.normcase(os.path.join(resolved, leaf))
  142. if not resolved:
  143. return None
  144. for protected, description in _protected():
  145. if _overlaps(resolved, protected):
  146. return description
  147. return None
  148. def _split_words(segment: str) -> list[str]:
  149. try:
  150. return shlex.split(segment)
  151. except ValueError:
  152. return segment.split()
  153. def _strip_prefixes(words: list[str]) -> list[str]:
  154. out = list(words)
  155. while out:
  156. first = out[0]
  157. if first in _COMMAND_PREFIXES:
  158. out = out[1:]
  159. continue
  160. if "=" in first and not first.startswith(("-", "/")) and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", first):
  161. out = out[1:]
  162. continue
  163. break
  164. return out
  165. def _version_spec_matches(spec: str, version: str, uv_root_name: str) -> bool:
  166. """``uv python uninstall`` spec against the running base's version/dir."""
  167. spec = spec.strip().lower()
  168. if not spec:
  169. return False
  170. if spec in ("--all", "-a", "all"):
  171. return True
  172. if spec.startswith("-"):
  173. return False
  174. if uv_root_name.lower().startswith(spec):
  175. return True
  176. return spec == version or (version.startswith(spec) and version[len(spec):len(spec) + 1] == ".")
  177. def _uv_uninstall_target(words: list[str]) -> Optional[str]:
  178. """Description when ``uv python uninstall`` would remove the running base."""
  179. protected = _protected()
  180. uv_entries = [
  181. (root, desc) for root, desc in protected
  182. if desc.startswith("the uv-managed Python install")
  183. ]
  184. if not uv_entries:
  185. return None
  186. lowered = [w.lower() for w in words]
  187. try:
  188. python_at = lowered.index("python")
  189. uninstall_at = lowered.index("uninstall", python_at + 1)
  190. except ValueError:
  191. return None
  192. specs = words[uninstall_at + 1:]
  193. for root, description in uv_entries:
  194. m = _UV_INSTALL_DIR_RE.match(root.replace("\\", "/"))
  195. version = m.group("version") if m else ""
  196. root_name = os.path.basename(root)
  197. if any(_version_spec_matches(spec, version, root_name) for spec in specs):
  198. return description
  199. return None
  200. def command_deletes_runtime(command: str) -> Optional[str]:
  201. """Description of the runtime path ``command`` would delete, else ``None``.
  202. Covers ``rm``/``rmdir``/``rd``/``del``/``erase``/``Remove-Item`` (any flags —
  203. the interpreter is a file, so no recursion is needed to kill it), the
  204. ``find <roots> -delete`` form, and ``uv python uninstall``. Known limits:
  205. paths assembled by ``xargs``/command substitution are invisible here, and
  206. ``shutil.rmtree`` inside executed *code* is a different sandbox.
  207. """
  208. if not command or not command.strip():
  209. return None
  210. protected = _protected()
  211. if not protected:
  212. return None
  213. for segment in _SEGMENT_SPLIT_RE.split(command):
  214. words = _strip_prefixes(_split_words(segment))
  215. if not words:
  216. continue
  217. name = os.path.basename(words[0]).lower()
  218. if name == "uv":
  219. target = _uv_uninstall_target(words)
  220. if target:
  221. return target
  222. continue
  223. if name == "find" and _FIND_DELETE_RE.search(segment):
  224. for word in words[1:]:
  225. if not word.startswith("-"):
  226. hit = is_protected_path(word)
  227. if hit:
  228. return hit
  229. continue
  230. if name not in _DELETING_COMMANDS:
  231. continue
  232. for word in words[1:]:
  233. if word.startswith("-"):
  234. continue
  235. hit = is_protected_path(word)
  236. if hit:
  237. return hit
  238. return None