windows_ssh_runtime.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. """Native Windows trust boundary for Desktop SSH backend lifecycle."""
  2. from __future__ import annotations
  3. import contextlib
  4. import importlib
  5. import json
  6. import os
  7. import re
  8. import subprocess
  9. import sys
  10. from pathlib import Path
  11. from types import SimpleNamespace
  12. from typing import Any
  13. from hermes_constants import get_default_hermes_root
  14. _HEX32 = re.compile(r"[0-9a-f]{32}\Z")
  15. _HEX16 = re.compile(r"[0-9a-f]{16}\Z")
  16. _HEX64 = re.compile(r"[0-9a-f]{64}\Z")
  17. _MAX_JSON = 1024 * 1024
  18. _MAX_LOG = 512 * 1024
  19. _OPEN_REPARSE_POINT = 0x00200000
  20. _DELETE_ON_CLOSE = 0x04000000
  21. _MOVE_REPLACE_EXISTING = 0x00000001
  22. _MOVE_WRITE_THROUGH = 0x00000008
  23. def _win32() -> Any:
  24. """Namespace of the pywin32 modules (ntsecuritycon, pywintypes, win32api, win32con, win32file,
  25. win32security); import is deferred so the module imports on non-Windows hosts."""
  26. if sys.platform != "win32":
  27. raise RuntimeError("Windows SSH runtime is only available on Windows")
  28. names = ("ntsecuritycon", "pywintypes", "win32api", "win32con", "win32file", "win32security")
  29. return SimpleNamespace(**{name: importlib.import_module(name) for name in names})
  30. def _check(pattern: re.Pattern, value: str, message: str) -> str:
  31. if not pattern.fullmatch(value or ""):
  32. raise ValueError(message)
  33. return value
  34. def _ownership(value: str) -> str:
  35. return _check(_HEX32, value, "invalid ownership ID")
  36. def _nonce(value: str) -> str:
  37. return _check(_HEX16, value, "invalid spawn nonce")
  38. def _root() -> Path:
  39. # The helper uploads the token before the child applies `--profile`; read_token() runs after
  40. # profile activation. Anchor both to the machine root so a named profile (or custom
  41. # HERMES_HOME) cannot move the reader away from the helper's token.
  42. return get_default_hermes_root() / "desktop-ssh"
  43. def _directory(ownership_id: str) -> Path:
  44. return _root() / _ownership(ownership_id)
  45. def _token_path(ownership_id: str, spawn_nonce: str) -> Path:
  46. return _directory(ownership_id) / f"{_nonce(spawn_nonce)}.token"
  47. def _log_path(ownership_id: str, spawn_nonce: str) -> Path:
  48. return _directory(ownership_id) / f"{_nonce(spawn_nonce)}.log"
  49. def _lock_path(ownership_id: str) -> Path:
  50. return _directory(ownership_id) / "backend.lock.json"
  51. def _current_sid():
  52. w = _win32()
  53. token = w.win32security.OpenProcessToken(w.win32api.GetCurrentProcess(), w.win32con.TOKEN_QUERY)
  54. return w.win32security.GetTokenInformation(token, w.win32security.TokenUser)[0]
  55. def _system_sid():
  56. return _win32().win32security.ConvertStringSidToSid("S-1-5-18")
  57. def _sid_str(sid) -> str:
  58. return _win32().win32security.ConvertSidToStringSid(sid)
  59. def _security_attributes():
  60. win32security = _win32().win32security
  61. owner = _sid_str(_current_sid())
  62. # D:P blocks inherited grants at creation. SDDL also avoids pywin32 311's
  63. # SetSecurityDescriptorControl argument-width bug on ARM64.
  64. descriptor = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
  65. f"O:{owner}D:P(A;;FA;;;{owner})(A;;FA;;;SY)", win32security.SDDL_REVISION_1)
  66. attributes = win32security.SECURITY_ATTRIBUTES()
  67. attributes.SECURITY_DESCRIPTOR = descriptor
  68. return attributes
  69. def _allowed_sids():
  70. return {_sid_str(_current_sid()), _sid_str(_system_sid())}
  71. def _verify_security(handle) -> None:
  72. win32security = _win32().win32security
  73. info = win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
  74. descriptor = win32security.GetSecurityInfo(handle, win32security.SE_FILE_OBJECT, info)
  75. allowed = _allowed_sids()
  76. if _sid_str(descriptor.GetSecurityDescriptorOwner()) not in allowed:
  77. raise OSError("Windows SSH runtime object has the wrong owner")
  78. dacl = descriptor.GetSecurityDescriptorDacl()
  79. if dacl is None:
  80. raise OSError("Windows SSH runtime object has a null DACL")
  81. allow_types = {
  82. win32security.ACCESS_ALLOWED_ACE_TYPE,
  83. win32security.ACCESS_ALLOWED_OBJECT_ACE_TYPE,
  84. getattr(win32security, "ACCESS_ALLOWED_CALLBACK_ACE_TYPE", 9),
  85. getattr(win32security, "ACCESS_ALLOWED_CALLBACK_OBJECT_ACE_TYPE", 11)}
  86. for index in range(dacl.GetAceCount()):
  87. ace = dacl.GetAce(index)
  88. if ace[0][0] in allow_types and ace[1] and _sid_str(ace[-1]) not in allowed:
  89. raise OSError("Windows SSH runtime object has a permissive DACL")
  90. def _open(path: Path, access: int, creation: int, flags: int, share: int = 0):
  91. win32file = _win32().win32file
  92. handle = win32file.CreateFile(str(path), access, share, _security_attributes(), creation, flags, None)
  93. try:
  94. actual = win32file.GetFinalPathNameByHandle(handle, 0).removeprefix("\\\\?\\")
  95. if os.path.normcase(actual) != os.path.normcase(os.path.abspath(str(path))):
  96. raise OSError("Windows SSH runtime handle escaped its expected path")
  97. if win32file.GetFileInformationByHandle(handle)[0] & 0x400: # FILE_ATTRIBUTE_REPARSE_POINT
  98. raise OSError("Windows SSH runtime path contains a reparse point")
  99. _verify_security(handle)
  100. return handle
  101. except BaseException:
  102. win32file.CloseHandle(handle)
  103. raise
  104. def _open_existing(path: Path, access: int, extra_flags: int = 0, share: int = 0):
  105. """``_open`` an existing file (FILE_ATTRIBUTE_NORMAL | reparse guard); None when it is missing."""
  106. w = _win32()
  107. try:
  108. return _open(path, access, w.win32con.OPEN_EXISTING,
  109. w.win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT | extra_flags, share)
  110. except w.pywintypes.error as exc:
  111. if exc.winerror in (2, 3):
  112. return None
  113. raise
  114. def _read_shared(path: Path, limit: int, share: int) -> bytes | None:
  115. """Read up to ``limit`` bytes of ``path`` opened read-only with ``share``; None when missing."""
  116. w = _win32()
  117. handle = _open_existing(path, w.win32con.GENERIC_READ | w.win32con.READ_CONTROL, share=share)
  118. if handle is None:
  119. return None
  120. try:
  121. return w.win32file.ReadFile(handle, limit)[1]
  122. finally:
  123. w.win32file.CloseHandle(handle)
  124. def _write_new(path: Path, data: bytes, share: int = 0) -> None:
  125. """Create ``path`` (CREATE_NEW), write ``data`` and flush."""
  126. w = _win32()
  127. win32con, win32file = w.win32con, w.win32file
  128. handle = _open(path, win32con.GENERIC_WRITE | win32con.READ_CONTROL, win32con.CREATE_NEW,
  129. win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT, share)
  130. try:
  131. win32file.WriteFile(handle, data)
  132. win32file.FlushFileBuffers(handle)
  133. finally:
  134. win32file.CloseHandle(handle)
  135. def write_private_file(path: Path, data: bytes) -> None:
  136. """Create/replace ``path`` with an owner+SYSTEM-only protected DACL (Windows only).
  137. The repo's writer for any credential landing on a Windows disk: ``os.open(..., 0o600)`` sets
  138. no ACLs there at all, so a token written that way inherits whatever the parent directory
  139. grants. CreateFile ignores the security descriptor when the file already exists, so an
  140. existing file is removed first rather than re-opened — which also avoids ``os.replace``
  141. failing against a reader that still holds the old file open.
  142. """
  143. with contextlib.suppress(FileNotFoundError):
  144. os.unlink(str(path))
  145. _write_new(path, data)
  146. def _ensure_directory(path: Path) -> None:
  147. w = _win32()
  148. pywintypes, win32con, win32file = w.pywintypes, w.win32con, w.win32file
  149. if path.parent not in (Path(path.anchor), path) and not path.parent.exists():
  150. _ensure_directory(path.parent)
  151. if not path.exists():
  152. try:
  153. win32file.CreateDirectory(str(path), _security_attributes())
  154. except pywintypes.error as exc:
  155. if exc.winerror != 183:
  156. raise
  157. handle = _open(path, win32con.GENERIC_READ | win32con.READ_CONTROL, win32con.OPEN_EXISTING,
  158. win32con.FILE_FLAG_BACKUP_SEMANTICS | _OPEN_REPARSE_POINT,
  159. win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE)
  160. win32file.CloseHandle(handle)
  161. def _ensure_scope(ownership_id: str) -> Path:
  162. _ensure_directory(_root())
  163. directory = _directory(ownership_id)
  164. _ensure_directory(directory)
  165. return directory
  166. def upload_token(ownership_id: str, spawn_nonce: str, token: bytes) -> dict[str, Any]:
  167. if len(token) != 64 or not _HEX64.fullmatch(token.decode("ascii", errors="ignore")):
  168. raise ValueError("invalid session token")
  169. _ensure_scope(ownership_id)
  170. path = _token_path(ownership_id, spawn_nonce)
  171. try:
  172. _write_new(path, token)
  173. except BaseException:
  174. path.unlink(missing_ok=True)
  175. raise
  176. return {"path": str(path)}
  177. def read_token(path_value: str) -> str:
  178. w = _win32()
  179. win32con, win32file = w.win32con, w.win32file
  180. path = Path(path_value)
  181. try:
  182. relative = path.relative_to(_root())
  183. except ValueError as exc:
  184. raise SystemExit("--ssh-session-token-file must be under the desktop-ssh directory") from exc
  185. if len(relative.parts) != 2 or not _HEX32.fullmatch(relative.parts[0]) or not re.fullmatch(r"[0-9a-f]{16}\.token", relative.parts[1]):
  186. raise SystemExit("--ssh-session-token-file has an invalid runtime path")
  187. flags = win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT | _DELETE_ON_CLOSE
  188. try:
  189. handle = _open(path, win32con.GENERIC_READ | win32con.READ_CONTROL | win32con.DELETE,
  190. win32con.OPEN_EXISTING, flags)
  191. except Exception as exc:
  192. raise SystemExit("--ssh-session-token-file is not accessible") from exc
  193. try:
  194. _, data = win32file.ReadFile(handle, 65)
  195. finally:
  196. win32file.CloseHandle(handle)
  197. token = data.decode("ascii", errors="ignore")
  198. if len(token) != 64 or not _HEX64.fullmatch(token):
  199. raise SystemExit("--ssh-session-token-file contains an invalid token")
  200. return token
  201. def _read_json_stdin() -> dict[str, Any]:
  202. raw = sys.stdin.buffer.read(_MAX_JSON + 1)
  203. if len(raw) > _MAX_JSON:
  204. raise ValueError("runtime payload is too large")
  205. parsed = json.loads(raw)
  206. if not isinstance(parsed, dict):
  207. raise ValueError("runtime payload must be an object")
  208. return parsed
  209. def read_lock(ownership_id: str) -> dict[str, Any] | None:
  210. win32con = _win32().win32con
  211. _ensure_scope(ownership_id)
  212. data = _read_shared(_lock_path(ownership_id), _MAX_JSON + 1, win32con.FILE_SHARE_READ)
  213. if data is None or len(data) > _MAX_JSON:
  214. return None
  215. try:
  216. parsed = json.loads(data)
  217. except (UnicodeDecodeError, json.JSONDecodeError):
  218. return None
  219. return parsed if isinstance(parsed, dict) else None
  220. def _lock_record(ownership_id: str, payload: dict[str, Any]) -> bytes:
  221. # The backend's owner watchdog only trusts a lock whose logPath ends in /<ownershipId>/<nonce>.log
  222. # (dashboard_procs._valid_lockfile_payload); without it a superseded Windows backend never retires.
  223. record = {**payload, "logPath": _log_path(ownership_id, str(payload.get("spawnNonce"))).as_posix()}
  224. data = json.dumps(record, separators=(",", ":")).encode()
  225. if len(data) > _MAX_JSON:
  226. raise ValueError("lock payload is too large")
  227. return data
  228. def write_lock(ownership_id: str, payload: dict[str, Any]) -> None:
  229. win32file = _win32().win32file
  230. directory = _ensure_scope(ownership_id)
  231. data = _lock_record(ownership_id, payload)
  232. temporary = directory / f".{os.urandom(8).hex()}.lock.tmp"
  233. _write_new(temporary, data)
  234. win32file.MoveFileEx(str(temporary), str(_lock_path(ownership_id)),
  235. _MOVE_REPLACE_EXISTING | _MOVE_WRITE_THROUGH)
  236. def remove_artifact(path: Path) -> bool:
  237. w = _win32()
  238. handle = _open_existing(path, w.win32con.DELETE | w.win32con.READ_CONTROL, _DELETE_ON_CLOSE)
  239. if handle is None:
  240. return False
  241. w.win32file.CloseHandle(handle)
  242. return True
  243. def process_state(pid: int, creation_time_ns: int, hermes_path: str, spawn_nonce: str) -> dict[str, Any]:
  244. import psutil
  245. _nonce(spawn_nonce)
  246. try:
  247. process = psutil.Process(pid)
  248. actual_creation = int(process.create_time() * 1_000_000_000)
  249. argv = process.cmdline()
  250. except psutil.NoSuchProcess as exc:
  251. return {"alive": False, "owned": False, "indeterminate": False, "reason": type(exc).__name__}
  252. except psutil.AccessDenied as exc:
  253. return {"alive": True, "owned": False, "indeterminate": True, "reason": type(exc).__name__}
  254. if actual_creation != creation_time_ns:
  255. return {"alive": False, "owned": False, "indeterminate": False, "reason": "creation-time",
  256. "actualCreationTimeNs": str(actual_creation), "expectedCreationTimeNs": str(creation_time_ns)}
  257. if not argv:
  258. return {"alive": True, "owned": False, "indeterminate": True, "reason": "argv-unavailable"}
  259. expected = os.path.normcase(os.path.abspath(hermes_path))
  260. arg0 = os.path.normcase(os.path.abspath(argv[0]))
  261. # argv[0] is the hermes exe or (normally) the base Python, whose path varies by venv/uv
  262. # layout — so match "a python running our module" (`-c` bootstrap or plain `-m`). Identity
  263. # is anchored by the unforgeable creation-time + secret owner-nonce below.
  264. is_python = os.path.basename(arg0).startswith("python")
  265. from gateway.status_inline_source import inline_bootstrap_argv
  266. logical_argv = inline_bootstrap_argv(argv) or argv
  267. launches_module = logical_argv[1:3] == ["-m", "hermes_cli.main"]
  268. executable_match = arg0 == expected or (is_python and launches_module)
  269. try:
  270. serve = logical_argv.index("serve")
  271. owner = logical_argv.index("--ssh-owner-nonce", serve + 1)
  272. owned = executable_match and "--isolated" in logical_argv[serve + 1:] and logical_argv[owner + 1] == spawn_nonce
  273. except (ValueError, IndexError):
  274. owned = False
  275. return {"alive": process.is_running(), "owned": owned, "indeterminate": False,
  276. "creationTimeNs": str(actual_creation), "reason": "owned" if owned else "argv",
  277. "argv": argv[:20], "expectedExecutable": expected}
  278. def terminate_owned(pid: int, creation_time_ns: int, hermes_path: str, spawn_nonce: str) -> bool:
  279. state = process_state(pid, creation_time_ns, hermes_path, spawn_nonce)
  280. if not state["alive"] or not state["owned"]:
  281. return False
  282. import psutil
  283. process = psutil.Process(pid)
  284. if int(process.create_time() * 1_000_000_000) != creation_time_ns:
  285. return False
  286. process.terminate()
  287. try:
  288. process.wait(5)
  289. except psutil.TimeoutExpired:
  290. process.kill()
  291. process.wait(5)
  292. return True
  293. def _resolve_direct_command(hermes_path: str) -> list[str]:
  294. """Ask the configured installation for its direct, boot-selecting command.
  295. The port owner must be the process we lock, not a console-launcher child.
  296. No assumption about python.exe beside an external bin launcher is valid.
  297. """
  298. out = subprocess.run([hermes_path, "--print-runtime-command"], capture_output=True,
  299. text=True, encoding="utf-8", errors="replace", timeout=30, check=False)
  300. if out.returncode != 0:
  301. raise ValueError("could not resolve Hermes runtime; refresh this installation's launcher")
  302. try:
  303. command = json.loads(out.stdout)
  304. except ValueError as exc:
  305. raise ValueError("Hermes launcher did not report a runtime command") from exc
  306. if (not isinstance(command, list) or not command
  307. or not all(isinstance(part, str) and "\x00" not in part for part in command)
  308. or not os.path.isabs(command[0]) or not os.path.isfile(command[0])):
  309. raise ValueError("Hermes launcher reported an invalid runtime command")
  310. return command
  311. def _spawn_env(payload: dict[str, Any]) -> dict[str, str]:
  312. """The serve's environment. A Desktop dev build's renderer is an http origin the backend trusts
  313. only from the HERMES_DESKTOP_DEV_SERVER it inherits, so the payload's ``devServer`` is handed
  314. down exactly as the POSIX spawn command does; without one the variable is not set at all."""
  315. dev_server = str(payload.get("devServer") or "")
  316. if len(dev_server) > 2048 or any(ch in dev_server for ch in "\x00\r\n"):
  317. raise ValueError("invalid devServer")
  318. env = dict(os.environ)
  319. env.pop("VIRTUAL_ENV", None)
  320. env.pop("PYTHONPATH", None)
  321. env.pop("HERMES_DESKTOP_DEV_SERVER", None)
  322. if dev_server:
  323. env["HERMES_DESKTOP_DEV_SERVER"] = dev_server
  324. return env
  325. def spawn_backend(payload: dict[str, Any]) -> dict[str, Any]:
  326. ownership_id = _ownership(str(payload["ownershipId"]))
  327. spawn_nonce = _nonce(str(payload["spawnNonce"]))
  328. configured_path = str(payload["hermesPath"])
  329. if not os.path.isabs(configured_path):
  330. raise ValueError("Hermes path must be absolute")
  331. hermes_path = os.path.abspath(configured_path)
  332. token_path = str(_token_path(ownership_id, spawn_nonce))
  333. profile = str(payload.get("profile") or "")
  334. if len(profile) > 256 or any(ch in profile for ch in "\x00\r\n"):
  335. raise ValueError("invalid profile")
  336. args = _resolve_direct_command(hermes_path)
  337. if profile:
  338. args.extend(["--profile", profile])
  339. args.extend(["serve", "--isolated", "--host", "127.0.0.1", "--port", "0",
  340. "--ssh-session-token-file", token_path, "--ssh-owner-nonce", spawn_nonce])
  341. env = _spawn_env(payload)
  342. _ensure_scope(ownership_id)
  343. log_path = _log_path(ownership_id, spawn_nonce)
  344. win32con = _win32().win32con
  345. log_handle = _open(log_path, win32con.GENERIC_WRITE | win32con.READ_CONTROL,
  346. win32con.CREATE_NEW, win32con.FILE_ATTRIBUTE_NORMAL | _OPEN_REPARSE_POINT,
  347. win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE)
  348. import msvcrt
  349. log_fd = msvcrt.open_osfhandle(int(log_handle), os.O_WRONLY)
  350. with os.fdopen(log_fd, "wb", buffering=0) as log_stream:
  351. # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB
  352. process = subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=log_stream, stderr=log_stream,
  353. close_fds=True, creationflags=0x00000008 | 0x00000200 | 0x01000000, env=env)
  354. creation_time_ns = int(__import__("psutil").Process(process.pid).create_time() * 1_000_000_000)
  355. return {"pid": process.pid, "creationTimeNs": str(creation_time_ns),
  356. "logPath": str(log_path), "tokenPath": token_path}
  357. def inspect_hermes(hermes_path: str) -> dict[str, Any]:
  358. path = os.path.abspath(hermes_path)
  359. if not os.path.isabs(hermes_path) or not os.path.isfile(path):
  360. raise ValueError("Hermes path is not an executable file")
  361. version = subprocess.run([path, "--version"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=20, check=False)
  362. help_result = subprocess.run([path, "serve", "--help"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=20, check=False)
  363. help_text = help_result.stdout + help_result.stderr
  364. return {
  365. "path": path,
  366. "version": (version.stdout + version.stderr).splitlines()[0] if version.returncode == 0 else "",
  367. "runtimeBootstrapOwnership": 1,
  368. "supported": "--ssh-session-token-file" in help_text and "--ssh-owner-nonce" in help_text}
  369. def _probe(*_: str) -> dict[str, Any]:
  370. import platform
  371. return {"os": "Windows", "arch": platform.machine(), "hermesHome": str(get_default_hermes_root()), "python": sys.executable}
  372. def _inventory(*_: str) -> dict[str, Any]:
  373. """Desktop's read-only roster: the canonical root and profile predicate; never mints an identity."""
  374. from hermes_cli.install_identity import _INSTALL_ID_FILENAME, _read_existing
  375. from hermes_cli.profiles import _iter_named_profile_dirs
  376. install_id, _ = _read_existing(get_default_hermes_root() / _INSTALL_ID_FILENAME)
  377. return {"profiles": ["default", *[p.name for p in _iter_named_profile_dirs()]], "installId": install_id}
  378. def _read_log(ownership_id: str, spawn_nonce: str) -> dict[str, Any]:
  379. win32con = _win32().win32con
  380. data = _read_shared(_log_path(ownership_id, spawn_nonce), _MAX_LOG,
  381. win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE)
  382. return {"content": "" if data is None else data.decode(errors="replace")}
  383. def _write_lock_op(ownership_id: str) -> dict[str, Any]:
  384. write_lock(ownership_id, _read_json_stdin())
  385. return {"ok": True}
  386. # operation -> (argument count or None for "any", handler(*args)).
  387. _OPERATIONS: dict[str, tuple[int | None, Any]] = {
  388. "probe": (None, _probe),
  389. "inventory": (None, _inventory),
  390. "upload-token": (2, lambda o, n: upload_token(o, n, sys.stdin.buffer.read(65))),
  391. "read-lock": (1, read_lock),
  392. "write-lock": (1, _write_lock_op),
  393. "remove-lock": (1, lambda o: {"removed": remove_artifact(_lock_path(o))}),
  394. "remove-token": (2, lambda o, n: {"removed": remove_artifact(_token_path(o, n))}),
  395. "read-log": (2, _read_log),
  396. "remove-log": (2, lambda o, n: {"removed": remove_artifact(_log_path(o, n))}),
  397. "spawn": (None, lambda *_: spawn_backend(_read_json_stdin())),
  398. "inspect": (1, inspect_hermes),
  399. "process-state": (4, lambda p, c, h, n: process_state(int(p), int(c), h, n)),
  400. "terminate": (4, lambda p, c, h, n: {"terminated": terminate_owned(int(p), int(c), h, n)})}
  401. def dispatch(argv: list[str]) -> Any:
  402. if not argv:
  403. raise ValueError("missing operation")
  404. operation, args = argv[0], argv[1:]
  405. entry = _OPERATIONS.get(operation)
  406. if entry is None or (entry[0] is not None and len(args) != entry[0]):
  407. raise ValueError("invalid operation")
  408. return entry[1](*args)
  409. def main() -> None:
  410. try:
  411. print(json.dumps(dispatch(sys.argv[1:]), separators=(",", ":")))
  412. except Exception as exc:
  413. print(json.dumps({"error": str(exc)}, separators=(",", ":")), file=sys.stderr)
  414. raise SystemExit(1)
  415. if __name__ == "__main__":
  416. main()