Skip to content

The agent that grows with you

fix(pm): install libatomic before the detached update child, not a sudo ticket

kshitijk4poorc4d4ac569f37
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.py
index 7a57ee80ad9..091f7e0473c 100644
--- a/hermes_cli/update_completion.py
+++ b/hermes_cli/update_completion.py
@@ -37,6 +37,11 @@ def _failed_result(request: dict, result_path: Path, code: int) -> int:
def run_completion(request: dict) -> dict:
"""Wait for new code; zero exit without a correlated terminal result fails closed."""
+ from pm.libatomic import install_before_lock
+
+ # The child below runs in a new session without a controlling terminal,
+ # so this is the last point where sudo can ask for a password.
+ install_before_lock()
root = Path(request["source"])
env = dict(os.environ, HERMES_HOME=request["home"], PYTHONUNBUFFERED="1")
for key in ("PYTHONPATH", "PYTHONHOME", "VIRTUAL_ENV"):
diff --git a/pm/client.py b/pm/client.py
index 5aecd238408..eb5ceee784b 100644
--- a/pm/client.py
+++ b/pm/client.py
@@ -244,11 +244,11 @@ def ensure_tools_for_sync() -> None:
gate it; a failed download fails the update.
"""
from pm.install import activate
- from pm.libatomic import warm_sudo_before_install
+ from pm.libatomic import install_before_lock
from pm.lock import Lockfile
from pm.registry import tool_roots
- warm_sudo_before_install()
+ install_before_lock()
for name in tool_roots(Lockfile(paths.lockfile_path()).names()):
ensure(name, explicit=True)
problems = activate(allow_incomplete=True)
diff --git a/pm/libatomic.py b/pm/libatomic.py
index fa61a6c46e4..e826c89d93f 100644
--- a/pm/libatomic.py
+++ b/pm/libatomic.py
@@ -1,8 +1,8 @@
"""Install the host libatomic package required by official Linux Node.
-Two entry points: warm_sudo_before_install() lets an interactive update cache
-a sudo ticket before PM takes its install lock, and try_install_libatomic()
-is the non-interactive repair run from Nodejs.repair_staged_verification().
+Two entry points: install_before_lock() lets an interactive update install
+the package (asking for sudo) before PM takes its install lock, and
+try_install_libatomic() is the non-interactive repair run from Nodejs.repair_staged_verification().
Package verification itself remains diagnostic and side-effect free.
"""
@@ -87,14 +87,14 @@ def _command_plan(command: tuple[str, ...]) -> tuple[list[str] | None, str, str]
return None, "", f"as root: {shlex.join(command)}"
-def warm_sudo_before_install() -> None:
- """Let a terminal user authorize sudo before PM takes its install lock.
+def install_before_lock() -> None:
+ """Install the libatomic package interactively before PM takes its lock.
- The staged repair can only use ``sudo -n``, so on a password-sudo host it
- succeeds only with a cached ticket. Updates enter PM directly, without the
- shell installer's prerequisites stage, so cache the ticket here: only on a
- glibc Linux host still missing libatomic.so.1, non-root, interactive, and
- only when sudo would actually ask.
+ Inside the lock the repair may only use ``sudo -n``, so a password-sudo
+ host needs the password asked here, where a prompt cannot wedge PM. Run
+ only on a glibc Linux host still missing libatomic.so.1, with a
+ controlling terminal sudo can read from (detached children, gateway and
+ Desktop updates have none), and only when sudo would actually ask.
"""
import ctypes
import sys
@@ -103,8 +103,6 @@ def warm_sudo_before_install() -> None:
if not sys.platform.startswith("linux") or _is_root():
return
- if not (sys.stdin and sys.stdin.isatty() and sys.stdout and sys.stdout.isatty()):
- return
target = current_target()
if target in MUSL_TARGETS or target.endswith("-bionic"):
return
@@ -113,29 +111,42 @@ def warm_sudo_before_install() -> None:
return
except OSError:
pass
- # Prompt only when the repair would actually run sudo with the ticket.
command = _host_install_command()
argv = _command_plan(command)[0] if command else None
- if not argv:
+ if not argv or not _has_terminal():
return
sudo = argv[0]
if subprocess.run([sudo, "-n", "true"], stdin=subprocess.DEVNULL,
capture_output=True, check=False).returncode == 0:
- return
+ return # the non-interactive repair will succeed on its own
print("→ Node.js needs libatomic.so.1; sudo may ask for your password to install it", flush=True)
+ _install([sudo], command, stdin=None)
+
+
+def _has_terminal() -> bool:
try:
- subprocess.run([sudo, "-v"], timeout=300, check=False)
- except (OSError, subprocess.TimeoutExpired):
- pass
+ os.close(os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY))
+ except OSError:
+ return False
+ return True
-def _run(argv: list[str]) -> bool:
+def _run(argv: list[str], stdin=subprocess.DEVNULL) -> bool:
try:
- return subprocess.run(argv, stdin=subprocess.DEVNULL, timeout=300, check=False).returncode == 0
+ return subprocess.run(argv, stdin=stdin, timeout=300, check=False).returncode == 0
except (OSError, subprocess.TimeoutExpired):
return False
+def _install(prefix: list[str], command: tuple[str, ...], stdin=subprocess.DEVNULL) -> bool:
+ if _run([*prefix, *command], stdin):
+ return True
+ if command[0] != "apt-get":
+ return False
+ # Minimal Debian/Ubuntu images ship empty package lists.
+ return _run([*prefix, "apt-get", "update", "-qq"], stdin) and _run([*prefix, *command], stdin)
+
+
def try_install_libatomic() -> tuple[bool, str]:
"""Try the distro-native libatomic package; return (attempt_succeeded, hint).
@@ -162,10 +173,4 @@ def _attempt() -> tuple[bool, str]:
return False, remedy
print(f"→ Node needs libatomic.so.1; trying non-interactive {attempt_display}", flush=True)
- if _run(argv):
- return True, remedy
- if command[0] != "apt-get":
- return False, remedy
- # Minimal Debian/Ubuntu images ship empty package lists.
- update = argv[: len(argv) - len(command)] + ["apt-get", "update", "-qq"]
- return _run(update) and _run(argv), remedy
+ return _install(argv[: len(argv) - len(command)], command), remedy
diff --git a/tests/pm/test_node_libatomic_install_boundary.py b/tests/pm/test_node_libatomic_install_boundary.py
index 181363b3952..6646357c074 100644
--- a/tests/pm/test_node_libatomic_install_boundary.py
+++ b/tests/pm/test_node_libatomic_install_boundary.py
@@ -94,3 +94,22 @@ def test_installer_sudo_warmup_honours_non_interactive(tmp_path, flags):
prompted = log.is_file() and "-v" in log.read_text().split()
assert prompted is (flags == "")
+
+
+def test_update_completion_installs_before_detaching(monkeypatch):
+ """run_completion's child has no controlling terminal; the interactive install runs first."""
+ from hermes_cli import update_completion
+ from pm import libatomic
+
+ order = []
+ monkeypatch.setattr(libatomic, "install_before_lock", lambda: order.append("install"))
+
+ def popen(*_args, **_kwargs):
+ order.append("detach")
+ raise RuntimeError("stop after spawn")
+
+ monkeypatch.setattr(update_completion.subprocess, "Popen", popen)
+ with pytest.raises(RuntimeError, match="stop after spawn"):
+ update_completion.run_completion({"source": "/nonexistent", "home": "/nonexistent",
+ "receipt": {"update_id": "u"}})
+ assert order == ["install", "detach"]