From 729a2b9a3b949ccb5115759bb8ab3d324e82802c Mon Sep 17 00:00:00 2001 From: tarilka0gg <216761460+tarilka0gg@users.noreply.github.com> Date: Wed, 4 Nov 2026 20:20:15 -0500 Subject: [PATCH 01/11] Reduce startup overhead and read Linux processes directly --- src/keychain/__init__.py | 8 +++++--- src/keychain/agents.py | 19 +++++-------------- src/keychain/coordination.py | 17 ++++------------- src/keychain/docs/__init__.py | 5 ++--- src/keychain/main.py | 7 ++++++- src/keychain/paths.py | 16 +++++----------- src/keychain/runtime/platform.py | 13 +++++++++++++ src/keychain/util.py | 27 ++++++++++++++++++++++++--- tests/test_paths.py | 2 +- 9 files changed, 65 insertions(+), 49 deletions(-) diff --git a/src/keychain/__init__.py b/src/keychain/__init__.py index b9f0e21..7c79986 100644 --- a/src/keychain/__init__.py +++ b/src/keychain/__init__.py @@ -29,9 +29,8 @@ ) sys.exit(2) -from importlib.metadata import PackageNotFoundError, version # noqa: E402 -from importlib.resources import files # noqa: E402 from pathlib import Path # noqa: E402 +from pkgutil import get_data # noqa: E402 __all__ = ["__version__"] @@ -44,7 +43,7 @@ def _resolve_version() -> str: # built from -- never a stale value from an unrelated ``keychain`` # package that happens to be installed system-wide. try: - text = files(__package__ or "keychain").joinpath("VERSION").read_text(encoding="utf-8").strip() + text = (get_data(__package__ or "keychain", "VERSION") or b"").decode("utf-8").strip() if text: return text except (FileNotFoundError, ModuleNotFoundError, OSError): @@ -59,6 +58,9 @@ def _resolve_version() -> str: if candidate.is_file(): return candidate.read_text(encoding="utf-8").strip() or "0.0.0" # 3. Fall back to installed-package metadata (pip install ., wheels, ...). + # Imported here: importlib.metadata costs more than the rest of startup. + from importlib.metadata import PackageNotFoundError, version + try: return version("keychain") except PackageNotFoundError: diff --git a/src/keychain/agents.py b/src/keychain/agents.py index 1907930..de17d16 100644 --- a/src/keychain/agents.py +++ b/src/keychain/agents.py @@ -11,7 +11,6 @@ import stat import subprocess import sys -import tempfile from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path @@ -19,7 +18,7 @@ from .env import SshAgentRef from .output.core import Output -from .util import KeychainError, LockFile, current_uid, get_tty, run, unlink_quiet +from .util import KeychainError, LockFile, current_uid, get_tty, run, tempdir, unlink_quiet, write_atomic if TYPE_CHECKING: from .state import KeychainState @@ -74,15 +73,7 @@ def ensure_macos_askpass(path: Path) -> Path: except OSError: pass - fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent, text=True) - try: - with os.fdopen(fd, "w", encoding="utf-8") as handle: - handle.write(_MACOS_ASKPASS) - os.chmod(tmp_name, 0o700) - Path(tmp_name).replace(path) - except Exception: - unlink_quiet(tmp_name) - raise + write_atomic(path, _MACOS_ASKPASS, 0o700) return path @@ -241,7 +232,7 @@ def pkcs11_provider_fingerprints(provider: str, out: Output) -> list[str] | None if not public_keys: return [] - with tempfile.TemporaryDirectory(prefix="keychain-pkcs11-") as td: + with tempdir(prefix="keychain-pkcs11-") as td: fps: list[str] = [] for i, public_key in enumerate(public_keys): public_key_path = Path(td) / f"provider-{i}.pub" @@ -733,7 +724,7 @@ def wipe(self) -> None: def warm_signing(self, gpg_keys: list[str]) -> None: out = self.out - with tempfile.TemporaryDirectory(prefix="keychain-gpg-") as td: + with tempdir(prefix="keychain-gpg-") as td: for index, k in enumerate(filter(None, gpg_keys)): out.info(f"Warming GPG signing key: {out.id(k)}") try: @@ -759,7 +750,7 @@ def warm_signing(self, gpg_keys: list[str]) -> None: def warm_decryption(self, gpg_keys: list[str]) -> None: out = self.out - with tempfile.TemporaryDirectory(prefix="keychain-gpg-") as td: + with tempdir(prefix="keychain-gpg-") as td: plain = Path(td) / "plain" plain.write_text("keychain\n", encoding="utf-8") for index, k in enumerate(filter(None, gpg_keys)): diff --git a/src/keychain/coordination.py b/src/keychain/coordination.py index a7b44ba..6ca36e6 100644 --- a/src/keychain/coordination.py +++ b/src/keychain/coordination.py @@ -7,11 +7,9 @@ import errno import json import os -import secrets import select import stat import subprocess -import tempfile import threading import time from collections.abc import Callable @@ -21,7 +19,7 @@ from .output.core import ActivationPrompt, Output from .paths import KeychainPaths -from .util import KeychainError, LockFile, unlink_quiet +from .util import KeychainError, LockFile, unlink_quiet, write_atomic _CHILD_TERMINATE_TIMEOUT = 5.0 @@ -54,14 +52,7 @@ def from_dict(cls, data: Any) -> CoordinationState: return cls(attempt, status) def save(self, path: Path) -> None: - fd, name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent, text=True) - try: - with os.fdopen(fd, "w", encoding="utf-8") as handle: - json.dump({"attempt": self.attempt, "status": self.status}, handle) - handle.write("\n") - Path(name).replace(path) - finally: - unlink_quiet(name) + write_atomic(path, json.dumps({"attempt": self.attempt, "status": self.status}) + "\n") def _open_fifo(path: Path, mode: int) -> int: @@ -198,7 +189,7 @@ def create_waiter(self) -> ActivationWaiter | None: if self.no_lock or not hasattr(os, "mkfifo") or not self.can_prompt(): return None with self.state_lock(): - return ActivationWaiter(self, self.endpoint(f"wait.{os.getpid()}.{secrets.token_hex(8)}")) + return ActivationWaiter(self, self.endpoint(f"wait.{os.getpid()}.{os.urandom(8).hex()}")) def notify_waiters(self, attempt: str, status: str) -> None: for path in self.paths.waiters_dir.glob("wait.*.fifo"): @@ -406,7 +397,7 @@ def __init__( self, coord: ActivationCoordinator, waiter: ActivationWaiter | None, *, exclusive: bool = False ) -> None: self.coord, self.waiter = coord, waiter - self.attempt = secrets.token_hex(16) + self.attempt = os.urandom(16).hex() self.gate = coord.activation_lock(shared=not exclusive) self.lock = coord.attempt_lock(self.attempt) self.status = "failed" diff --git a/src/keychain/docs/__init__.py b/src/keychain/docs/__init__.py index b9527f0..b41ea7e 100644 --- a/src/keychain/docs/__init__.py +++ b/src/keychain/docs/__init__.py @@ -16,7 +16,7 @@ import sys from dataclasses import dataclass from functools import cache -from importlib.resources import files +from pkgutil import get_data from typing import Any from ..output.core import Output, Span, strip_ansi @@ -26,8 +26,7 @@ @cache def _payload() -> dict[str, Any]: - blob = files("keychain").joinpath("docs").joinpath("_doc_texts.json").read_text(encoding="utf-8") - return json.loads(blob) + return json.loads(get_data("keychain", "docs/_doc_texts.json") or b"{}") def _entry(tag: str) -> dict[str, str]: diff --git a/src/keychain/main.py b/src/keychain/main.py index aa3a952..d3a3216 100644 --- a/src/keychain/main.py +++ b/src/keychain/main.py @@ -19,9 +19,9 @@ import sys import time from contextlib import contextmanager +from typing import TYPE_CHECKING from . import __version__, agents, keys, state -from .coordination import ActivationCoordinator, ActivationWaiter from .env import SshAgentRef from .output.core import Output from .runtime import platform @@ -29,6 +29,9 @@ from .runtime.config import OptionError, RuntimeConfig from .util import KeychainError +if TYPE_CHECKING: + from .coordination import ActivationCoordinator, ActivationWaiter + def _emit_eval_failure(enabled: bool) -> None: if enabled: @@ -277,6 +280,8 @@ def _resolve_requested_keys(self, *, gpg_lookup: bool = True) -> keys.ResolvedKe return resolved def _coordinator(self) -> ActivationCoordinator: + from .coordination import ActivationCoordinator + lockwait = self.args.get_value("lockwait") if lockwait is None: lockwait = 5 diff --git a/src/keychain/paths.py b/src/keychain/paths.py index 13730e8..b1e27c6 100644 --- a/src/keychain/paths.py +++ b/src/keychain/paths.py @@ -3,12 +3,9 @@ from __future__ import annotations -import base64 -import hashlib import os import shlex import stat -import tempfile from collections.abc import Mapping from dataclasses import dataclass from pathlib import Path @@ -22,6 +19,7 @@ lax_perm_warning, lax_perms, unlink_quiet, + write_atomic, ) # macOS has the smallest common sockaddr_un.sun_path limit: 104 bytes, @@ -60,14 +58,7 @@ def render(self, env: SshAgentRef) -> str: def write(self, env: SshAgentRef) -> None: """Write the pidfile atomically via temp file + rename.""" - fd, tmp_name = tempfile.mkstemp(prefix=f".{self.path.name}.", suffix=".tmp", dir=self.path.parent, text=True) - try: - with os.fdopen(fd, "w", encoding="utf-8") as handle: - handle.write(self.render(env)) - Path(tmp_name).replace(self.path) - except Exception: - unlink_quiet(tmp_name) - raise + write_atomic(self.path, self.render(env)) @dataclass(frozen=True) @@ -254,6 +245,9 @@ def ssh_agent_socket_path(self) -> Path: return path def _ssh_agent_socket_path(self) -> Path: + import base64 + import hashlib + host_digest = hashlib.sha256(os.fsencode(self.host)).digest()[:6] socket_name = base64.urlsafe_b64encode(host_digest).decode() return self.keydir / f"{socket_name}.s" diff --git a/src/keychain/runtime/platform.py b/src/keychain/runtime/platform.py index ac95d9f..5bf5b56 100644 --- a/src/keychain/runtime/platform.py +++ b/src/keychain/runtime/platform.py @@ -15,6 +15,7 @@ from __future__ import annotations +import os import re import shutil import subprocess @@ -61,6 +62,18 @@ def __init__(self, name: str) -> None: def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int]: pids: list[int] = [] + if self.name.startswith("linux") and os.path.isdir("/proc/self"): + # Spawning ps costs ~10 ms; walking /proc costs ~4 ms. + for entry in os.listdir("/proc"): + try: + if not entry.isdigit() or (uid is not None and os.stat(f"/proc/{entry}").st_uid != uid): + continue + with open(f"/proc/{entry}/comm", encoding="utf-8", errors="replace") as handle: + if pattern.search(handle.read().strip()): + pids.append(int(entry)) + except OSError: + continue # the process exited mid-scan + return pids try: proc = subprocess.Popen( # illumos/Solaris treats everything after '=' in one -o diff --git a/src/keychain/util.py b/src/keychain/util.py index 466be85..2f96d3c 100644 --- a/src/keychain/util.py +++ b/src/keychain/util.py @@ -7,10 +7,8 @@ from __future__ import annotations import contextlib -import ctypes import errno import os -import secrets import socket import stat import subprocess @@ -102,7 +100,7 @@ def __init__(self, path: PathLike, no_lock: bool, wait: int, out: Output, *, sha self.acquired = False self.shared = shared self._fd = -1 - self._token = f"{socket.gethostname()}:{os.getpid()}:{secrets.token_hex(8)}" + self._token = f"{socket.gethostname()}:{os.getpid()}:{os.urandom(8).hex()}" # ---- context manager ---------------------------------------------- def __enter__(self) -> LockFile: @@ -193,6 +191,8 @@ def pid_alive(pid: int) -> bool: if pid <= 0: return False if os.name == "nt": + import ctypes + kernel32 = cast(Any, ctypes).windll.kernel32 handle = kernel32.OpenProcess(0x1000, False, pid) if not handle: @@ -273,6 +273,27 @@ def unlink_quiet(*paths: PathLike) -> None: os.unlink(p) +def write_atomic(path: Path, text: str, mode: int | None = None) -> None: + """Write *text* to *path* through a temp file in the same directory, then rename.""" + import tempfile # slow to import, and only writers need it + + fd, tmp = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent, text=True) + try: + with os.fdopen(fd, "w", encoding="utf-8") as handle: + handle.write(text) + if mode is not None: + os.chmod(tmp, mode) + Path(tmp).replace(path) + finally: + unlink_quiet(tmp) + + +def tempdir(prefix: str) -> Any: + import tempfile # slow to import, and only some actions need it + + return tempfile.TemporaryDirectory(prefix=prefix) + + def dedupe_sorted(items: Iterable[str]) -> list[str]: """Deterministic deduplication: insertion-order de-dup, then sorted.""" seen: set[str] = set() diff --git a/tests/test_paths.py b/tests/test_paths.py index 53d4311..b71eaef 100644 --- a/tests/test_paths.py +++ b/tests/test_paths.py @@ -203,7 +203,7 @@ def fake_mkstemp(*args, **kwargs): calls.append((kwargs["prefix"], kwargs["suffix"], kwargs["dir"])) return real_mkstemp(*args, **kwargs) - with patch("keychain.paths.tempfile.mkstemp", side_effect=fake_mkstemp): + with patch("tempfile.mkstemp", side_effect=fake_mkstemp): kp.write(SshAgentRef.from_text(AGENT_SH_OUTPUT), _out()) assert calls == [ From 99b323f0d58c47d5021e8c0ae729eaa01f2e615c Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:20:33 -0500 Subject: [PATCH 02/11] Reuse verified sockets when Linux restricts process visibility --- src/keychain/agents.py | 17 ++- src/keychain/output/inspect.py | 28 +++- src/keychain/runtime/platform.py | 26 +++- src/keychain/state.py | 10 ++ tests/test_agent_visibility.py | 125 ++++++++++++++++ tests/test_agents.py | 5 +- tests/test_hidden_agent_e2e.py | 240 +++++++++++++++++++++++++++++++ tests/test_state.py | 2 +- 8 files changed, 439 insertions(+), 14 deletions(-) create mode 100644 tests/test_agent_visibility.py create mode 100644 tests/test_hidden_agent_e2e.py diff --git a/src/keychain/agents.py b/src/keychain/agents.py index de17d16..a28489d 100644 --- a/src/keychain/agents.py +++ b/src/keychain/agents.py @@ -366,7 +366,8 @@ def _validate_candidate(self, source: str, agent_env: SshAgentRef, *, announce: out.note("Ignoring gpg-agent SSH socket; Keychain manages SSH keys with ssh-agent.") return None - if pid_str and agent_env.pid_int not in self.keychain_state.ssh_agent_pids: + pid_status = self.keychain_state.ssh_pid_status(agent_env.pid_int) if pid_str else "unset" + if pid_str and pid_status not in ("verified", "uninspectable"): out.debug(f"SSH_AGENT_PID in {source} ({pid_str}) is not a running ssh-agent; ignoring it") if visible: self._remember_spawn_context(source, "pid is not ssh-agent") @@ -391,7 +392,8 @@ def _validate_candidate(self, source: str, agent_env: SshAgentRef, *, announce: return None if announce: - out.info(f"Existing ssh-agent ({source}): {out.id(pid_str)}") + detail = "; process identity unavailable, socket verified" if pid_status == "uninspectable" else "" + out.info(f"Existing ssh-agent ({source}): {out.id(pid_str)}{detail}") return SshAgentRef(sock, pid_str) def select_existing(self, *, pidfile_only: bool = False, announce: bool = False) -> SshAgentRef: @@ -519,13 +521,13 @@ def start(self, state_lock: LockFile) -> bool: def stop(self, which: str) -> None: out = self.out out.info("Stopping ssh-agent(s)...") + pidf_env = self.keychain_state.pidfile_env if which != "all": - pidf_env = self.keychain_state.pidfile_env if pidf_env: self.env = pidf_env pids = findpids("ssh") if not pids: - out.info("No ssh-agent(s) found running") + out.info("No visible ssh-agent(s) found running") else: our = self._our_pid() ours = our if our in pids else None @@ -545,9 +547,9 @@ def stop(self, which: str) -> None: rendered = out.id(" ".join(map(str, killed))) if which == "all": - out.info(f"All ssh-agents stopped: {rendered}") + out.info(f"Visible ssh-agents stopped: {rendered}") elif which == "mine": - out.info(f"All {out.id(self.keychain_state.user)}'s ssh-agents stopped: {rendered}") + out.info(f"Visible ssh-agents owned by {out.id(self.keychain_state.user)} stopped: {rendered}") elif which == "pidfile" and killed: out.info(f"Keychain ssh-agent stopped: {out.id(killed[0])}") elif which == "others": @@ -555,6 +557,9 @@ def stop(self, which: str) -> None: else: out.info("No keychain ssh-agent found running") if which != "others": + if pidf_env.pid_int not in pids and self.keychain_state.ssh_pid_status(pidf_env.pid_int) == "uninspectable": + out.warn(f"Cannot verify process identity for PID {pidf_env.pid}; not signaling it, pidfile kept.") + return self.keychain_state.paths.clear() # ---- key operations ---------------------------------------------- diff --git a/src/keychain/output/inspect.py b/src/keychain/output/inspect.py index fe8a39a..bc5a954 100644 --- a/src/keychain/output/inspect.py +++ b/src/keychain/output/inspect.py @@ -135,6 +135,8 @@ def set_vars(*names: str) -> str: ("pidfile path", str(state.pidfile_path), ""), ("pidfile exists", state.pidfile_exists, ""), ] + pidfile = state.pidfile_env + pid_status = state.ssh_pid_status(pidfile.pid_int) if state.pidfile_exists: pidf_rows.append(("SSH_AUTH_SOCK", state.pidfile_socket or "(unset)", "")) pidf_rows.append(("SSH_AGENT_PID", state.pidfile_pid or "(unset)", "")) @@ -143,11 +145,14 @@ def set_vars(*names: str) -> str: pidf_rows.append(("socket valid", socket_validation.valid, sock_hint, socket_validation.severity)) pid_hint = "" if state.pidfile_pid_alive else ("process is not running" if state.pidfile_pid else "") pidf_rows.append(("pid alive", state.pidfile_pid_alive, pid_hint)) + pidf_rows.append(("process identity", pid_status, "")) if not state.process_listing_supported: pidf_rows.append(("processes", "listing not available on this platform", "")) else: - pidf_rows.append(("ssh-agent pids", _fmt_pids(state.ssh_agent_pids), "")) - pidf_rows.append(("gpg-agent pids", _fmt_pids(state.gpg_agent_pids), "")) + pidf_rows.append(("visible ssh-agent pids", _fmt_pids(state.ssh_agent_pids), "")) + pidf_rows.append(("visible gpg-agent pids", _fmt_pids(state.gpg_agent_pids), "")) + selected = state.selected_ssh_env + pidf_rows.append(("selected socket", selected.sock or "(none)", "responding" if selected else "")) sections.append(("Agent State", pidf_rows)) term_w = shutil.get_terminal_size((80, 24)).columns @@ -159,6 +164,13 @@ def set_vars(*names: str) -> str: for line in layout.splitlines(): out.result(" " + line) + selected_status = state.ssh_pid_status(selected.pid_int) if selected.pid_int != pidfile.pid_int else pid_status + if "uninspectable" in (pid_status, selected_status): + out.note( + "The PID is alive, but process details are inaccessible (for example, /proc hidepid restrictions). " + "Keychain can reuse a responding, user-owned socket but cannot safely stop this unverified process." + ) + out.heading("Loaded SSH keys (best available agent)") fps = state.loaded_ssh_fingerprints if fps: @@ -175,7 +187,7 @@ def set_vars(*names: str) -> str: if state.has_selected_ssh_agent: out.result(f" {out.dim('(none loaded)')}") else: - out.result(f" {out.dim('(no agent reachable)')}") + out.result(f" {out.dim('(no usable agent selected)')}") if state.cmdline_keys or state.confallhosts: cli_repr = " ".join(state.cmdline_keys) or "(--confallhosts)" @@ -217,6 +229,7 @@ def _agent_reference( socket_reason: str, socket_severity: str, pid_alive: bool, + identity: str, ) -> dict[str, Any]: return { "socket": { @@ -225,7 +238,7 @@ def _agent_reference( "reason": socket_reason or None, "severity": socket_severity or None, }, - "process": {"pid": pid or None, "alive": pid_alive}, + "process": {"pid": pid or None, "alive": pid_alive, "identity": identity}, } @@ -295,6 +308,7 @@ def render_inspect_json(state: KeychainState) -> None: state.pidfile_socket_validation.reason, state.pidfile_socket_validation.severity, state.pidfile_pid_alive, + state.ssh_pid_status(state.pidfile_env.pid_int), ), }, "inherited": _agent_reference( @@ -304,7 +318,13 @@ def render_inspect_json(state: KeychainState) -> None: state.inherited_socket_validation.reason, state.inherited_socket_validation.severity, state.inherited_pid_alive, + state.ssh_pid_status(state.inherited_env.pid_int), ), + "selected": { + "socket": state.selected_ssh_env.sock or None, + "pid": state.selected_ssh_env.pid or None, + "source": state.ssh.env_source or None, + }, "processes": { "supported": state.process_listing_supported, "ssh_agent_pids": list(state.ssh_agent_pids), diff --git a/src/keychain/runtime/platform.py b/src/keychain/runtime/platform.py index 5bf5b56..35e66f7 100644 --- a/src/keychain/runtime/platform.py +++ b/src/keychain/runtime/platform.py @@ -50,16 +50,38 @@ def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int] "process listing not available on {}: {}".format(self.name, self.reason or "unsupported platform") ) + def process_details_unavailable(self, pid: int) -> bool: + """Whether a live PID's identity is inaccessible, not merely absent from a scan.""" + return False + def __repr__(self): # pragma: no cover - debugging aid return f"" class _PosixPlatform(Platform): - """POSIX-shaped userland: enumerate processes via ``ps``.""" + """POSIX-shaped userland: enumerate visible processes via /proc or ps.""" def __init__(self, name: str) -> None: self.name = name + def process_details_unavailable(self, pid: int) -> bool: + if pid <= 0 or not self.name.startswith(("linux", "android")) or not os.path.isdir("/proc/self"): + return False + try: + with open(f"/proc/{pid}/comm", encoding="utf-8", errors="replace") as handle: + handle.read(1) + except (FileNotFoundError, PermissionError): + # hidepid can return ENOENT for a live, non-dumpable ssh-agent. + # Check liveness after the read, so an exit during it is not "hidden". + try: + os.kill(pid, 0) + except (OSError, OverflowError): + return False + return True + except OSError: + pass + return False + def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int]: pids: list[int] = [] if self.name.startswith("linux") and os.path.isdir("/proc/self"): @@ -72,7 +94,7 @@ def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int] if pattern.search(handle.read().strip()): pids.append(int(entry)) except OSError: - continue # the process exited mid-scan + continue # exited mid-scan, or process details are restricted return pids try: proc = subprocess.Popen( diff --git a/src/keychain/state.py b/src/keychain/state.py index 5ee55c5..acb0696 100644 --- a/src/keychain/state.py +++ b/src/keychain/state.py @@ -233,6 +233,16 @@ def ssh_agent_pids(self) -> list[int]: return [] return agents.findpids("ssh") + def ssh_pid_status(self, pid: int | None) -> str: + """Fresh identity check; uninspectable is not permission to signal a PID.""" + if pid is None: + return "unset" + if pid in self.ssh_agent_pids: + return "verified" + if self.platform.process_details_unavailable(pid): + return "uninspectable" + return "unverified" + @cached_property def gpg_agent_pids(self) -> list[int]: if not self.process_listing_supported: diff --git a/tests/test_agent_visibility.py b/tests/test_agent_visibility.py new file mode 100644 index 0000000..c82d180 --- /dev/null +++ b/tests/test_agent_visibility.py @@ -0,0 +1,125 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Hidden processes are not dead processes, nor verified signal targets.""" + +import errno +import io +from unittest.mock import Mock + +import pytest + +from keychain import agents, state +from keychain.env import SshAgentRef +from keychain.output.core import Output +from keychain.paths import KeychainPaths +from keychain.runtime import platform + + +@pytest.mark.parametrize("name", ["linux", "linux2", "android"]) +@pytest.mark.parametrize("error", [errno.ENOENT, errno.EACCES, errno.EPERM, errno.EIO, None]) +@pytest.mark.parametrize("alive", [True, False]) +def test_process_details_probe(monkeypatch, name, error, alive): + def read(path, **_kwargs): + assert path == "/proc/123/comm" + if error: + raise OSError(error, "test") + return io.StringIO("python\n") + + def kill(pid, sig): + assert (pid, sig) == (123, 0) + if not alive: + raise ProcessLookupError() + + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) + monkeypatch.setattr(platform, "open", read, raising=False) + monkeypatch.setattr(platform.os, "kill", kill) + assert platform._PosixPlatform(name).process_details_unavailable(123) is ( + alive and error in (errno.ENOENT, errno.EACCES, errno.EPERM) + ) + + +@pytest.mark.parametrize("name,proc", [("darwin", True), ("sunos5", True), ("linux", False), ("android", False)]) +def test_no_visibility_inference_without_linux_proc(monkeypatch, name, proc): + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: proc) + monkeypatch.setattr(platform, "open", lambda *_a, **_k: pytest.fail("must not read proc"), raising=False) + assert not platform._PosixPlatform(name).process_details_unavailable(123) + + +@pytest.mark.parametrize("pid", [-1, 0, 2**64]) +def test_invalid_pid_cannot_enable_fallback(monkeypatch, pid): + def read(*_args, **_kwargs): + raise FileNotFoundError() + + def kill(actual_pid, sig): + assert actual_pid > 0 and sig == 0 + raise OverflowError() + + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) + monkeypatch.setattr(platform, "open", read, raising=False) + monkeypatch.setattr(platform.os, "kill", kill) + assert not platform._PosixPlatform("linux").process_details_unavailable(pid) + + +@pytest.fixture +def agent(tmp_path, monkeypatch): + k = state.KeychainState(paths=KeychainPaths(keydir=tmp_path, host="test"), env={}) + k.platform = platform._PosixPlatform("linux") + monkeypatch.setattr(agents, "findpids", lambda _name: []) + monkeypatch.setattr(agents, "validate_ssh_socket", lambda sock: agents.SocketValidation(sock, True)) + monkeypatch.setattr(k.platform, "process_details_unavailable", lambda _pid: True) + return agents.SshAgent(k, Output.build(quiet=False, debug=True, eval_mode=False, color=False)) + + +@pytest.mark.parametrize("source", ["pidfile", "env", "selected"]) +@pytest.mark.parametrize("status", [0, 1, 2]) +def test_uninspectable_agent_requires_a_responding_socket(agent, monkeypatch, source, status): + ref = SshAgentRef("/test.sock", "123") + monkeypatch.setattr(agents, "ssh_l", lambda _env: ([], status)) + assert agent._validate_candidate(source, ref) == (ref if status != 2 else None) + + +@pytest.mark.parametrize("reason", ["foreign-owner", "symlink", "not-socket", "missing"]) +def test_hidden_pid_does_not_bypass_socket_checks(agent, monkeypatch, reason): + monkeypatch.setattr(agents, "validate_ssh_socket", lambda sock: agents.SocketValidation(sock, False, reason)) + monkeypatch.setattr(agents, "ssh_l", lambda _env: pytest.fail("must not contact rejected socket")) + assert agent._validate_candidate("pidfile", SshAgentRef("/test.sock", "123")) is None + + +def test_visible_wrong_process_or_dead_pid_still_rejected(agent, monkeypatch): + monkeypatch.setattr(agent.keychain_state.platform, "process_details_unavailable", lambda _pid: False) + monkeypatch.setattr(agents, "ssh_l", lambda _env: pytest.fail("must reject PID first")) + assert agent._validate_candidate("pidfile", SshAgentRef("/test.sock", "123")) is None + + +def test_verified_process_does_not_need_fallback_probe(agent, monkeypatch): + monkeypatch.setattr(agents, "findpids", lambda _name: [123]) + monkeypatch.setattr(agent.keychain_state.platform, "process_details_unavailable", lambda _pid: pytest.fail("unneeded probe")) + assert agent.keychain_state.ssh_pid_status(123) == "verified" + + +def test_process_status_is_rechecked_after_visibility_changes(agent, monkeypatch): + pids = [123] + monkeypatch.setattr(agents, "findpids", lambda _name: pids) + assert agent.keychain_state.ssh_pid_status(123) == "verified" + pids.clear() + assert agent.keychain_state.ssh_pid_status(123) == "uninspectable" + monkeypatch.setattr(agent.keychain_state.platform, "process_details_unavailable", lambda _pid: False) + assert agent.keychain_state.ssh_pid_status(123) == "unverified" + + +@pytest.mark.parametrize("which", ["pidfile", "mine", "all", "others"]) +@pytest.mark.parametrize("visible", [[], [456]]) +def test_stop_never_signals_hidden_pid_and_keeps_its_reference(agent, monkeypatch, capsys, which, visible): + ref = SshAgentRef("/test.sock", "123") + monkeypatch.setattr(state.KeychainState, "pidfile_env", property(lambda _self: ref)) + monkeypatch.setattr(agents, "findpids", lambda _name: visible) + clear = Mock() + kill = Mock() + monkeypatch.setattr(KeychainPaths, "clear", clear) + monkeypatch.setattr(agents.os, "kill", kill) + + agent.stop(which) + + assert [call.args[0] for call in kill.call_args_list] == ([] if which == "pidfile" else visible) + clear.assert_not_called() + if which != "others": + assert "pidfile kept" in capsys.readouterr().err diff --git a/tests/test_agents.py b/tests/test_agents.py index b98ac23..ee1a791 100644 --- a/tests/test_agents.py +++ b/tests/test_agents.py @@ -554,6 +554,7 @@ class TestSshAgentStop: def _agent(self, pid: str, cleared: list[bool]): state = SimpleNamespace( pidfile_env=SshAgentRef(sock="/tmp/agent.sock", pid=pid), + ssh_pid_status=lambda _pid: "unverified", user="tester", paths=SimpleNamespace(clear=lambda: cleared.append(True)), ) @@ -760,7 +761,9 @@ def _agent( inherited_env=inherited, pidfile_env=pidfile, platform=SimpleNamespace(name=platform_name), - ssh_agent_pids=[11, 22] if ssh_agent_pids is None else ssh_agent_pids, + ssh_pid_status=lambda pid: "verified" if pid in ( + [11, 22] if ssh_agent_pids is None else ssh_agent_pids + ) else "unverified", ) return agents.SshAgent(state, _out()) diff --git a/tests/test_hidden_agent_e2e.py b/tests/test_hidden_agent_e2e.py new file mode 100644 index 0000000..931e115 --- /dev/null +++ b/tests/test_hidden_agent_e2e.py @@ -0,0 +1,240 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Opt-in Linux reproduction of #270, with isolated mounts, PIDs, and keys. + +Run as root with KEYCHAIN_TEST_HIDEPID=1. Root only creates the namespaces +and mount; agents and Keychain run as UID 65534 with disposable keys, +never the user's keys. +""" + +import ctypes +import errno +import json +import os +import re +import shutil +import socket +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] + + +def _namespace_probe(hidepid): + # Only called inside unshare's new mount/PID namespaces, never on host /proc. + if os.getpid() != 1 or os.geteuid() != 0: + raise RuntimeError("The probe must be PID 1 under root's unshare --mount --pid --fork") + subprocess.run(["mount", "-o", f"remount,hidepid={hidepid},gid=3009", "/proc"], check=True) + os.setgroups([]) + os.setgid(65534) + os.setuid(65534) + # Make this ordinary control process visible after dropping privileges. + libc = ctypes.CDLL(None, use_errno=True) + assert libc.prctl(4, 1, 0, 0, 0) == 0 # PR_SET_DUMPABLE + sys.path.insert(0, str(ROOT / "src")) + from keychain.env import SshAgentRef + from keychain.output.core import Output + from keychain.paths import KeychainPaths + from keychain.runtime.platform import _PosixPlatform + + report = { + "hidepid": hidepid, + "uid": os.getuid(), + "control_visible": Path(f"/proc/{os.getpid()}/comm").exists(), + "proc_mounts": [line for line in Path("/proc/self/mountinfo").read_text().splitlines() if " /proc " in line], + "cases": {}, + } + # Selecting android tests its current ps backend on Linux, not Android itself. + for backend in ("linux", "android"): + with tempfile.TemporaryDirectory(prefix="kc-hidepid-") as temporary: + home = Path(temporary) + keydir = home / ".keychain" + env = {"PATH": os.environ["PATH"], "HOME": str(home), "LC_ALL": "C", "PYTHONPATH": str(ROOT / "src")} + program = ( + "import sys; from keychain.runtime import platform; " + "platform.detect(platform_override=sys.argv.pop(1), has_ps=True); " + "from keychain.main import main; sys.exit(main())" + ) + command = [str(Path(sys.executable).resolve()), "-c", program, backend] + options = ["--host", "visibility", "--dir", str(keydir), "--absolute", "--debug"] + + def invoke(*args, command=command, options=options, env=env): + return subprocess.run([*command, *args, *options], env=env, capture_output=True, text=True, timeout=30) + + started = invoke("agent", "start") + assert started.returncode == 0, started.stdout + started.stderr + pidfile = keydir / "visibility-sh" + original = SshAgentRef.from_text(pidfile.read_text()) + assert original.pid_int is not None + empty_reused = invoke("agent", "start") + empty_pid = SshAgentRef.from_text(pidfile.read_text()).pid_int + agent_env = {**env, **original.as_dict()} + key = home / "test-key" + subprocess.run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)], env=env, check=True) + added = subprocess.run(["ssh-add", str(key)], env=agent_env, capture_output=True, text=True, timeout=10) + assert added.returncode == 0, added.stderr + listed = subprocess.run(["ssh-add", "-l"], env=agent_env, capture_output=True, text=True, timeout=10) + assert listed.returncode == 0, listed.stderr + os.kill(original.pid_int, 0) + with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection: + connection.settimeout(5) + connection.connect(original.sock) + peer_pid, peer_uid, peer_gid = struct.unpack("3i", connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + try: + owner = Path(f"/proc/{original.pid_int}").stat().st_uid + proc_errno = 0 + except OSError as error: + owner, proc_errno = None, error.errno + try: + Path(f"/proc/{original.pid_int}/comm").read_text() + comm_errno = 0 + except OSError as error: + comm_errno = error.errno + pids = _PosixPlatform(backend).process_list(re.compile(r"(?:^|/)ssh-agent$"), uid=os.getuid()) + inspected = invoke("inspect") + inspected_json = invoke("inspect", "--json") + assert inspected_json.returncode == 0, inspected_json.stderr + reused = invoke("add", "--immediate", str(key)) + current = SshAgentRef.from_text(pidfile.read_text()) + # Exercise an actual load too, not only reuse of a populated agent. + subprocess.run(["ssh-add", "-D"], env=agent_env, check=True, capture_output=True) + loaded = invoke("add", "--immediate", str(key)) + loaded_keys = subprocess.run(["ssh-add", "-l"], env=agent_env, capture_output=True, text=True, timeout=10) + paths = KeychainPaths(keydir=keydir, host="visibility") + bad_references = {} + with subprocess.Popen(["true"]) as dead: + dead.wait() + # A working socket must not excuse a visibly wrong or dead PID. + for label, pid in (("visible-other-process", os.getpid()), ("dead-process", dead.pid)): + paths.write(SshAgentRef(original.sock, str(pid)), Output.silent()) + rejected = invoke("inspect", "--json") + assert rejected.returncode == 0, rejected.stderr + bad_references[label] = json.loads(rejected.stdout)["agent_state"] + paths.write(original, Output.silent()) + stopped = invoke("agent", "stop") + after_stop = subprocess.run(["ssh-add", "-l"], env=agent_env, capture_output=True, text=True, timeout=10) + report["cases"][backend] = { + "pid_alive": True, + "manual_ssh_add_status": listed.returncode, + "proc_errno": proc_errno, + "comm_errno": comm_errno, + "proc_owner": owner, + "listed": original.pid_int in pids, + "peer_credentials": {"pid": peer_pid, "uid": peer_uid, "gid": peer_gid}, + "original_pid": original.pid_int, + "subsequent_pid": current.pid_int, + "add_status": reused.returncode, + "add_output": reused.stdout + reused.stderr, + "inspect_output": inspected.stdout + inspected.stderr, + "inspect_lists_key": listed.stdout.split()[1] in inspected.stdout + inspected.stderr, + "inspect_json": json.loads(inspected_json.stdout), + "load_status": loaded.returncode, + "load_output": loaded.stdout + loaded.stderr, + "loaded_keys": loaded_keys.stdout, + "stop_output": stopped.stdout + stopped.stderr, + "pidfile_preserved": pidfile.exists(), + "after_stop_status": after_stop.returncode, + "empty_reuse_status": empty_reused.returncode, + "empty_pid": empty_pid, + "bad_references": bad_references, + } + # PID namespace teardown also removes any replacement/orphaned agents. + print(json.dumps(report)) + + +@pytest.fixture(scope="module", params=[0, 1, 2], ids=["normal-proc", "restricted-proc", "hidden-proc"]) +def visibility_report(request): + if os.environ.get("KEYCHAIN_TEST_HIDEPID") != "1": + pytest.skip("set KEYCHAIN_TEST_HIDEPID=1 to run the isolated Linux mount test") + if not sys.platform.startswith("linux") or os.geteuid() != 0: + pytest.skip("requires Linux root to create private mount/PID namespaces, then drops to UID 65534") + for tool in ("unshare", "mount", "ps", "ssh-agent", "ssh-keygen", "ssh-add"): + if shutil.which(tool) is None: + pytest.skip(f"requires {tool}") + before = Path("/proc/self/mountinfo").read_text() + result = subprocess.run([ + "unshare", "--mount", "--pid", "--fork", "--mount-proc", "--propagation", "private", "--kill-child", + sys.executable, str(Path(__file__).resolve()), "--namespace-probe", str(request.param), + ], capture_output=True, text=True, timeout=90) + assert result.returncode == 0, result.stdout + result.stderr + assert Path("/proc/self/mountinfo").read_text() == before, "Host mount table changed" + report = json.loads(result.stdout) + summary = {**report, "cases": { + name: {key: value for key, value in case.items() if not key.endswith(("_output", "_json", "_references"))} + for name, case in report["cases"].items() + }} + print(json.dumps(summary, indent=2)) + return report + + +@pytest.mark.parametrize("backend", ["linux", "android"]) +def test_real_agent_visibility(visibility_report, backend): + report = visibility_report + case = report["cases"][backend] + assert report["uid"] == 65534 + assert report["control_visible"] + if report["hidepid"]: + assert any(re.search(r"hidepid=(?:1|2|noaccess|invisible)(?:,|$)", mount) for mount in report["proc_mounts"]) + assert case["pid_alive"] and case["manual_ssh_add_status"] == 0 + assert case["peer_credentials"]["uid"] == report["uid"] + assert case["comm_errno"] in ((errno.ENOENT, errno.EACCES, errno.EPERM) if report["hidepid"] else (0,)) + assert case["listed"] is (report["hidepid"] == 0) + + +@pytest.mark.parametrize("backend", ["linux", "android"]) +def test_keychain_reuses_working_agent(visibility_report, backend): + report = visibility_report + case = report["cases"][backend] + assert case["add_status"] == 0, case["add_output"] + assert case["subsequent_pid"] == case["original_pid"], case["add_output"] + assert case["empty_reuse_status"] == 0 + assert case["empty_pid"] == case["original_pid"] + + +@pytest.mark.parametrize("backend", ["linux", "android"]) +def test_inspect_reports_reachable_agent(visibility_report, backend): + report = visibility_report + case = report["cases"][backend] + assert case["inspect_lists_key"], case["inspect_output"] + data = case["inspect_json"]["agent_state"] + assert data["pidfile"]["process"]["identity"] == ("uninspectable" if report["hidepid"] else "verified") + assert data["selected"]["pid"] == str(case["original_pid"]) + assert "selected socket" in case["inspect_output"] + if report["hidepid"]: + assert "process details are inaccessible" in case["inspect_output"] + assert "hidepid" in case["inspect_output"] + + +@pytest.mark.parametrize("backend", ["linux", "android"]) +def test_keychain_loads_into_original_agent(visibility_report, backend): + case = visibility_report["cases"][backend] + assert case["load_status"] == 0, case["load_output"] + assert "SHA256:" in case["loaded_keys"] + + +@pytest.mark.parametrize("backend", ["linux", "android"]) +def test_responding_socket_does_not_excuse_wrong_pid(visibility_report, backend): + for reference in visibility_report["cases"][backend]["bad_references"].values(): + assert reference["pidfile"]["process"]["identity"] == "unverified" + assert reference["selected"]["socket"] is None + + +@pytest.mark.parametrize("backend", ["linux", "android"]) +def test_stop_preserves_hidden_agent_without_signaling(visibility_report, backend): + report = visibility_report + case = report["cases"][backend] + assert case["pidfile_preserved"] is bool(report["hidepid"]) + if report["hidepid"]: + assert case["after_stop_status"] == 0 + assert "pidfile kept" in case["stop_output"] + else: + assert case["after_stop_status"] == 2 + + +if __name__ == "__main__": + assert sys.argv[1] == "--namespace-probe" + _namespace_probe(int(sys.argv[2])) diff --git a/tests/test_state.py b/tests/test_state.py index 893f9f8..681c584 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -242,7 +242,7 @@ def test_render_inspect_json_emits_valid_object(paths, capsys): "reason": "empty", "severity": None, } - assert pidfile["process"] == {"pid": None, "alive": False} + assert pidfile["process"] == {"pid": None, "alive": False, "identity": "unset"} assert payload["agent_state"]["inherited"]["socket"]["reason"] == "empty" assert "supported" in payload["agent_state"]["processes"] assert isinstance(payload["keys"]["loaded_ssh_fingerprints"], list) From 1357942f5a0a6bc645757c6245cb6dbc94186ef9 Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:20:41 -0500 Subject: [PATCH 03/11] Fix Cygwin and MSYS2 process discovery and test real agent reuse Co-authored-by: Fumiyuki Shimizu <22541573+fmrns@users.noreply.github.com> --- .github/workflows/python-ci.yml | 30 ++++++++ src/keychain/runtime/platform.py | 30 ++++++-- tests/test_agent_lifecycle_e2e.py | 111 ++++++++++++++++++++++++++++++ tests/test_cli_startup.py | 41 ++++++++++- tests/test_e2e_playbooks.py | 2 + tests/test_runtime.py | 89 +++++++++++++++++++++++- 6 files changed, 293 insertions(+), 10 deletions(-) create mode 100644 tests/test_agent_lifecycle_e2e.py diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml index 69b487b..8a1db87 100644 --- a/.github/workflows/python-ci.yml +++ b/.github/workflows/python-ci.yml @@ -93,6 +93,32 @@ jobs: - name: pytest run: python -m pytest -v --tb=short --cov=src/keychain --cov-branch --cov-report=term-missing:skip-covered + # MSYS2's POSIX Python and OpenSSH, not setup-python's native Windows build. + test-msys2: + runs-on: windows-latest + timeout-minutes: 15 + defaults: + run: + shell: msys2 {0} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: msys2/setup-msys2@ec48f7c5447b3140e2b088413ae3a55687bccb6e # v2 + with: + msystem: UCRT64 + path-type: strict + update: true + install: python python-pytest openssh + - name: verify POSIX runtime and tools + run: | + /usr/bin/python -c 'import os, sys; print(sys.version, sys.platform); assert os.name == "posix" and sys.platform.startswith(("cygwin", "msys"))' + command -v python ps ssh-agent ssh-add ssh-keygen + ps --version + ssh -V + pacman -Q python openssh msys2-runtime + - name: process discovery and real agent lifecycle + run: | + /usr/bin/python -m pytest -v --tb=short tests/test_runtime.py tests/test_cli_startup.py tests/test_agent_lifecycle_e2e.py + # ------------------------------------------------------------------------- # Production-target authenticity: Rocky Linux 8 + python3.9 module. # @@ -199,12 +225,14 @@ jobs: needs: - static-analysis - test-fast + - test-msys2 - test-rocky8-py39 - test-full-sweep runs-on: ubuntu-latest env: STATIC_ANALYSIS_RESULT: ${{ needs.static-analysis.result }} TEST_FAST_RESULT: ${{ needs.test-fast.result }} + TEST_MSYS2_RESULT: ${{ needs.test-msys2.result }} TEST_ROCKY8_RESULT: ${{ needs.test-rocky8-py39.result }} TEST_FULL_SWEEP_RESULT: ${{ needs.test-full-sweep.result }} TEST_FULL_SWEEP_REQUIRED: >- @@ -219,6 +247,7 @@ jobs: run: | echo "static-analysis: ${STATIC_ANALYSIS_RESULT}" echo "test-fast: ${TEST_FAST_RESULT}" + echo "test-msys2: ${TEST_MSYS2_RESULT}" echo "test-rocky8-py39: ${TEST_ROCKY8_RESULT}" echo "test-full-sweep: ${TEST_FULL_SWEEP_RESULT} (required: ${TEST_FULL_SWEEP_REQUIRED})" @@ -227,6 +256,7 @@ jobs: for result in \ "${STATIC_ANALYSIS_RESULT}" \ "${TEST_FAST_RESULT}" \ + "${TEST_MSYS2_RESULT}" \ "${TEST_ROCKY8_RESULT}" do if [ "${result}" != "success" ]; then diff --git a/src/keychain/runtime/platform.py b/src/keychain/runtime/platform.py index 35e66f7..889c0fe 100644 --- a/src/keychain/runtime/platform.py +++ b/src/keychain/runtime/platform.py @@ -20,6 +20,8 @@ import shutil import subprocess +from ..util import KeychainError + class Platform: """Resolved host environment. @@ -96,20 +98,36 @@ def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int] except OSError: continue # exited mid-scan, or process details are restricted return pids + cygwin_ps = self.name == "cygwin" or self.name.startswith("msys") try: proc = subprocess.Popen( # illumos/Solaris treats everything after '=' in one -o # argument as header text, including commas. Separate -o # options preserve all three columns across POSIX hosts. - ["ps", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm="], + ["ps", "-e", "-l"] if cygwin_ps else ["ps", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm="], stdout=subprocess.PIPE, - stderr=subprocess.DEVNULL, + stderr=subprocess.PIPE, + # Cygwin/MSYS ps truncates command names to COLUMNS even in a pipe. + env={key: value for key, value in os.environ.items() if key != "COLUMNS"}, ) - stdout, _ = proc.communicate() - except OSError: - return pids + stdout, stderr = proc.communicate() + except OSError as exc: + raise KeychainError(f"Process discovery failed: cannot run ps: {exc}") from exc + if proc.returncode: + detail = stderr.decode(errors="replace").strip() or "no error output" + raise KeychainError(f"Process discovery failed: ps exited with status {proc.returncode}: {detail}") for line in stdout.decode(errors="replace").splitlines(): - parts = line.split(None, 2) + if cygwin_ps: + # ps -l starts with a status character. STIME is eight characters + # wide, including spaces in dates such as " Nov 1". + match = re.match( + r"^.\s*(\d+)\s+\d+\s+\d+\s+\d+\s+\S+\s+(\d+) .{8} (.+)$", line + ) + if not match: + continue + parts = list(match.groups()) + else: + parts = line.split(None, 2) if len(parts) < 3: continue try: diff --git a/tests/test_agent_lifecycle_e2e.py b/tests/test_agent_lifecycle_e2e.py new file mode 100644 index 0000000..d148d47 --- /dev/null +++ b/tests/test_agent_lifecycle_e2e.py @@ -0,0 +1,111 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Real agent discovery, key retention, and shutdown on POSIX-shaped hosts.""" + +import os +import re +import shutil +import signal +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +import pytest + +from keychain.env import SshAgentRef +from keychain.paths import KeychainPaths +from keychain.runtime import platform + +pytestmark = pytest.mark.skipif( + os.name == "nt" or not platform.detect().supported + or any(shutil.which(tool) is None for tool in ("ssh-agent", "ssh-add", "ssh-keygen")), + reason="requires a supported POSIX host and OpenSSH tools", +) +ROOT = Path(__file__).resolve().parents[1] + + +@pytest.mark.parametrize("columns", [None, "20", "80"]) +def test_agent_reuse_preserves_loaded_key(monkeypatch, columns): + monkeypatch.setattr(platform, "_cached", None) + if columns is None: + monkeypatch.delenv("COLUMNS", raising=False) + else: + monkeypatch.setenv("COLUMNS", columns) + # Short paths also fit macOS sockaddr_un; spaces exercise real ps parsing. + with tempfile.TemporaryDirectory(prefix="kc-life-", dir="/tmp") as temporary: + home = Path(temporary) / "test home" + home.mkdir(mode=0o700) + paths = KeychainPaths.build(str(home / ".keychain"), True, "test") + env = {key: value for key, value in os.environ.items() if not key.startswith("KEYCHAIN_")} + env.update(HOME=str(home), PYTHONPATH=str(ROOT / "src"), SSH_ASKPASS_REQUIRE="never") + for key in ("SSH_AUTH_SOCK", "SSH_AGENT_PID", "XDG_CONFIG_HOME", "XDG_RUNTIME_DIR"): + env.pop(key, None) + pids = set() + + def keychain(*args): + try: + return subprocess.run( + [sys.executable, "-m", "keychain", *args, "--host", "test", + "--dir", str(paths.keydir), "--absolute", "--nocolor"], + env=env, capture_output=True, text=True, timeout=30, + ) + finally: + # Cleanup must not depend on process discovery working correctly. + pidfile = paths.pidfile_path("sh") + if pidfile.exists(): + match = re.search(r"^SSH_AGENT_PID=(\d+);", pidfile.read_text(), re.M) + if match: + pids.add(int(match.group(1))) + + def run(*args, agent=None): + return subprocess.run( + args, env={**env, **(agent.as_dict() if agent else {})}, + capture_output=True, text=True, timeout=30, + ) + + try: + first = keychain("add", "--eval", "--noask", "--no-inherit") + assert first.returncode == 0, first.stdout + first.stderr + agent = SshAgentRef.from_text(first.stdout) + assert agent.pid_int is not None + assert agent.sock == str(paths.ssh_agent_socket_path) + visible = platform.detect().process_list(re.compile(r"(?:^|/)ssh-agent$"), os.getuid()) + assert agent.pid_int in visible, { + "agent": agent, "uid": os.getuid(), "COLUMNS": os.environ.get("COLUMNS"), + "platform": repr(platform.detect()), "ps_path": shutil.which("ps"), + "ps": run("ps", "-e", "-l").stdout, + "ssh-add": run("ssh-add", "-l", agent=agent), + } + + key = str(home / "test-key") + generated = run("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key) + assert generated.returncode == 0, generated.stderr + fingerprint = run("ssh-keygen", "-lf", key + ".pub") + assert fingerprint.returncode == 0, fingerprint.stderr + expected = fingerprint.stdout.split()[1] + added = run("ssh-add", key, agent=agent) + assert added.returncode == 0, added.stderr + + for _ in range(3): + reused = keychain("add", "--eval", "--noask", "--no-inherit") + assert reused.returncode == 0, reused.stdout + reused.stderr + assert SshAgentRef.from_text(reused.stdout) == agent + assert pids == {agent.pid_int}, "Keychain started another agent instead of reusing it" + loaded = run("ssh-add", "-l", agent=agent) + assert loaded.returncode == 0, loaded.stderr + assert expected in loaded.stdout + + stopped = keychain("agent", "stop") + assert stopped.returncode == 0, stopped.stdout + stopped.stderr + assert not paths.pidfile_path("sh").exists() + deadline = time.monotonic() + 5 + while run("ssh-add", "-l", agent=agent).returncode != 2: + assert time.monotonic() < deadline, "agent still responds after Keychain stopped it" + time.sleep(0.05) + finally: + for pid in pids: + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + pass diff --git a/tests/test_cli_startup.py b/tests/test_cli_startup.py index f012e8f..d5cdb87 100644 --- a/tests/test_cli_startup.py +++ b/tests/test_cli_startup.py @@ -1,6 +1,7 @@ # SPDX-License-Identifier: GPL-3.0-only """CLI startup behavior tests.""" +import os import subprocess import sys from pathlib import Path @@ -8,11 +9,49 @@ import pytest -from keychain import main +from keychain import agents, main +from keychain.paths import KeychainPaths from keychain.util import KeychainError from tests.support import set_home +@pytest.mark.skipif(os.name == "nt", reason="requires POSIX file ownership") +@pytest.mark.parametrize("action", [["add", "--noask", "--eval"], ["env"], ["agent", "stop"]]) +@pytest.mark.parametrize("failure", ["exit", "launch"]) +def test_failed_discovery_preserves_agent_reference(tmp_path, monkeypatch, capsys, action, failure): + set_home(monkeypatch, tmp_path, patch_path_home=True) + monkeypatch.delenv("KEYCHAIN_CONFIG", raising=False) + monkeypatch.delenv("KEYCHAIN_SSH_AGENT_ARGS", raising=False) + monkeypatch.delenv("SSH_AUTH_SOCK", raising=False) + monkeypatch.delenv("SSH_AGENT_PID", raising=False) + paths = KeychainPaths.build(str(tmp_path / ".keychain"), True, "test") + paths.keydir.mkdir(mode=0o700) + pidfile = paths.pidfile_path("sh") + contents = "SSH_AUTH_SOCK=/test.sock; export SSH_AUTH_SOCK;\nSSH_AGENT_PID=123; export SSH_AGENT_PID;\n" + pidfile.write_text(contents) + pidfile.chmod(0o600) + monkeypatch.setattr(main.platform, "_cached", main.platform._PosixPlatform("cygwin")) + monkeypatch.setattr(agents, "validate_ssh_socket", lambda sock: agents.SocketValidation(sock, True)) + + def fail_ps(cmd, **_kwargs): + assert cmd == ["ps", "-e", "-l"], "must not launch a replacement agent" + if failure == "launch": + raise FileNotFoundError("test ps missing") + return SimpleNamespace(returncode=1, communicate=lambda: (b"", b"test ps failure")) + + monkeypatch.setattr(main.platform.subprocess, "Popen", fail_ps) + monkeypatch.setattr(agents.os, "kill", lambda *_a: pytest.fail("must not signal an agent")) + with pytest.raises(SystemExit) as exc: + main.main([*action, "--nocolor", "--host", "test", "--dir", str(paths.keydir), "--absolute"]) + captured = capsys.readouterr() + assert exc.value.code == 1 + assert "Process discovery failed" in captured.err + assert "test ps" in captured.err + assert "Traceback" not in captured.err + assert captured.out.strip() == ("false;" if "--eval" in action else "") + assert pidfile.read_text() == contents + + def test_debug_reports_loaded_keychainrc_even_when_quiet(tmp_path, monkeypatch, capsys): home = tmp_path / "home" home.mkdir() diff --git a/tests/test_e2e_playbooks.py b/tests/test_e2e_playbooks.py index 153f03e..12a1c9e 100644 --- a/tests/test_e2e_playbooks.py +++ b/tests/test_e2e_playbooks.py @@ -381,6 +381,8 @@ def test_wipe_routes_ssh_and_gpg_targets(playbook: PlaybookRunner, monkeypatch): monkeypatch.setattr(platform, "detect", lambda *_args, **_kwargs: platform._classify("linux", has_ps=True)) monkeypatch.setattr(agents.SshAgent, "wipe", lambda self: calls.append("ssh")) monkeypatch.setattr(agents.GpgOperations, "wipe", lambda self: calls.append("gpg")) + # This routing-only test starts no agents, including during fixture cleanup. + monkeypatch.setattr(agents, "findpids", lambda _prog: []) playbook.set_host("testhost") diff --git a/tests/test_runtime.py b/tests/test_runtime.py index b78c2e2..2762436 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -1,12 +1,14 @@ # SPDX-License-Identifier: GPL-3.0-only """Tests for :mod:`keychain.runtime` platform detection.""" +import os import re from types import SimpleNamespace import pytest from keychain.runtime import platform +from keychain.util import KeychainError @pytest.fixture(autouse=True) @@ -69,8 +71,7 @@ def test_unsupported_process_list_raises(): def test_supported_process_list_returns_list(): - # Use the host's actual ``ps`` if available; otherwise the Popen call - # raises OSError and the method returns an empty list. + # Exercise the host's real discovery mechanism, not just a parser fixture. p = platform.detect() if not p.supported: pytest.skip("host platform unsupported") @@ -100,9 +101,91 @@ def fake_popen(cmd, **kwargs): lines = [" ".join(headers)] if any(headers) else [] lines.extend(" ".join(row[field] for field in fields) for row in rows) stdout = ("\n".join(lines) + "\n").encode() - return SimpleNamespace(communicate=lambda: (stdout, None)) + return SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")) monkeypatch.setattr(platform.subprocess, "Popen", fake_popen) p = platform.detect(platform_override="sunos5", has_ps=True) assert p.process_list(re.compile(r"(?:^|/)ssh-agent$"), uid=uid) == expected + + +@pytest.mark.parametrize("name", ["cygwin", "msys", "msys2"]) +@pytest.mark.parametrize("uid, expected", [(1000, [123, 789]), (2000, [456]), (None, [123, 456, 789])]) +@pytest.mark.parametrize("columns", [None, "20", "80"]) +def test_process_list_with_cygwin_ps(monkeypatch, name, uid, expected, columns): + if columns is None: + monkeypatch.delenv("COLUMNS", raising=False) + else: + monkeypatch.setenv("COLUMNS", columns) + parent_env = dict(os.environ) + stdout = ( + b" PID PPID PGID WINPID TTY UID STIME COMMAND\n" + b" 123 1 123 52000 ? 1000 15:39:13 /usr/bin/ssh-agent\n" + b"S 456 1 456 53000 ? 2000 15:39:13 /usr/bin/ssh-agent\n" + b"I 789 1 789 54000 ? 1000 15:39:13 /path with spaces/ssh-agent\n" + b" 987 1 987 55000 ? 1000 15:39:13 /usr/bin/ssh-agent-helper\n" + b" 988 1 988 56000 ? 1000 15:39:13 /usr/bin/ssh-agent \n" + b"invalid row\n" + ) + + def fake_popen(cmd, **kwargs): + assert cmd == ["ps", "-e", "-l"] + assert kwargs["env"] == {key: value for key, value in parent_env.items() if key != "COLUMNS"} + return SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")) + + monkeypatch.setattr(platform.subprocess, "Popen", fake_popen) + p = platform.detect(platform_override=name, has_ps=True) + + assert p.process_list(re.compile(r"(?:^|/)ssh-agent$"), uid=uid) == expected + assert dict(os.environ) == parent_env + + +@pytest.mark.parametrize("name", ["cygwin", "msys", "msys2"]) +@pytest.mark.parametrize("stime", ["15:39:13", " Nov 1", " Nov 12"]) +def test_process_list_with_cygwin_stime(monkeypatch, name, stime): + stdout = ( + " PID PPID PGID WINPID TTY UID STIME COMMAND\n" + f" 123 1 123 52000 ? 1000 {stime} /path with spaces/ssh-agent\n" + ).encode() + + def fake_popen(cmd, **kwargs): + assert cmd == ["ps", "-e", "-l"] + return SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")) + + monkeypatch.setattr(platform.subprocess, "Popen", fake_popen) + p = platform.detect(platform_override=name, has_ps=True) + + assert p.process_list(re.compile(r"^/path with spaces/ssh-agent$"), uid=1000) == [123] + + +@pytest.mark.parametrize("name", ["sunos5", "darwin", "cygwin", "msys2"]) +@pytest.mark.parametrize("status", [1, 2, -15]) +@pytest.mark.parametrize("stderr", [b"ps: unsupported option\n", b"", b"invalid byte: \xff"]) +def test_failed_ps_is_not_an_empty_process_list(monkeypatch, name, status, stderr): + def fake_popen(_cmd, **kwargs): + assert kwargs["stderr"] == platform.subprocess.PIPE + return SimpleNamespace(returncode=status, communicate=lambda: (b"123 1000 ssh-agent\n", stderr)) + + monkeypatch.setattr(platform.subprocess, "Popen", fake_popen) + with pytest.raises(KeychainError, match=f"Process discovery failed: ps exited with status {status}") as exc: + platform._PosixPlatform(name).process_list(re.compile("ssh-agent")) + assert (stderr.decode(errors="replace").strip() or "no error output") in str(exc.value) + + +@pytest.mark.parametrize("error", [FileNotFoundError("ps missing"), PermissionError("ps not executable")]) +def test_ps_launch_failure_is_fatal(monkeypatch, error): + def fail(*_args, **_kwargs): + raise error + + monkeypatch.setattr(platform.subprocess, "Popen", fail) + with pytest.raises(KeychainError, match="Process discovery failed: cannot run ps"): + platform._PosixPlatform("cygwin").process_list(re.compile("ssh-agent")) + + +@pytest.mark.parametrize("stdout", [b"", b"123 1000 other-command\n"]) +def test_successful_ps_without_matching_agents_is_valid(monkeypatch, stdout): + monkeypatch.setattr( + platform.subprocess, "Popen", + lambda *_a, **_k: SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")), + ) + assert platform._PosixPlatform("sunos5").process_list(re.compile("ssh-agent")) == [] From 64b9cb293c190bd5309518a2000509b3eaabd8aa Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:20:45 -0500 Subject: [PATCH 04/11] Restore legacy stop selections and exclude dead Linux agents --- src/keychain/runtime/compat.py | 4 +- src/keychain/runtime/platform.py | 6 ++- tests/test_cli_actions.py | 42 +++++++++++++++++- tests/test_cli_legacy.py | 8 ++-- tests/test_compat.py | 10 ++--- tests/test_runtime.py | 76 ++++++++++++++++++++++++++++++++ 6 files changed, 133 insertions(+), 13 deletions(-) diff --git a/src/keychain/runtime/compat.py b/src/keychain/runtime/compat.py index d0a4b69..23db0a1 100644 --- a/src/keychain/runtime/compat.py +++ b/src/keychain/runtime/compat.py @@ -188,9 +188,9 @@ def translate(self, argv: list[str]) -> list[str]: if key in ("--stop", "-k"): if subcmd is None: subcmd = "agent" - if value == "all": + if value == "mine": sub_args = ["stop"] - elif value in ("mine", "others"): + elif value in ("all", "others"): sub_args = ["stop", f"--{value}"] else: sub_args = ["stop", value] diff --git a/src/keychain/runtime/platform.py b/src/keychain/runtime/platform.py index 889c0fe..ceec061 100644 --- a/src/keychain/runtime/platform.py +++ b/src/keychain/runtime/platform.py @@ -93,7 +93,11 @@ def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int] if not entry.isdigit() or (uid is not None and os.stat(f"/proc/{entry}").st_uid != uid): continue with open(f"/proc/{entry}/comm", encoding="utf-8", errors="replace") as handle: - if pattern.search(handle.read().strip()): + if not pattern.search(handle.read().strip()): + continue + with open(f"/proc/{entry}/stat", encoding="utf-8", errors="replace") as handle: + # Skip zombie/dead tasks; the parenthesized name can contain ')'. + if handle.read().rpartition(")")[2].split()[0] not in ("Z", "X", "x"): pids.append(int(entry)) except OSError: continue # exited mid-scan, or process details are restricted diff --git a/tests/test_cli_actions.py b/tests/test_cli_actions.py index 488772c..3e81a5e 100644 --- a/tests/test_cli_actions.py +++ b/tests/test_cli_actions.py @@ -1,12 +1,14 @@ # SPDX-License-Identifier: GPL-3.0-only """CLI action-resolution and handler tests.""" +import signal import subprocess from types import SimpleNamespace import pytest -from keychain import keys, main +from keychain import agents, keys, main +from keychain.env import SshAgentRef from keychain.main import KeychainApp from keychain.output.core import Output from keychain.paths import KeychainPaths @@ -30,6 +32,44 @@ def test_agent_stop_action(self): assert KeychainApp(ns, out)._resolve_action() == "agent_stop" assert ns.get_value("target") == "mine" + @pytest.mark.parametrize( + "argv, expected", + [ + (["--stop", "mine"], [101]), + (["--stop=mine"], [101]), + (["-k", "mine"], [101]), + (["-qk", "mine"], [101]), + (["--stop", "all"], [101, 202]), + (["--stop=all"], [101, 202]), + (["-k", "all"], [101, 202]), + (["--stop", "others"], [202]), + (["--stop=others"], [202]), + (["-k", "others"], [202]), + (["agent", "stop"], [101]), + (["agent", "stop", "--mine"], [101, 202]), + (["agent", "stop", "--all"], [101, 202]), + (["agent", "stop", "--others"], [202]), + ], + ) + def test_stop_signals_the_requested_agents(self, monkeypatch, argv, expected): + args = RuntimeConfig.resolve(argv) + out = Output.build(quiet=True, debug=False, eval_mode=False, color=False) + state = SimpleNamespace( + user="tester", + pidfile_env=SshAgentRef("/test.sock", "101"), + paths=SimpleNamespace(ensure_keydir=lambda: None, clear=lambda: None), + ) + state.ssh = agents.SshAgent(state, out) + app = KeychainApp(args, out) + app._kstate = state + signaled = [] + monkeypatch.setattr(agents, "findpids", lambda _prog: [101, 202]) + monkeypatch.setattr(agents.os, "kill", lambda pid, sig: signaled.append((pid, sig))) + + assert app._resolve_action() == "agent_stop" + assert app._handle_agent_stop_action() == 0 + assert signaled == [(pid, signal.SIGTERM) for pid in expected] + def test_agent_stop_defaults_to_pidfile_when_no_target_is_selected(self): """The stop handler applies its own runtime fallback when no target flag was parsed.""" ns = RuntimeConfig.resolve(["agent", "stop"]) diff --git a/tests/test_cli_legacy.py b/tests/test_cli_legacy.py index 994b6cf..ab5e9b5 100644 --- a/tests/test_cli_legacy.py +++ b/tests/test_cli_legacy.py @@ -17,15 +17,15 @@ def test_legacy_list(self): assert ns.action == "list" def test_legacy_stop_all(self): - """The compat shim now treats `all` as the implicit stop default, not an explicit parsed target.""" + """Legacy all selects every agent owned by this user, not just the pidfile agent.""" ns = RuntimeConfig.resolve(["--stop", "all"]) assert ns.action == "agent stop" - assert ns.get_value("target") is None + assert ns.get_value("target") == "all" def test_legacy_stop_mine(self): ns = RuntimeConfig.resolve(["--stop", "mine"]) assert ns.action == "agent stop" - assert ns.get_value("target") == "mine" + assert ns.get_value("target") is None def test_legacy_stop_others(self): ns = RuntimeConfig.resolve(["-k", "others"]) @@ -145,7 +145,7 @@ def test_legacy_missing_wipe_value_rejected(self): "argv,flag,replacement", [ (["id_rsa", "--list"], "--list", "list"), - (["id_rsa", "--stop", "mine"], "--stop", "agent stop --mine"), + (["id_rsa", "--stop", "mine"], "--stop", "agent stop"), ], ) @pytest.mark.skip( diff --git a/tests/test_compat.py b/tests/test_compat.py index 1d71e4d..20fc6dc 100644 --- a/tests/test_compat.py +++ b/tests/test_compat.py @@ -84,15 +84,15 @@ def test_help_and_version(self): def test_stop_with_value(self): # Legacy ``--stop X`` / ``-k X`` translates to the new ``agent stop`` - # domain form (with --mine/--others flags; bare = all). - assert translate(["--stop", "all"]) == ["agent", "stop"] - assert translate(["--stop", "mine"]) == ["agent", "stop", "--mine"] - assert translate(["-k", "mine"]) == ["agent", "stop", "--mine"] + # domain form (bare = pidfile agent; --all = all of the user's agents). + assert translate(["--stop", "all"]) == ["agent", "stop", "--all"] + assert translate(["--stop", "mine"]) == ["agent", "stop"] + assert translate(["-k", "mine"]) == ["agent", "stop"] assert translate(["-k", "others"]) == ["agent", "stop", "--others"] def test_stop_with_equals(self): assert translate(["--stop=others"]) == ["agent", "stop", "--others"] - assert translate(["--stop=all"]) == ["agent", "stop"] + assert translate(["--stop=all"]) == ["agent", "stop", "--all"] def test_wipe_with_value(self): # ``--wipe ssh`` -> ``wipe --ssh``; ``--wipe gpg`` -> ``wipe --gpg``; diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 2762436..f9f0976 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -1,8 +1,12 @@ # SPDX-License-Identifier: GPL-3.0-only """Tests for :mod:`keychain.runtime` platform detection.""" +import io import os import re +import subprocess +import sys +import time from types import SimpleNamespace import pytest @@ -79,6 +83,78 @@ def test_supported_process_list_returns_list(): assert isinstance(result, list) +@pytest.mark.parametrize("state", ["R", "S", "D", "T", "t", "I", "Z", "X", "x"]) +@pytest.mark.parametrize("comm", ["ssh-agent", "ssh ) agent ("]) +def test_proc_discovery_checks_process_state(monkeypatch, state, comm): + reads = [] + + def read(path, **_kwargs): + reads.append(path) + return io.StringIO( + { + "/proc/123/comm": f"{comm}\n", + "/proc/123/stat": f"123 ({comm}) {state} 1 123 123 0\n", + }[path] + ) + + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) + monkeypatch.setattr(platform.os, "listdir", lambda _path: ["self", "123"]) + monkeypatch.setattr(platform.os, "stat", lambda _path: SimpleNamespace(st_uid=1000)) + monkeypatch.setattr(platform, "open", read, raising=False) + monkeypatch.setattr(platform.subprocess, "Popen", lambda *_a, **_k: pytest.fail("must not run ps")) + + p = platform._PosixPlatform("linux") + assert p.process_list(re.compile(re.escape(comm) + "$"), uid=1000) == ([] if state in ("Z", "X", "x") else [123]) + assert reads == ["/proc/123/comm", "/proc/123/stat"] + reads.clear() + assert p.process_list(re.compile("unrelated-command"), uid=1000) == [] + assert reads == ["/proc/123/comm"] + reads.clear() + assert p.process_list(re.compile(re.escape(comm) + "$"), uid=2000) == [] + assert reads == [] + + +@pytest.mark.parametrize("error", [FileNotFoundError, PermissionError]) +def test_proc_discovery_skips_unreadable_state(monkeypatch, error): + def read(path, **_kwargs): + if path.endswith("/comm"): + return io.StringIO("ssh-agent\n") + raise error(path) + + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) + monkeypatch.setattr(platform.os, "listdir", lambda _path: ["123"]) + monkeypatch.setattr(platform, "open", read, raising=False) + assert platform._PosixPlatform("linux").process_list(re.compile("ssh-agent")) == [] + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="requires Linux /proc and prctl") +def test_proc_discovery_excludes_real_zombie(): + # The child exits without being reaped, keeping its /proc entry available. + code = """ +import ctypes +import os +libc = ctypes.CDLL(None, use_errno=True) +if libc.prctl(15, ctypes.c_char_p(b"ssh-agent"), 0, 0, 0) != 0: + raise OSError(ctypes.get_errno(), "PR_SET_NAME") +os._exit(0) +""" + with subprocess.Popen([sys.executable, "-c", code]) as child: + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + with open(f"/proc/{child.pid}/stat") as handle: + if handle.read().rpartition(")")[2].split()[0] == "Z": + break + time.sleep(0.01) + else: + child.kill() + pytest.fail("child did not exit within 10 seconds") + with open(f"/proc/{child.pid}/comm") as handle: + assert handle.read().strip() == "ssh-agent" + assert child.pid not in platform._PosixPlatform("linux").process_list( + re.compile(r"^ssh-agent$"), uid=os.getuid() + ) + + @pytest.mark.parametrize("uid, expected", [(1000, [123]), (2000, [456]), (None, [123, 456])]) def test_process_list_with_illumos_ps(monkeypatch, uid, expected): """illumos consumes the remainder of each -o argument as header text.""" From b2ba813bf06c23244ddd0aa923e1b964af02c844 Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:20:51 -0500 Subject: [PATCH 05/11] Isolate and validate process discovery across supported platforms Co-authored-by: tarilka0gg <216761460+tarilka0gg@users.noreply.github.com> --- .github/workflows/python-ci.yml | 87 ++++++++++- man/embedded-docs.txt | 20 +-- scripts/test_posix_vm.py | 51 +++++++ src/keychain/agents.py | 14 +- src/keychain/runtime/compat.py | 2 +- src/keychain/runtime/platform.py | 182 +++++++++++++--------- tests/test_agent_lifecycle_e2e.py | 5 +- tests/test_agent_visibility.py | 12 +- tests/test_cli_startup.py | 10 +- tests/test_hidden_agent_e2e.py | 6 +- tests/test_posix_vm_runner.py | 52 +++++++ tests/test_runtime.py | 242 ++++++++++++++++++++++++++++-- tests/test_ssh_confirm_e2e.py | 81 +++++++++- 13 files changed, 645 insertions(+), 119 deletions(-) create mode 100644 scripts/test_posix_vm.py create mode 100644 tests/test_posix_vm_runner.py diff --git a/.github/workflows/python-ci.yml b/.github/workflows/python-ci.yml index 8a1db87..6be3fb9 100644 --- a/.github/workflows/python-ci.yml +++ b/.github/workflows/python-ci.yml @@ -82,7 +82,7 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: install shells and manual renderer for tests if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y fish tcsh groff + run: sudo apt-get update && sudo apt-get install -y fish tcsh groff busybox - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: ${{ matrix.python-version }} @@ -119,6 +119,77 @@ jobs: run: | /usr/bin/python -m pytest -v --tb=short tests/test_runtime.py tests/test_cli_startup.py tests/test_agent_lifecycle_e2e.py + # Real kernels and native ps/OpenSSH, not Linux containers or parser fixtures. + # Each VM uses a dedicated ordinary user and a private copy of the checkout. + test-freebsd: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1 + with: + release: '14.4' + mem: 2048 + cpu: 2 + sync: rsync + copyback: false + prepare: | + pkg install -y python312 py312-pytest + pw useradd kctest -m -d /tmp/keychain-home -s /bin/sh + run: | + cp -R . /tmp/keychain-home/repo + chown -R kctest /tmp/keychain-home/repo + su - kctest -c 'cd /tmp/keychain-home/repo && /usr/local/bin/python3.12 scripts/test_posix_vm.py freebsd' + + test-openbsd: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: vmactions/openbsd-vm@f1ca8bc8ecc5b6ef7218e5b914836e067e1546d3 # v1 + with: + release: '8.0' + mem: 2048 + cpu: 2 + sync: rsync + copyback: false + prepare: | + pkg_add -I py3-test + python3 -c 'import pytest' + useradd -m -d /tmp/keychain-home -s /bin/sh kctest + run: | + cp -R . /tmp/keychain-home/repo + chown -R kctest /tmp/keychain-home/repo + su - kctest -c 'cd /tmp/keychain-home/repo && /usr/local/bin/python3 scripts/test_posix_vm.py openbsd' + + test-omnios: + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - uses: vmactions/omnios-vm@aeee92416495d9685b2997d954f6b063ae5b832d # v1 + with: + release: 'r151054' + mem: 2048 + cpu: 2 + sync: rsync + copyback: false + prepare: | + pkg install runtime/python-313 library/python-3/pip-313 + python3.13 -m venv --without-pip /opt/keychain-test + python3.13 -m pip --python /opt/keychain-test/bin/python install 'pytest>=8,<9' + useradd -m -d /tmp/keychain-home -s /bin/sh kctest + run: | + cp -R . /tmp/keychain-home/repo + chown -R kctest /tmp/keychain-home/repo + su - kctest -c 'cd /tmp/keychain-home/repo && /opt/keychain-test/bin/python scripts/test_posix_vm.py sunos' + # ------------------------------------------------------------------------- # Production-target authenticity: Rocky Linux 8 + python3.9 module. # @@ -200,7 +271,7 @@ jobs: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 - name: install shells and manual renderer for tests if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y fish tcsh groff + run: sudo apt-get update && sudo apt-get install -y fish tcsh groff busybox - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: ${{ matrix.python-version }} @@ -226,6 +297,9 @@ jobs: - static-analysis - test-fast - test-msys2 + - test-freebsd + - test-openbsd + - test-omnios - test-rocky8-py39 - test-full-sweep runs-on: ubuntu-latest @@ -233,6 +307,9 @@ jobs: STATIC_ANALYSIS_RESULT: ${{ needs.static-analysis.result }} TEST_FAST_RESULT: ${{ needs.test-fast.result }} TEST_MSYS2_RESULT: ${{ needs.test-msys2.result }} + TEST_FREEBSD_RESULT: ${{ needs.test-freebsd.result }} + TEST_OPENBSD_RESULT: ${{ needs.test-openbsd.result }} + TEST_OMNIOS_RESULT: ${{ needs.test-omnios.result }} TEST_ROCKY8_RESULT: ${{ needs.test-rocky8-py39.result }} TEST_FULL_SWEEP_RESULT: ${{ needs.test-full-sweep.result }} TEST_FULL_SWEEP_REQUIRED: >- @@ -248,6 +325,9 @@ jobs: echo "static-analysis: ${STATIC_ANALYSIS_RESULT}" echo "test-fast: ${TEST_FAST_RESULT}" echo "test-msys2: ${TEST_MSYS2_RESULT}" + echo "test-freebsd: ${TEST_FREEBSD_RESULT}" + echo "test-openbsd: ${TEST_OPENBSD_RESULT}" + echo "test-omnios: ${TEST_OMNIOS_RESULT}" echo "test-rocky8-py39: ${TEST_ROCKY8_RESULT}" echo "test-full-sweep: ${TEST_FULL_SWEEP_RESULT} (required: ${TEST_FULL_SWEEP_REQUIRED})" @@ -257,6 +337,9 @@ jobs: "${STATIC_ANALYSIS_RESULT}" \ "${TEST_FAST_RESULT}" \ "${TEST_MSYS2_RESULT}" \ + "${TEST_FREEBSD_RESULT}" \ + "${TEST_OPENBSD_RESULT}" \ + "${TEST_OMNIOS_RESULT}" \ "${TEST_ROCKY8_RESULT}" do if [ "${result}" != "success" ]; then diff --git a/man/embedded-docs.txt b/man/embedded-docs.txt index 4afcc68..bd77f48 100644 --- a/man/embedded-docs.txt +++ b/man/embedded-docs.txt @@ -97,7 +97,7 @@ See also: `topic:extkeys`, `topic:coordination`. @syntax keychain agent [OPTIONS] -Domain command for managing agent processes without loading keys. `agent start` ensures an agent exists and can emit its environment; `agent stop` terminates agents recorded in the pidfile. +Domain command for managing agent processes without loading keys. `agent start` ensures an agent exists and can emit its environment; `agent stop` terminates the pidfile agent, or with a target option, the user's other visible agents. == @action agent start: fork an agent if none is running (no key load) @@ -105,11 +105,11 @@ Domain command for managing agent processes without loading keys. `agent start` Start an `ssh-agent` if none is running, then optionally emit its environment for the current shell. By default, Keychain pins a spawned `ssh-agent` to a host-specific socket path under `~/.keychain/` so the agent endpoint stays stable across WSL and other early startup environments that may clean `/tmp`. This action does not load any keys; use `add` when you want prompt-and-load semantics. -== @action agent stop: terminate ssh-agents (default: all in pidfile) +== @action agent stop: terminate ssh-agents (default: the pidfile agent) -@syntax keychain agent stop [--mine|--others] +@syntax keychain agent stop [--mine|--others|--all] -Terminate the ssh-agents recorded in the pidfile. Bare `agent stop` targets every recorded agent; `--mine` and `--others` narrow the kill list by owner UID. +Terminate ssh-agents. Bare `agent stop` stops only the agent recorded in the pidfile. `--mine` and `--all` stop every visible ssh-agent owned by the calling user, and `--others` stops the user's visible agents except the pidfile agent. Agents owned by other users are never signaled. == @action list: List keys currently held by ssh-agent. @@ -319,17 +319,17 @@ Don't trust `$SSH_AUTH_SOCK` / `$SSH_AGENT_PID` from the parent environment; alw Use PATH as the ssh-agent socket explicitly. When this option is not supplied, Keychain now chooses a host-specific managed socket path under `~/.keychain/` instead of letting `ssh-agent` pick a transient location under `/tmp`. Override it only when integrating with another tool that expects a specific socket path. -== @option mine: terminate only this UID's agents +== @option mine: terminate all of this user's agents -Restrict the kill list to agents whose owner UID matches the calling user. Useful in shared accounts or root-cron contexts where you must not touch other users' agents. +Terminate every visible ssh-agent owned by the calling user, not only the pidfile agent. Agents owned by other users are never signaled. Same selection as `--all`; this is not the legacy `--stop mine`, which is plain `agent stop`. -== @option others: terminate agents owned by others +== @option others: terminate this user's other agents -Inverse of `--mine`: terminate only agents whose owner UID does *not* match the calling user. Rare; typically a maintenance tool. +Terminate the calling user's visible ssh-agents except the pidfile agent. Agents owned by other users are never signaled. -== @option all: terminate all candidate agents +== @option all: terminate all of this user's agents -Terminate every candidate agent recorded in the pidfile, regardless of owner. This is the default target for `keychain agent stop`. +Terminate every visible ssh-agent owned by the calling user, not only the pidfile agent. Without any target option, `keychain agent stop` stops only the pidfile agent. == @option list-json: emit machine-readable JSON on stdout diff --git a/scripts/test_posix_vm.py b/scripts/test_posix_vm.py new file mode 100644 index 0000000..d3f6d90 --- /dev/null +++ b/scripts/test_posix_vm.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the native POSIX acceptance suite as the VM's unprivileged test user.""" + +import os +import shutil +import subprocess +import sys + +import pytest + + +class RequiredLiveTests: + def __init__(self): + self.passed = set() + + def pytest_runtest_logreport(self, report): + if report.when == "call" and report.passed: + self.passed.add(report.nodeid) + + +def main(): + if not sys.platform.startswith(sys.argv[1]) or os.getuid() == 0: + raise RuntimeError(f"Expected unprivileged {sys.argv[1]}, got {sys.platform} uid={os.getuid()}") + print(sys.version, sys.platform, os.uname(), flush=True) + for tool in ("ps", "ssh-agent", "ssh-add", "ssh-keygen"): + location = shutil.which(tool) + if location is None: + raise RuntimeError(f"Required test tool missing: {tool}") + print(f"{tool}: {location}", flush=True) + subprocess.run(["ssh", "-V"], check=True) + live = RequiredLiveTests() + result = pytest.main([ + "-v", "--tb=short", "-rs", + "tests/test_runtime.py", "tests/test_agent_visibility.py", + "tests/test_cli_startup.py", "tests/test_agent_lifecycle_e2e.py", + ], plugins=[live]) + required = { + "tests/test_runtime.py::test_supported_process_list_returns_list", + "tests/test_runtime.py::test_real_ps_discovers_agent_launched_from_long_path", + *{f"tests/test_agent_lifecycle_e2e.py::test_agent_reuse_preserves_loaded_key[{value}]" + for value in ("None", "20", "80")}, + } + missing = required - live.passed + if missing: + print(f"Required live tests did not pass: {sorted(missing)}", file=sys.stderr) + return int(result) or int(bool(missing)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/keychain/agents.py b/src/keychain/agents.py index a28489d..8946555 100644 --- a/src/keychain/agents.py +++ b/src/keychain/agents.py @@ -366,7 +366,7 @@ def _validate_candidate(self, source: str, agent_env: SshAgentRef, *, announce: out.note("Ignoring gpg-agent SSH socket; Keychain manages SSH keys with ssh-agent.") return None - pid_status = self.keychain_state.ssh_pid_status(agent_env.pid_int) if pid_str else "unset" + pid_status = self.keychain_state.ssh_pid_status(agent_env.pid_int) if pid_str and pid_status not in ("verified", "uninspectable"): out.debug(f"SSH_AGENT_PID in {source} ({pid_str}) is not a running ssh-agent; ignoring it") if visible: @@ -526,6 +526,9 @@ def stop(self, which: str) -> None: if pidf_env: self.env = pidf_env pids = findpids("ssh") + hidden = which != "others" and ( + pidf_env.pid_int not in pids and self.keychain_state.ssh_pid_status(pidf_env.pid_int) == "uninspectable" + ) if not pids: out.info("No visible ssh-agent(s) found running") else: @@ -554,12 +557,11 @@ def stop(self, which: str) -> None: out.info(f"Keychain ssh-agent stopped: {out.id(killed[0])}") elif which == "others": out.info(f"Other ssh-agents stopped: {rendered}") - else: + elif not hidden: out.info("No keychain ssh-agent found running") - if which != "others": - if pidf_env.pid_int not in pids and self.keychain_state.ssh_pid_status(pidf_env.pid_int) == "uninspectable": - out.warn(f"Cannot verify process identity for PID {pidf_env.pid}; not signaling it, pidfile kept.") - return + if hidden: + out.warn(f"Cannot verify process identity for PID {pidf_env.pid}; not signaling it, pidfile kept.") + elif which != "others": self.keychain_state.paths.clear() # ---- key operations ---------------------------------------------- diff --git a/src/keychain/runtime/compat.py b/src/keychain/runtime/compat.py index 23db0a1..85e7870 100644 --- a/src/keychain/runtime/compat.py +++ b/src/keychain/runtime/compat.py @@ -146,7 +146,7 @@ def translate(self, argv: list[str]) -> list[str]: Examples: ``['--list']`` -> ``['list']``, ``['--wipe', 'ssh']`` -> ``['wipe', '--ssh']``, - ``['--stop', 'mine']`` -> ``['agent', 'stop', '--mine']``, + ``['--stop', 'mine']`` -> ``['agent', 'stop']``, ``['id_ed25519']`` -> ``['add', 'id_ed25519']``. Unrecognised tokens are passed through so argparse can reject them.""" out_args: list[str] = [] diff --git a/src/keychain/runtime/platform.py b/src/keychain/runtime/platform.py index ceec061..0424b5b 100644 --- a/src/keychain/runtime/platform.py +++ b/src/keychain/runtime/platform.py @@ -60,59 +60,29 @@ def __repr__(self): # pragma: no cover - debugging aid return f"" -class _PosixPlatform(Platform): - """POSIX-shaped userland: enumerate visible processes via /proc or ps.""" +class _PsPlatform(Platform): + """Shared ps execution and validation; subclasses own dialect differences.""" + + # Separate -o arguments also work on Solaris, where text after '=' is a header. + ps_command: tuple[str, ...] = ("ps", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm=") + ps_header: tuple[str, ...] = () + requires_ps = True def __init__(self, name: str) -> None: self.name = name - def process_details_unavailable(self, pid: int) -> bool: - if pid <= 0 or not self.name.startswith(("linux", "android")) or not os.path.isdir("/proc/self"): - return False - try: - with open(f"/proc/{pid}/comm", encoding="utf-8", errors="replace") as handle: - handle.read(1) - except (FileNotFoundError, PermissionError): - # hidepid can return ENOENT for a live, non-dumpable ssh-agent. - # Check liveness after the read, so an exit during it is not "hidden". - try: - os.kill(pid, 0) - except (OSError, OverflowError): - return False - return True - except OSError: - pass - return False + def _parse_record(self, line: str) -> list[str]: + return line.split(None, 2) def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int]: pids: list[int] = [] - if self.name.startswith("linux") and os.path.isdir("/proc/self"): - # Spawning ps costs ~10 ms; walking /proc costs ~4 ms. - for entry in os.listdir("/proc"): - try: - if not entry.isdigit() or (uid is not None and os.stat(f"/proc/{entry}").st_uid != uid): - continue - with open(f"/proc/{entry}/comm", encoding="utf-8", errors="replace") as handle: - if not pattern.search(handle.read().strip()): - continue - with open(f"/proc/{entry}/stat", encoding="utf-8", errors="replace") as handle: - # Skip zombie/dead tasks; the parenthesized name can contain ')'. - if handle.read().rpartition(")")[2].split()[0] not in ("Z", "X", "x"): - pids.append(int(entry)) - except OSError: - continue # exited mid-scan, or process details are restricted - return pids - cygwin_ps = self.name == "cygwin" or self.name.startswith("msys") try: proc = subprocess.Popen( - # illumos/Solaris treats everything after '=' in one -o - # argument as header text, including commas. Separate -o - # options preserve all three columns across POSIX hosts. - ["ps", "-e", "-l"] if cygwin_ps else ["ps", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm="], + list(self.ps_command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, # Cygwin/MSYS ps truncates command names to COLUMNS even in a pipe. - env={key: value for key, value in os.environ.items() if key != "COLUMNS"}, + env={**{key: value for key, value in os.environ.items() if key != "COLUMNS"}, "LC_ALL": "C"}, ) stdout, stderr = proc.communicate() except OSError as exc: @@ -120,28 +90,94 @@ def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int] if proc.returncode: detail = stderr.decode(errors="replace").strip() or "no error output" raise KeychainError(f"Process discovery failed: ps exited with status {proc.returncode}: {detail}") - for line in stdout.decode(errors="replace").splitlines(): - if cygwin_ps: - # ps -l starts with a status character. STIME is eight characters - # wide, including spaces in dates such as " Nov 1". - match = re.match( - r"^.\s*(\d+)\s+\d+\s+\d+\s+\d+\s+\S+\s+(\d+) .{8} (.+)$", line - ) - if not match: - continue - parts = list(match.groups()) - else: - parts = line.split(None, 2) - if len(parts) < 3: + records = 0 + for number, line in enumerate(stdout.decode(errors="replace").splitlines(), 1): + if not line.strip(): continue - try: - pid, proc_uid = int(parts[0]), int(parts[1]) - except ValueError: + if number == 1 and self.ps_header and tuple(line.split()) == self.ps_header: continue + parts = self._parse_record(line) + if len(parts) != 3 or not all(re.fullmatch(r"[0-9]+", value) for value in parts[:2]): + raise KeychainError(f"Process discovery failed: ps returned an invalid record at line {number}") + pid, proc_uid = int(parts[0]), int(parts[1]) + records += 1 if uid is not None and proc_uid != uid: continue if pattern.search(parts[2].strip()): pids.append(pid) + if not records: + raise KeychainError("Process discovery failed: ps returned no process records") + return pids + + +class _BSDPlatform(_PsPlatform): + # BSD ps supports unlimited width; System V ps does not share this option. + ps_command = ("ps", "-ww", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm=") + + +class _SolarisPlatform(_PsPlatform): + # comm comes from bounded argv text. fname avoids path truncation; + # a 16-character header widens its default eight-character field. + ps_command = ("ps", "-A", "-o", "pid=", "-o", "uid=", "-o", "fname=KEYCHAIN_COMMAND") + ps_header = ("KEYCHAIN_COMMAND",) + + +class _CygwinPlatform(_PsPlatform): + """Cygwin and MSYS use their own fixed-column ps format.""" + + ps_command = ("ps", "-e", "-l") + ps_header = ("PID", "PPID", "PGID", "WINPID", "TTY", "UID", "STIME", "COMMAND") + + def _parse_record(self, line: str) -> list[str]: + # The status prefix and eight-character STIME may contain spaces. + match = re.match(r"^[ SIO] +([0-9]+)\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+\S+\s+([0-9]+) .{8} (.+)$", line) + return list(match.groups()) if match else [] + + +class _LinuxPlatform(_PsPlatform): + """Linux and Android prefer /proc, with ps as a fallback when unavailable.""" + + def __init__(self, name: str) -> None: + super().__init__(name) + self.requires_ps = not os.path.isdir("/proc/self") + + def process_details_unavailable(self, pid: int) -> bool: + if pid <= 0 or self.requires_ps: + return False + try: + with open(f"/proc/{pid}/comm", encoding="utf-8", errors="replace") as handle: + handle.read(1) + except (FileNotFoundError, PermissionError): + # hidepid can return ENOENT for a live, non-dumpable ssh-agent. + # Check liveness after the read, so an exit during it is not "hidden". + try: + os.kill(pid, 0) + except (OSError, OverflowError): + return False + return True + except OSError: + pass + return False + + def process_list(self, pattern: re.Pattern, uid: int | None = None) -> list[int]: + if self.requires_ps: + return super().process_list(pattern, uid) + pids: list[int] = [] + for entry in os.listdir("/proc"): + try: + if not entry.isdigit() or (uid is not None and os.stat(f"/proc/{entry}").st_uid != uid): + continue + with open(f"/proc/{entry}/comm", encoding="utf-8", errors="replace") as handle: + if not pattern.search(handle.read().strip()): + continue + with open(f"/proc/{entry}/stat", encoding="utf-8", errors="replace") as handle: + # Skip zombie/dead tasks; the parenthesized name can contain ')'. + # An empty read means the task vanished mid-scan. + fields = handle.read().rpartition(")")[2].split() + if fields and fields[0] not in ("Z", "X", "x"): + pids.append(int(entry)) + except OSError: + continue # exited mid-scan, or process details are restricted return pids @@ -171,26 +207,36 @@ def _classify(platform_name: str, has_ps: bool | None = None) -> Platform: *has_ps* controls whether ``ps`` is considered available; pass it explicitly in tests to avoid probing the host's actual PATH. - When ``None`` (the default), :func:`_probe_ps` is called once. + When ``None`` (the default), :func:`_probe_ps` is called once if /proc + discovery is unavailable. """ - if has_ps is None: - has_ps = _probe_ps() - p = platform_name.lower() # Native Windows is unsupported regardless of ps. if p == "win32": return _UnsupportedPlatform("windows", _UNSUPPORTED_WINDOWS_REASON) - is_known_posix = ( - p.startswith(("linux", "darwin", "freebsd", "openbsd", "netbsd", "dragonfly", "sunos", "aix", "haiku", "gnu")) - or p == "cygwin" - or p.startswith("msys") - ) + implementation: type[_PsPlatform] = _PsPlatform + for prefixes, candidate in ( + (("linux", "android"), _LinuxPlatform), + (("darwin", "freebsd", "openbsd", "netbsd", "dragonfly"), _BSDPlatform), + (("sunos",), _SolarisPlatform), + (("cygwin", "msys"), _CygwinPlatform), + ): + if p.startswith(prefixes): + implementation = candidate + break + platform = implementation(p) + if not platform.requires_ps: + return platform + if has_ps is None: + has_ps = _probe_ps() + + is_known_posix = implementation is not _PsPlatform or p.startswith(("aix", "haiku", "gnu")) if is_known_posix: if has_ps: - return _PosixPlatform(p) + return platform return _UnsupportedPlatform( p, "ps(1) was not found in PATH on this {} system. " @@ -200,7 +246,7 @@ def _classify(platform_name: str, has_ps: bool | None = None) -> Platform: # Unknown platform: use ps if available; refuse with a clear message otherwise. if has_ps: - return _PosixPlatform(p) + return platform return _UnsupportedPlatform( p, "Unrecognized platform '{}' and ps(1) is not in PATH. " diff --git a/tests/test_agent_lifecycle_e2e.py b/tests/test_agent_lifecycle_e2e.py index d148d47..e9c41cc 100644 --- a/tests/test_agent_lifecycle_e2e.py +++ b/tests/test_agent_lifecycle_e2e.py @@ -74,9 +74,12 @@ def run(*args, agent=None): assert agent.pid_int in visible, { "agent": agent, "uid": os.getuid(), "COLUMNS": os.environ.get("COLUMNS"), "platform": repr(platform.detect()), "ps_path": shutil.which("ps"), - "ps": run("ps", "-e", "-l").stdout, + "ps": run(*platform.detect().ps_command).stdout, "ssh-add": run("ssh-add", "-l", agent=agent), } + assert agent.pid_int not in platform.detect().process_list( + re.compile(r"(?:^|/)ssh-agent$"), os.getuid() + 1, + ) key = str(home / "test-key") generated = run("ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", key) diff --git a/tests/test_agent_visibility.py b/tests/test_agent_visibility.py index c82d180..5e33809 100644 --- a/tests/test_agent_visibility.py +++ b/tests/test_agent_visibility.py @@ -32,7 +32,7 @@ def kill(pid, sig): monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) monkeypatch.setattr(platform, "open", read, raising=False) monkeypatch.setattr(platform.os, "kill", kill) - assert platform._PosixPlatform(name).process_details_unavailable(123) is ( + assert platform._classify(name, has_ps=True).process_details_unavailable(123) is ( alive and error in (errno.ENOENT, errno.EACCES, errno.EPERM) ) @@ -41,7 +41,7 @@ def kill(pid, sig): def test_no_visibility_inference_without_linux_proc(monkeypatch, name, proc): monkeypatch.setattr(platform.os.path, "isdir", lambda _path: proc) monkeypatch.setattr(platform, "open", lambda *_a, **_k: pytest.fail("must not read proc"), raising=False) - assert not platform._PosixPlatform(name).process_details_unavailable(123) + assert not platform._classify(name, has_ps=True).process_details_unavailable(123) @pytest.mark.parametrize("pid", [-1, 0, 2**64]) @@ -56,13 +56,13 @@ def kill(actual_pid, sig): monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) monkeypatch.setattr(platform, "open", read, raising=False) monkeypatch.setattr(platform.os, "kill", kill) - assert not platform._PosixPlatform("linux").process_details_unavailable(pid) + assert not platform._LinuxPlatform("linux").process_details_unavailable(pid) @pytest.fixture def agent(tmp_path, monkeypatch): k = state.KeychainState(paths=KeychainPaths(keydir=tmp_path, host="test"), env={}) - k.platform = platform._PosixPlatform("linux") + k.platform = platform._LinuxPlatform("linux") monkeypatch.setattr(agents, "findpids", lambda _name: []) monkeypatch.setattr(agents, "validate_ssh_socket", lambda sock: agents.SocketValidation(sock, True)) monkeypatch.setattr(k.platform, "process_details_unavailable", lambda _pid: True) @@ -122,4 +122,6 @@ def test_stop_never_signals_hidden_pid_and_keeps_its_reference(agent, monkeypatc assert [call.args[0] for call in kill.call_args_list] == ([] if which == "pidfile" else visible) clear.assert_not_called() if which != "others": - assert "pidfile kept" in capsys.readouterr().err + err = capsys.readouterr().err + assert "pidfile kept" in err + assert "No keychain ssh-agent found running" not in err diff --git a/tests/test_cli_startup.py b/tests/test_cli_startup.py index d5cdb87..e440176 100644 --- a/tests/test_cli_startup.py +++ b/tests/test_cli_startup.py @@ -17,7 +17,7 @@ @pytest.mark.skipif(os.name == "nt", reason="requires POSIX file ownership") @pytest.mark.parametrize("action", [["add", "--noask", "--eval"], ["env"], ["agent", "stop"]]) -@pytest.mark.parametrize("failure", ["exit", "launch"]) +@pytest.mark.parametrize("failure", ["exit", "launch", "malformed", "empty"]) def test_failed_discovery_preserves_agent_reference(tmp_path, monkeypatch, capsys, action, failure): set_home(monkeypatch, tmp_path, patch_path_home=True) monkeypatch.delenv("KEYCHAIN_CONFIG", raising=False) @@ -30,13 +30,16 @@ def test_failed_discovery_preserves_agent_reference(tmp_path, monkeypatch, capsy contents = "SSH_AUTH_SOCK=/test.sock; export SSH_AUTH_SOCK;\nSSH_AGENT_PID=123; export SSH_AGENT_PID;\n" pidfile.write_text(contents) pidfile.chmod(0o600) - monkeypatch.setattr(main.platform, "_cached", main.platform._PosixPlatform("cygwin")) + monkeypatch.setattr(main.platform, "_cached", main.platform._classify("cygwin", has_ps=True)) monkeypatch.setattr(agents, "validate_ssh_socket", lambda sock: agents.SocketValidation(sock, True)) def fail_ps(cmd, **_kwargs): assert cmd == ["ps", "-e", "-l"], "must not launch a replacement agent" if failure == "launch": raise FileNotFoundError("test ps missing") + if failure in ("malformed", "empty"): + stdout = b"unsupported output\n" if failure == "malformed" else b"" + return SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")) return SimpleNamespace(returncode=1, communicate=lambda: (b"", b"test ps failure")) monkeypatch.setattr(main.platform.subprocess, "Popen", fail_ps) @@ -46,7 +49,8 @@ def fail_ps(cmd, **_kwargs): captured = capsys.readouterr() assert exc.value.code == 1 assert "Process discovery failed" in captured.err - assert "test ps" in captured.err + if failure in ("exit", "launch"): + assert "test ps" in captured.err assert "Traceback" not in captured.err assert captured.out.strip() == ("false;" if "--eval" in action else "") assert pidfile.read_text() == contents diff --git a/tests/test_hidden_agent_e2e.py b/tests/test_hidden_agent_e2e.py index 931e115..f722b11 100644 --- a/tests/test_hidden_agent_e2e.py +++ b/tests/test_hidden_agent_e2e.py @@ -39,7 +39,7 @@ def _namespace_probe(hidepid): from keychain.env import SshAgentRef from keychain.output.core import Output from keychain.paths import KeychainPaths - from keychain.runtime.platform import _PosixPlatform + from keychain.runtime.platform import _LinuxPlatform report = { "hidepid": hidepid, @@ -48,7 +48,7 @@ def _namespace_probe(hidepid): "proc_mounts": [line for line in Path("/proc/self/mountinfo").read_text().splitlines() if " /proc " in line], "cases": {}, } - # Selecting android tests its current ps backend on Linux, not Android itself. + # Both platform names use Linux /proc; this does not emulate Android's SELinux policy. for backend in ("linux", "android"): with tempfile.TemporaryDirectory(prefix="kc-hidepid-") as temporary: home = Path(temporary) @@ -94,7 +94,7 @@ def invoke(*args, command=command, options=options, env=env): comm_errno = 0 except OSError as error: comm_errno = error.errno - pids = _PosixPlatform(backend).process_list(re.compile(r"(?:^|/)ssh-agent$"), uid=os.getuid()) + pids = _LinuxPlatform(backend).process_list(re.compile(r"(?:^|/)ssh-agent$"), uid=os.getuid()) inspected = invoke("inspect") inspected_json = invoke("inspect", "--json") assert inspected_json.returncode == 0, inspected_json.stderr diff --git a/tests/test_posix_vm_runner.py b/tests/test_posix_vm_runner.py new file mode 100644 index 0000000..4095b25 --- /dev/null +++ b/tests/test_posix_vm_runner.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""A green VM job must include the live tests, not just parser fixtures.""" + +from types import SimpleNamespace + +import pytest +from scripts import test_posix_vm as runner + + +@pytest.fixture +def vm(monkeypatch): + monkeypatch.setattr(runner.sys, "argv", ["test_posix_vm.py", "freebsd"]) + monkeypatch.setattr(runner.sys, "platform", "freebsd14") + monkeypatch.setattr(runner.os, "getuid", lambda: 1000, raising=False) + monkeypatch.setattr(runner.os, "uname", lambda: "test FreeBSD", raising=False) + monkeypatch.setattr(runner.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr(runner.subprocess, "run", lambda *_a, **_kw: None) + return monkeypatch + + +@pytest.mark.parametrize("missing, result, expected", [(None, 0, 0), ("long_path", 0, 1), (None, 1, 1)]) +def test_requires_live_tests_to_pass(vm, missing, result, expected): + def run(args, plugins): + assert "tests/test_agent_lifecycle_e2e.py" in args + names = [ + "tests/test_runtime.py::test_supported_process_list_returns_list", + "tests/test_runtime.py::test_real_ps_discovers_agent_launched_from_long_path", + *[f"tests/test_agent_lifecycle_e2e.py::test_agent_reuse_preserves_loaded_key[{value}]" + for value in ("None", "20", "80")], + ] + for name in names: + plugins[0].pytest_runtest_logreport(SimpleNamespace( + when="call", passed=missing is None or missing not in name, nodeid=name, + )) + return result + + vm.setattr(runner.pytest, "main", run) + assert runner.main() == expected + + +@pytest.mark.parametrize("uid, name", [(0, "freebsd14"), (1000, "linux")]) +def test_rejects_root_or_wrong_os(vm, uid, name): + vm.setattr(runner.os, "getuid", lambda: uid) + vm.setattr(runner.sys, "platform", name) + with pytest.raises(RuntimeError, match="Expected unprivileged"): + runner.main() + + +def test_missing_tools_are_errors_not_skips(vm): + vm.setattr(runner.shutil, "which", lambda _name: None) + with pytest.raises(RuntimeError, match="Required test tool missing"): + runner.main() diff --git a/tests/test_runtime.py b/tests/test_runtime.py index f9f0976..db859cd 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -4,6 +4,7 @@ import io import os import re +import shutil import subprocess import sys import time @@ -42,13 +43,21 @@ def test_native_windows_unsupported(): assert "WSL" in p.reason or "Cygwin" in p.reason -def test_known_posix_ps_missing(): +def test_known_posix_ps_missing(monkeypatch): # A known POSIX platform without ps in PATH is unsupported with a clear message. + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: False) p = platform.detect(platform_override="linux", has_ps=False) assert p.supported is False assert "ps" in p.reason.lower() +@pytest.mark.parametrize("name", ["linux", "linux2", "android"]) +def test_linux_proc_does_not_require_ps(monkeypatch, name): + monkeypatch.setattr(platform.os.path, "isdir", lambda path: path == "/proc/self") + monkeypatch.setattr(platform.shutil, "which", lambda *_a: pytest.fail("must not require ps")) + assert platform.detect(platform_override=name).supported + + def test_unknown_platform_with_ps(): # An unrecognised platform string is accepted when ps is present. p = platform.detect(platform_override="plan9", has_ps=True) @@ -68,6 +77,54 @@ def test_detection_is_cached(): assert first is second +@pytest.mark.parametrize("name, implementation", [ + ("linux", platform._LinuxPlatform), ("android", platform._LinuxPlatform), + ("darwin", platform._BSDPlatform), ("freebsd14", platform._BSDPlatform), + ("openbsd7", platform._BSDPlatform), ("netbsd10", platform._BSDPlatform), + ("dragonfly6", platform._BSDPlatform), ("sunos5", platform._SolarisPlatform), + ("cygwin", platform._CygwinPlatform), ("msys2", platform._CygwinPlatform), + ("aix", platform._PsPlatform), ("unknown-posix", platform._PsPlatform), +]) +def test_factory_selects_platform_implementation(name, implementation): + p = platform._classify(name, has_ps=True) + assert type(p) is implementation + assert p.name == name + + +@pytest.mark.parametrize("name", ["linux", "android"]) +def test_linux_ps_fallback_is_selected_once(monkeypatch, name): + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: False) + p = platform._classify(name, has_ps=True) + assert p.requires_ps + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: pytest.fail("must not redetect /proc")) + + def ps(command, **_kwargs): + assert command == ["ps", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm="] + return SimpleNamespace(returncode=0, communicate=lambda: (b"123 1000 ssh-agent\n", b"")) + + monkeypatch.setattr(platform.subprocess, "Popen", ps) + assert p.process_list(re.compile("^ssh-agent$"), uid=1000) == [123] + assert not p.process_details_unavailable(123) + + +def test_ps_dialects_do_not_change_each_others_commands(monkeypatch): + seen = [] + + def ps(command, **_kwargs): + seen.append(command) + return SimpleNamespace(returncode=0, communicate=lambda: (b"123 1000 ssh-agent\n", b"")) + + monkeypatch.setattr(platform.subprocess, "Popen", ps) + for name in ("sunos5", "freebsd14", "aix", "sunos5"): + p = platform._classify(name, has_ps=True) + p.name = "msys2" # Labels do not reroute a previously selected implementation. + assert p.process_list(re.compile("^ssh-agent$")) == [123] + assert seen == [ + list(platform._SolarisPlatform.ps_command), list(platform._BSDPlatform.ps_command), + list(platform._PsPlatform.ps_command), list(platform._SolarisPlatform.ps_command), + ] + + def test_unsupported_process_list_raises(): p = platform.detect(platform_override="win32") with pytest.raises(RuntimeError): @@ -85,7 +142,8 @@ def test_supported_process_list_returns_list(): @pytest.mark.parametrize("state", ["R", "S", "D", "T", "t", "I", "Z", "X", "x"]) @pytest.mark.parametrize("comm", ["ssh-agent", "ssh ) agent ("]) -def test_proc_discovery_checks_process_state(monkeypatch, state, comm): +@pytest.mark.parametrize("name", ["linux", "android"]) +def test_proc_discovery_checks_process_state(monkeypatch, state, comm, name): reads = [] def read(path, **_kwargs): @@ -103,7 +161,7 @@ def read(path, **_kwargs): monkeypatch.setattr(platform, "open", read, raising=False) monkeypatch.setattr(platform.subprocess, "Popen", lambda *_a, **_k: pytest.fail("must not run ps")) - p = platform._PosixPlatform("linux") + p = platform._classify(name, has_ps=True) assert p.process_list(re.compile(re.escape(comm) + "$"), uid=1000) == ([] if state in ("Z", "X", "x") else [123]) assert reads == ["/proc/123/comm", "/proc/123/stat"] reads.clear() @@ -114,6 +172,47 @@ def read(path, **_kwargs): assert reads == [] +def test_proc_discovery_skips_task_with_empty_stat(monkeypatch): + # A task that exits between the comm and stat reads can yield an empty stat. + files = {"/proc/123/comm": "ssh-agent\n", "/proc/123/stat": "", "/proc/456/comm": "ssh-agent\n", + "/proc/456/stat": "456 (ssh-agent) S 1 456 456 0\n"} + monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) + monkeypatch.setattr(platform.os, "listdir", lambda _path: ["123", "456"]) + monkeypatch.setattr(platform.os, "stat", lambda _path: SimpleNamespace(st_uid=1000)) + monkeypatch.setattr(platform, "open", lambda path, **_kw: io.StringIO(files[path]), raising=False) + + assert platform._LinuxPlatform("linux").process_list(re.compile("ssh-agent$"), uid=1000) == [456] + + +@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="requires Linux /proc") +@pytest.mark.parametrize("name", ["linux", "android"]) +@pytest.mark.parametrize("ps_available", [False, True]) +def test_real_agent_discovery_with_minimal_path(tmp_path, monkeypatch, name, ps_available): + agent = shutil.which("ssh-agent") + if not agent: + pytest.skip("requires ssh-agent") + if ps_available: + busybox = shutil.which("busybox") + if not busybox: + pytest.skip("requires BusyBox") + (tmp_path / "ps").symlink_to(busybox) + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("PATH", str(tmp_path)) + with subprocess.Popen([agent, "-D", "-a", "agent.sock"], stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) as child: + try: + deadline = time.monotonic() + 5 + while not (tmp_path / "agent.sock").exists(): + assert child.poll() is None, child.stderr.read().decode() + assert time.monotonic() < deadline, "agent did not create its socket" + time.sleep(0.01) + p = platform.detect(platform_override=name) + assert p.supported + assert child.pid in p.process_list(re.compile(r"^ssh-agent$"), uid=os.getuid()) + finally: + child.terminate() + child.wait(timeout=5) + + @pytest.mark.parametrize("error", [FileNotFoundError, PermissionError]) def test_proc_discovery_skips_unreadable_state(monkeypatch, error): def read(path, **_kwargs): @@ -124,7 +223,7 @@ def read(path, **_kwargs): monkeypatch.setattr(platform.os.path, "isdir", lambda _path: True) monkeypatch.setattr(platform.os, "listdir", lambda _path: ["123"]) monkeypatch.setattr(platform, "open", read, raising=False) - assert platform._PosixPlatform("linux").process_list(re.compile("ssh-agent")) == [] + assert platform._LinuxPlatform("linux").process_list(re.compile("ssh-agent")) == [] @pytest.mark.skipif(not sys.platform.startswith("linux"), reason="requires Linux /proc and prctl") @@ -150,7 +249,7 @@ def test_proc_discovery_excludes_real_zombie(): pytest.fail("child did not exit within 10 seconds") with open(f"/proc/{child.pid}/comm") as handle: assert handle.read().strip() == "ssh-agent" - assert child.pid not in platform._PosixPlatform("linux").process_list( + assert child.pid not in platform._LinuxPlatform("linux").process_list( re.compile(r"^ssh-agent$"), uid=os.getuid() ) @@ -159,7 +258,7 @@ def test_proc_discovery_excludes_real_zombie(): def test_process_list_with_illumos_ps(monkeypatch, uid, expected): """illumos consumes the remainder of each -o argument as header text.""" rows = [ - {"pid": "123", "uid": "1000", "comm": "/usr/bin/ssh-agent"}, + {"pid": "123", "uid": "1000", "comm": "/path with spaces/" * 10 + "ssh-agent"}, {"pid": "456", "uid": "2000", "comm": "ssh-agent"}, {"pid": "789", "uid": "1000", "comm": "ssh-agent-helper"}, {"pid": "987", "uid": "1000", "comm": "not-ssh-agent"}, @@ -174,6 +273,12 @@ def fake_popen(cmd, **kwargs): names, separator, header = cmd[index + 1].partition("=") fields.extend(names.split(",")) headers.append(header if separator else names) + assert fields == ["pid", "uid", "fname"] + assert headers == ["", "", "KEYCHAIN_COMMAND"] + # Model illumos's pr_fname and its default eight-character display width. + width = len(headers[-1]) or 8 + for row in rows: + row["fname"] = row["comm"].rsplit("/", 1)[-1][:15][:width] lines = [" ".join(headers)] if any(headers) else [] lines.extend(" ".join(row[field] for field in fields) for row in rows) stdout = ("\n".join(lines) + "\n").encode() @@ -201,12 +306,11 @@ def test_process_list_with_cygwin_ps(monkeypatch, name, uid, expected, columns): b"I 789 1 789 54000 ? 1000 15:39:13 /path with spaces/ssh-agent\n" b" 987 1 987 55000 ? 1000 15:39:13 /usr/bin/ssh-agent-helper\n" b" 988 1 988 56000 ? 1000 15:39:13 /usr/bin/ssh-agent \n" - b"invalid row\n" ) def fake_popen(cmd, **kwargs): assert cmd == ["ps", "-e", "-l"] - assert kwargs["env"] == {key: value for key, value in parent_env.items() if key != "COLUMNS"} + assert kwargs["env"] == {**{key: value for key, value in parent_env.items() if key != "COLUMNS"}, "LC_ALL": "C"} return SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")) monkeypatch.setattr(platform.subprocess, "Popen", fake_popen) @@ -218,10 +322,11 @@ def fake_popen(cmd, **kwargs): @pytest.mark.parametrize("name", ["cygwin", "msys", "msys2"]) @pytest.mark.parametrize("stime", ["15:39:13", " Nov 1", " Nov 12"]) -def test_process_list_with_cygwin_stime(monkeypatch, name, stime): +@pytest.mark.parametrize("status", [" ", "S", "I", "O"]) +def test_process_list_with_cygwin_stime(monkeypatch, name, stime, status): stdout = ( " PID PPID PGID WINPID TTY UID STIME COMMAND\n" - f" 123 1 123 52000 ? 1000 {stime} /path with spaces/ssh-agent\n" + f"{status} 123 1 123 52000 ? 1000 {stime} /path with spaces/ssh-agent\n" ).encode() def fake_popen(cmd, **kwargs): @@ -244,7 +349,7 @@ def fake_popen(_cmd, **kwargs): monkeypatch.setattr(platform.subprocess, "Popen", fake_popen) with pytest.raises(KeychainError, match=f"Process discovery failed: ps exited with status {status}") as exc: - platform._PosixPlatform(name).process_list(re.compile("ssh-agent")) + platform._classify(name, has_ps=True).process_list(re.compile("ssh-agent")) assert (stderr.decode(errors="replace").strip() or "no error output") in str(exc.value) @@ -255,13 +360,122 @@ def fail(*_args, **_kwargs): monkeypatch.setattr(platform.subprocess, "Popen", fail) with pytest.raises(KeychainError, match="Process discovery failed: cannot run ps"): - platform._PosixPlatform("cygwin").process_list(re.compile("ssh-agent")) + platform._classify("cygwin", has_ps=True).process_list(re.compile("ssh-agent")) -@pytest.mark.parametrize("stdout", [b"", b"123 1000 other-command\n"]) +@pytest.mark.parametrize("stdout", [b"123 1000 other-command\n", b"0 0 -\n", b"\n123 1000 other-command\n\n"]) def test_successful_ps_without_matching_agents_is_valid(monkeypatch, stdout): monkeypatch.setattr( platform.subprocess, "Popen", lambda *_a, **_k: SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")), ) - assert platform._PosixPlatform("sunos5").process_list(re.compile("ssh-agent")) == [] + assert platform._classify("sunos5", has_ps=True).process_list(re.compile("ssh-agent")) == [] + + +@pytest.mark.parametrize("name", ["sunos5", "darwin", "freebsd14", "openbsd7", "netbsd", "aix", "cygwin", "msys2"]) +@pytest.mark.parametrize("stdout", [b"", b"\n", b"unsupported output\n", b"123 1000\n", b"123 uid ssh-agent\n"]) +def test_successful_but_unusable_ps_output_is_fatal(monkeypatch, name, stdout): + monkeypatch.setattr( + platform.subprocess, "Popen", + lambda *_a, **_k: SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")), + ) + with pytest.raises(KeychainError, match="Process discovery failed: ps"): + platform._classify(name, has_ps=True).process_list(re.compile("ssh-agent")) + + +@pytest.mark.parametrize("bad_row", ["garbage", "123 1000", "-1 1000 ssh-agent", "123 -1 ssh-agent", "+123 1000 ssh-agent"]) +def test_ps_rejects_partial_results_before_uid_or_name_filtering(monkeypatch, bad_row): + stdout = f"123 1000 ssh-agent\n{bad_row}\n456 2000 other-command\n".encode() + monkeypatch.setattr( + platform.subprocess, "Popen", + lambda *_a, **_k: SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")), + ) + with pytest.raises(KeychainError, match="Process discovery failed: ps.*line 2"): + platform._classify("sunos5", has_ps=True).process_list(re.compile("ssh-agent"), uid=1000) + + +@pytest.mark.parametrize("name", ["cygwin", "msys2"]) +@pytest.mark.parametrize("suffix", [b"", b"invalid row\n"]) +def test_cygwin_header_is_not_a_process_record(monkeypatch, name, suffix): + stdout = b" PID PPID PGID WINPID TTY UID STIME COMMAND\n" + suffix + monkeypatch.setattr( + platform.subprocess, "Popen", + lambda *_a, **_k: SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")), + ) + with pytest.raises(KeychainError, match="Process discovery failed: ps"): + platform._classify(name, has_ps=True).process_list(re.compile("ssh-agent")) + + +@pytest.mark.parametrize("prefix", ["1", "? ", "Z "]) +def test_cygwin_ps_rejects_invalid_status_instead_of_truncating_pid(monkeypatch, prefix): + stdout = f"{prefix}123 1 123 52000 ? 1000 15:39:13 /usr/bin/ssh-agent\n".encode() + monkeypatch.setattr( + platform.subprocess, "Popen", + lambda *_a, **_k: SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")), + ) + with pytest.raises(KeychainError, match="Process discovery failed: ps.*line 1"): + platform._classify("cygwin", has_ps=True).process_list(re.compile("ssh-agent")) + + +@pytest.mark.parametrize("name", ["darwin", "freebsd14", "openbsd7", "netbsd", "dragonfly6"]) +def test_bsd_ps_requests_unlimited_width(monkeypatch, name): + monkeypatch.setenv("COLUMNS", "8") + monkeypatch.setenv("LC_ALL", "fr_FR.UTF-8") + parent_env = dict(os.environ) + command_name = "/a very long installation directory/" * 8 + "ssh-agent" + + def fake_popen(cmd, **kwargs): + assert cmd == ["ps", "-ww", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm="] + assert "COLUMNS" not in kwargs["env"] + assert kwargs["env"]["LC_ALL"] == "C" + stdout = f"123 1000 {command_name}\n456 1000 {command_name}-helper\n".encode() + return SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")) + + monkeypatch.setattr(platform.subprocess, "Popen", fake_popen) + assert platform._classify(name, has_ps=True).process_list(re.compile(r"(?:^|/)ssh-agent$"), uid=1000) == [123] + assert dict(os.environ) == parent_env + + +@pytest.mark.parametrize("command_name", ["ssh-agen", "ssh-agent-helper", "not-ssh-agent", "ssh-agent "]) +def test_ps_never_guesses_an_agent_from_a_partial_name(monkeypatch, command_name): + stdout = f"123 1000 {command_name}\n".encode() + monkeypatch.setattr( + platform.subprocess, "Popen", + lambda *_a, **_k: SimpleNamespace(returncode=0, communicate=lambda: (stdout, b"")), + ) + assert platform._classify("darwin", has_ps=True).process_list(re.compile(r"(?:^|/)ssh-agent$"), uid=1000) == [] + + +@pytest.mark.skipif( + not sys.platform.startswith(("linux", "darwin", "freebsd", "openbsd", "netbsd", "dragonfly", "sunos")), + reason="requires POSIX ps and symlinks", +) +def test_real_ps_discovers_agent_launched_from_long_path(tmp_path, monkeypatch): + agent = shutil.which("ssh-agent") + ps = shutil.which("ps") + if not agent or not ps: + pytest.skip("requires ssh-agent and ps") + if os.path.basename(os.path.realpath(ps)).startswith("busybox"): + pytest.skip("BusyBox is exercised through Linux /proc, not the generic ps format") + directory = tmp_path / ("long installation path " * 5) + directory.mkdir() + executable = directory / "ssh-agent" + executable.symlink_to(agent) + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("COLUMNS", "1") + # Force Linux's ps fallback too; normal Linux discovery already has a live test. + p = platform._PsPlatform("linux") if sys.platform.startswith("linux") else platform.detect() + with subprocess.Popen([str(executable), "-D", "-a", "agent.sock"], + stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) as child: + try: + deadline = time.monotonic() + 5 + while not (tmp_path / "agent.sock").exists(): + assert child.poll() is None, child.stderr.read().decode() + assert time.monotonic() < deadline, "agent did not create its socket" + time.sleep(0.01) + assert child.pid in p.process_list( + re.compile(r"(?:^|/)ssh-agent$"), uid=os.getuid() + ) + finally: + child.terminate() + child.wait(timeout=5) diff --git a/tests/test_ssh_confirm_e2e.py b/tests/test_ssh_confirm_e2e.py index 7403eb0..cd4ea07 100644 --- a/tests/test_ssh_confirm_e2e.py +++ b/tests/test_ssh_confirm_e2e.py @@ -31,6 +31,8 @@ def _run(cmd: list[str], env: dict[str, str], *, timeout: int = 30) -> subproces text=True, encoding="utf-8", errors="replace", + stdin=subprocess.DEVNULL, + start_new_session=True, timeout=timeout, check=False, ) @@ -52,6 +54,64 @@ def _write_askpass(path: Path, log: Path, response: str = "yes") -> None: path.chmod(0o700) +def _require_force_askpass(env, key, log, agents): + # Probe OpenSSH itself, not Keychain or a version number: vendors backport features. + started = _run(["ssh-agent", "-s"], env) + _assert_ok(started) + agent = SshAgentRef.from_text(started.stdout) + assert agent, started.stdout + agents.append(agent) + probe_env = agent.overlay(env) + result = _run(["ssh-add", str(key)], probe_env) + if result.returncode != 0 and not log.exists(): + # A working display-based helper distinguishes an unsupported force mode + # from a broken helper, bad key, or other test setup failure. + probe_env.pop("SSH_ASKPASS_REQUIRE", None) + probe_env["DISPLAY"] = ":0" + _assert_ok(_run(["ssh-add", str(key)], probe_env)) + assert log.exists(), "display-based askpass did not invoke the helper" + pytest.skip("installed ssh-add does not support forced askpass without DISPLAY") + _assert_ok(result) + assert log.exists(), "forced askpass did not invoke the helper" + log.unlink() + + +@pytest.mark.parametrize("case", ["supported", "unsupported", "broken-helper", "broken-fallback", "missing-log"]) +def test_force_askpass_probe_only_skips_an_unsupported_capability(tmp_path, monkeypatch, case): + log = tmp_path / "askpass.log" + env = {"SSH_ASKPASS_REQUIRE": "force", "SSH_ASKPASS": str(tmp_path / "helper")} + calls = [] + agents = [] + + def run(cmd, child_env): + calls.append((cmd, child_env.copy())) + if cmd == ["ssh-agent", "-s"]: + return subprocess.CompletedProcess(cmd, 0, "SSH_AUTH_SOCK=/test.sock; SSH_AGENT_PID=123;", "") + if "DISPLAY" in child_env: + assert "SSH_ASKPASS_REQUIRE" not in child_env + if case == "unsupported": + log.write_text("|passphrase\n") + return subprocess.CompletedProcess(cmd, 0, "", "") + elif case in ("supported", "broken-helper"): + log.write_text("|passphrase\n") + status = 0 if case in ("supported", "missing-log") else 1 + return subprocess.CompletedProcess(cmd, status, "", "probe diagnostic") + + monkeypatch.setattr(sys.modules[__name__], "_run", run) + if case == "supported": + _require_force_askpass(env, tmp_path / "key", log, agents) + assert not log.exists(), "Keychain's later invocation must produce its own evidence" + elif case == "unsupported": + with pytest.raises(pytest.skip.Exception, match="without DISPLAY"): + _require_force_askpass(env, tmp_path / "key", log, agents) + else: + with pytest.raises(AssertionError): + _require_force_askpass(env, tmp_path / "key", log, agents) + assert len(calls) == (3 if case in ("unsupported", "broken-fallback") else 2) + assert agents == [SshAgentRef("/test.sock", "123")], "the fixture must clean up the probe agent" + assert env == {"SSH_ASKPASS_REQUIRE": "force", "SSH_ASKPASS": str(tmp_path / "helper")} + + @pytest.fixture def ssh_confirm_home(): root = Path(tempfile.mkdtemp(prefix="kc-ssh-", dir="/tmp" if sys.platform == "darwin" else None)) @@ -106,23 +166,32 @@ def _keychain_add_confirm(env: dict[str, str], key: Path) -> SshAgentRef: def test_confirmed_key_invokes_askpass_when_agent_inherits_askpass(ssh_confirm_home) -> None: env, key, askpass, log, agents = ssh_confirm_home - env.update({"SSH_ASKPASS": str(askpass), "SSH_ASKPASS_REQUIRE": "force"}) + # The shell helper needs no X server; DISPLAY enables older OpenSSH's askpass path. + env.update({"SSH_ASKPASS": str(askpass), "DISPLAY": ":0"}) agent = _keychain_add_confirm(env, key) agents.append(agent) result = _run(["ssh-add", "-T", f"{key}.pub"], agent.overlay(env)) _assert_ok(result) - assert log.read_text(encoding="utf-8").startswith("confirm|") + hint, prompt = log.read_text(encoding="utf-8").split("|", 1) + assert hint in ("", "confirm") # Older OpenSSH does not supply SSH_ASKPASS_PROMPT. + assert prompt.strip() -def test_force_askpass_loads_encrypted_key_without_display(ssh_confirm_home) -> None: +@pytest.mark.parametrize("mode", ["display", "force"]) +def test_askpass_loads_encrypted_key(ssh_confirm_home, mode) -> None: env, key, askpass, log, agents = ssh_confirm_home encrypted_key = key.with_name("id_encrypted") passphrase = "test passphrase" _assert_ok(_run(["ssh-keygen", "-q", "-t", "ed25519", "-N", passphrase, "-f", str(encrypted_key)], env)) _write_askpass(askpass, log, passphrase) - env.update({"SSH_ASKPASS": str(askpass), "SSH_ASKPASS_REQUIRE": "force"}) + env["SSH_ASKPASS"] = str(askpass) + if mode == "force": + env["SSH_ASKPASS_REQUIRE"] = "force" + _require_force_askpass(env, encrypted_key, log, agents) + else: + env["DISPLAY"] = ":0" agent = _keychain_add_confirm(env, encrypted_key) agents.append(agent) @@ -133,11 +202,11 @@ def test_force_askpass_loads_encrypted_key_without_display(ssh_confirm_home) -> def test_confirmed_key_cannot_replace_askpass_after_agent_start(ssh_confirm_home) -> None: env, key, askpass, log, agents = ssh_confirm_home - env.update({"SSH_ASKPASS": str(askpass.with_name("missing-askpass")), "SSH_ASKPASS_REQUIRE": "force"}) + env.update({"SSH_ASKPASS": str(askpass.with_name("missing-askpass")), "DISPLAY": ":0"}) agent = _keychain_add_confirm(env, key) agents.append(agent) client_env = agent.overlay(env) - client_env.update({"SSH_ASKPASS": str(askpass), "SSH_ASKPASS_REQUIRE": "force"}) + client_env["SSH_ASKPASS"] = str(askpass) result = _run(["ssh-add", "-T", f"{key}.pub"], client_env) From cdf22ca49e59376bf6c797a9fbb0a4d10d43b4f7 Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:21:12 -0500 Subject: [PATCH 06/11] Load catch-all SSH identities with --confallhosts --- man/embedded-docs.txt | 6 ++++-- src/keychain/keys.py | 20 +++++++++++------- tests/test_e2e_playbooks.py | 37 +++++++++++++++++++++++++++++++++ tests/test_keys.py | 41 ++++++++++++++++++++++++++++++++----- 4 files changed, 90 insertions(+), 14 deletions(-) diff --git a/man/embedded-docs.txt b/man/embedded-docs.txt index bd77f48..fd05dd8 100644 --- a/man/embedded-docs.txt +++ b/man/embedded-docs.txt @@ -303,9 +303,11 @@ keychain wipe && keychain add KEYS `--clear` does not flush GnuPG's passphrase cache, even when GPG keys are also requested. Use `keychain wipe --gpg` when that separate operation is intended. -== @option confallhosts: load every IdentityFile in ~/.ssh/config +== @option confallhosts: load configured SSH identities -Iterate every `Host` block in *~/.ssh/config* (excluding pure-wildcard patterns and negations) and load its `IdentityFile`. Equivalent to `--extended host:NAME` for every host. Per-host expansion is delegated to `ssh -G NAME` so include files, Match blocks, and `%d`/`%u`/`%h` tokens work exactly as OpenSSH does. +Load identities for each concrete `Host` name listed in *~/.ssh/config*, as with `host:NAME`. If no concrete names are listed but a `Host *` block is present, evaluate that catch-all block instead. Other wildcard patterns and negations are not enumerated. + +OpenSSH evaluates the configuration through `ssh -G`, including applicable `Include` and `Match` rules. Keychain expands `~` home-directory prefixes in the resulting identity paths. It does not currently expand `%` tokens or `${VAR}` references left in that output. == @option ssh-allow-forwarded: adopt a forwarded SSH agent diff --git a/src/keychain/keys.py b/src/keychain/keys.py index 644fd1e..f3eea86 100644 --- a/src/keychain/keys.py +++ b/src/keychain/keys.py @@ -3,6 +3,7 @@ from __future__ import annotations +import os import subprocess from dataclasses import dataclass, field from pathlib import Path @@ -50,25 +51,29 @@ def deduped(self) -> ResolvedKeys: def all_host_identities(out: Output) -> ResolvedKeys: - """Return resolved IdentityFiles for every Host block in ``~/.ssh/config``. + """Resolve identities for concrete hosts, or a lone catch-all Host block. - Per-host expansion is delegated to ``ssh -G`` (via :func:`expand_host`) - so ``~``, ``${VAR}``, ``%d``/``%u``/``%h``, quoted args, ``Match``, and - ``Include`` are handled exactly as OpenSSH does -- no parallel parser. + OpenSSH evaluates Host/Match/Include rules; expand_host handles the + home-directory prefixes left in its IdentityFile output. """ config = Path.home() / ".ssh" / "config" if not config.is_file(): out.warn("No ~/.ssh/config -- can't extract host identities") return ResolvedKeys() hosts: set[str] = set() + catch_all = False for line in config.read_text(encoding="utf-8", errors="replace").splitlines(): s = line.strip() if not s or s.startswith("#") or not s.lower().startswith("host "): continue for pat in s.split()[1:]: - # Skip negations and pure wildcards: ssh -G needs a concrete name. - if not any(c in pat for c in "*?!"): + if pat == "*": + catch_all = True + elif not any(c in pat for c in "*?!"): hosts.add(pat) + if not hosts and catch_all: + # Query the literal catch-all, not an invented destination hostname. + hosts.add("*") result = ResolvedKeys() for h in sorted(hosts): result.extend(expand_host(h)) @@ -131,7 +136,8 @@ def expand_host(hostname: str) -> ResolvedKeys: paths: list[str] = [] for line in r.stdout.splitlines(): if line.startswith("identityfile "): - paths.append(line.split(None, 1)[1]) + # ssh -G selects identities but leaves home prefixes unexpanded. + paths.append(os.path.expanduser(line.split(None, 1)[1])) return keyf_expand(paths) diff --git a/tests/test_e2e_playbooks.py b/tests/test_e2e_playbooks.py index 12a1c9e..18071c6 100644 --- a/tests/test_e2e_playbooks.py +++ b/tests/test_e2e_playbooks.py @@ -568,6 +568,43 @@ def resolve_host(configured_host): assert loaded_ssh_keys(playbook, host) == {configured_public} +@OPENSSH_AGENT_ONLY +@pytest.mark.skipif(shutil.which("ssh") is None, reason="requires the OpenSSH client") +@pytest.mark.parametrize("home_prefix", [True, False]) +@pytest.mark.parametrize("included", [True, False]) +def test_confallhosts_catch_all_with_real_openssh(playbook: PlaybookRunner, home_prefix, included): + host = "testhost" + playbook.set_host(host) + ssh_dir = playbook.home / ".ssh" + ssh_dir.mkdir() + configured_key = ssh_dir / "key with spaces" + configured_public = generate_ssh_key(configured_key) + identity = "~/.ssh/key with spaces" if home_prefix else str(configured_key) + directive = f'IdentityFile "{identity}"\n' + if included: + fragment = ssh_dir / "identities.conf" + fragment.write_text(directive, encoding="utf-8") + directive = f'Include "{fragment}"\n' + config = ssh_dir / "config" + config.write_text(f"Host *\n {directive}", encoding="utf-8") + run = keys.run + seen_hosts = [] + + def isolated_ssh(command, **kwargs): + # OpenSSH finds config through passwd, not HOME. Only redirect that file; + # leave config evaluation and key loading to the real OpenSSH programs. + assert command == ["ssh", "-nG", "*"] + seen_hosts.append(command[-1]) + return run(["ssh", "-F", str(config), *command[1:]], **kwargs) + + playbook.monkeypatch.setattr(keys, "run", isolated_ssh) + + playbook.run("add", "--quiet", "--immediate", "--confallhosts") + + assert seen_hosts == ["*"] + assert loaded_ssh_keys(playbook, host) == {configured_public} + + @LINUX_AGENT_ONLY def test_inspect_command(playbook: PlaybookRunner): """Verify that keychain inspect successfully outputs state.""" diff --git a/tests/test_keys.py b/tests/test_keys.py index b9e71ba..6763694 100644 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -1,10 +1,10 @@ # SPDX-License-Identifier: GPL-3.0-only -"""Tests for keychain.keys.all_host_identities (--confallhosts). +"""SSH identity selection and path handling. -Issue #198: tilde / ${VAR} / %d / quoted args were not expanded. The fix -delegates per-host expansion to ``ssh -G`` (via ``expand_host``); these -tests verify the host-enumeration step pulls the right names out of the -config and that wildcard / negation patterns are skipped. +OpenSSH evaluates configuration; Keychain enumerates concrete hosts (or the +catch-all when there are none) and expands home-directory path prefixes. +OpenSSH 7.3p1, 8.0p1, 9.0p1 and 10.2p1 source dumps IdentityFile values before +the expansion in load_public_identity_files; -G alone does not expand paths. """ from __future__ import annotations @@ -15,6 +15,7 @@ from keychain import keys from keychain.util import KeychainError +from tests.support import set_home class _Out: @@ -60,6 +61,23 @@ def test_concrete_hosts_enumerated(fake_home, captured_hosts): assert "/expanded/alpha" in result.ssh +def test_catch_all_without_concrete_hosts_is_evaluated(fake_home, captured_hosts): + (fake_home / ".ssh" / "config").write_text("Host *\n IdentityFile ~/.ssh/id_default\n") + + result = keys.all_host_identities(_Out()) + + assert captured_hosts == ["*"] + assert result.ssh == ["/expanded/*"] + + +@pytest.mark.parametrize("config", ["", "# no hosts\n", "Host *.example !excluded.example\n"]) +def test_no_catch_all_or_concrete_hosts_does_not_invent_a_host(fake_home, captured_hosts, config): + (fake_home / ".ssh" / "config").write_text(config) + + assert keys.all_host_identities(_Out()) == keys.ResolvedKeys() + assert captured_hosts == [] + + def test_wildcards_and_negations_skipped(fake_home, captured_hosts): (fake_home / ".ssh" / "config").write_text( "Host *\n" @@ -195,6 +213,19 @@ def ssh_config(command, **kwargs): assert keys.expand_host("example.com").ssh == [str(first), str(second)] +@pytest.mark.parametrize("home_prefix", [True, False]) +def test_expand_host_accepts_home_prefix_or_expanded_path(monkeypatch, tmp_path, home_prefix): + set_home(monkeypatch, tmp_path) + keyfile = tmp_path / "key with spaces" + keyfile.write_text("private", encoding="utf-8") + identity = "~/key with spaces" if home_prefix else str(keyfile) + monkeypatch.setattr( + keys, "run", lambda *_a, **_kw: subprocess.CompletedProcess([], 0, f"identityfile {identity}\n", "") + ) + + assert keys.expand_host("example.com").ssh == [str(keyfile)] + + def test_resolve_requested_keys_mixes_prefixed_and_bare(fake_home, monkeypatch): keyfile = fake_home / ".ssh" / "id_test" keyfile.write_text("dummy") From 445994f6648d3ffa1e39c17f2c3d214ae9f46500 Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:21:16 -0500 Subject: [PATCH 07/11] Validate numeric ownership and protect user-supplied command operands Co-authored-by: tarilka0gg <216761460+tarilka0gg@users.noreply.github.com> --- src/keychain/agents.py | 4 +- src/keychain/keys.py | 4 +- src/keychain/paths.py | 41 ++++---- src/keychain/state.py | 4 +- src/keychain/util.py | 33 ++---- tests/support.py | 15 +++ tests/test_agents.py | 6 +- tests/test_cli_startup.py | 24 +---- tests/test_e2e_playbooks.py | 13 ++- tests/test_keys.py | 24 ++++- tests/test_paths.py | 193 ++++++++++++++++++++++++------------ tests/test_state.py | 25 ++--- 12 files changed, 232 insertions(+), 154 deletions(-) diff --git a/src/keychain/agents.py b/src/keychain/agents.py index 8946555..0512564 100644 --- a/src/keychain/agents.py +++ b/src/keychain/agents.py @@ -582,7 +582,7 @@ def remove(self, ssh_keys: list[str]) -> None: env = self.env or self.select_existing() for k in ssh_keys: try: - r = run(["ssh-add", "-d", k], env=env.as_dict(), c_locale=False) + r = run(["ssh-add", "-d", "--", k], env=env.as_dict(), c_locale=False) except (FileNotFoundError, OSError): raise KeychainError("ssh-add not found") if r.returncode == 0: @@ -640,7 +640,7 @@ def prepare_load( commands: list[list[str]] = [] fingerprints = [self.fingerprint(key) for key in missing] if missing: - commands.append([*base_cmd, *missing]) + commands.append([*base_cmd, "--", *missing]) for provider in pkcs11: commands.append([*base_cmd, "-s", provider]) fingerprints.extend(pkcs11_provider_fingerprints(provider, out) or [None]) diff --git a/src/keychain/keys.py b/src/keychain/keys.py index f3eea86..ba26cf4 100644 --- a/src/keychain/keys.py +++ b/src/keychain/keys.py @@ -94,7 +94,7 @@ def _resolve_bare_keys(keys: list[str], gpg_prog: str, gpg_lookup: bool) -> Reso continue if gpg_lookup: try: - r = run([gpg_prog, "--list-secret-keys", k], timeout=5) + r = run([gpg_prog, "--list-secret-keys", "--", k], timeout=5) if r.returncode == 0: result.gpg.append(k) continue @@ -128,7 +128,7 @@ def keyf_expand(paths: list[str]) -> ResolvedKeys: def expand_host(hostname: str) -> ResolvedKeys: """Expand a ``host:`` extkey into resolved SSH keys via ``ssh -nG``.""" try: - r = run(["ssh", "-nG", hostname], timeout=10) + r = run(["ssh", "-nG", "--", hostname], timeout=10) except subprocess.TimeoutExpired as exc: raise KeychainError(f'ssh timed out while expanding host "{hostname}"') from exc except (FileNotFoundError, OSError): diff --git a/src/keychain/paths.py b/src/keychain/paths.py index b1e27c6..f5a6bb4 100644 --- a/src/keychain/paths.py +++ b/src/keychain/paths.py @@ -15,10 +15,10 @@ from .output.core import Output from .util import ( KeychainError, - get_owner, + current_uid, lax_perm_warning, - lax_perms, unlink_quiet, + user_name, write_atomic, ) @@ -190,6 +190,8 @@ def build(cls, dir_opt: str | None, absolute: bool, host: str, pid_formats: str path, preserving the 2.x convention that ``--dir /tmp`` stored files under ``/tmp/.keychain``. """ + if "/" in host or "\0" in host or host in ("", ".", ".."): + raise KeychainError(f"Invalid host name {host!r}: it is used in file names") if dir_opt: expanded = _expand_home(dir_opt) # Preserve historic behaviour: a path containing "/." is taken verbatim, @@ -299,7 +301,7 @@ def ensure_keydir(self) -> None: raise KeychainError(f"can't write inside {self.keydir}") unlink_quiet(probe) - def security_audit(self, me: str, socket_path: str = "") -> list[SecurityCheck]: + def security_audit(self, socket_path: str = "") -> list[SecurityCheck]: paths: list[tuple[str, Path, bool]] = [("keydir", self.keydir, True)] paths.extend( ("pidfile" if fmt == "sh" else f"{fmt}_pidfile", self.pidfile_path(fmt), True) for fmt in self.pid_formats @@ -315,38 +317,35 @@ def security_audit(self, me: str, socket_path: str = "") -> list[SecurityCheck]: if socket_path: paths.append(("ssh_socket", Path(socket_path), False)) + uid = current_uid() checks: list[SecurityCheck] = [] for label, path, check_mode in paths: - if not path.exists(): + try: + info = path.stat() + except FileNotFoundError: + continue + except OSError: + checks.append(SecurityCheck(label, path, message=f"Cannot inspect {path}.", severity="err")) continue - owner = get_owner(path) - mode: str | None = None - mode_error = "" - if check_mode: - try: - mode = f"0{stat.S_IMODE(os.stat(path).st_mode):o}" - except OSError: - mode_error = f"Cannot inspect {path}." + owner = user_name(info.st_uid) if uid is not None else "" + mode = f"0{stat.S_IMODE(info.st_mode):o}" if check_mode else None message = "" severity = "" - if label == "keydir" and not path.is_dir(): + if label == "keydir" and not stat.S_ISDIR(info.st_mode): message = f"{path} is a file, not a directory." severity = "err" - elif owner and owner != me: - message = f"{path} is owned by {owner}, not {me}; refusing to use it." - severity = "err" - elif mode_error: - message = mode_error + elif uid is not None and info.st_uid != uid: + message = f"{path} is owned by {owner} (UID {info.st_uid}), not UID {uid}; refusing to use it." severity = "err" - elif check_mode and owner and lax_perms(path): + elif uid is not None and check_mode and stat.S_IMODE(info.st_mode) & 0o077: message = lax_perm_warning(self.keydir) severity = "err" checks.append(SecurityCheck(label, path, owner, mode, message, severity)) return checks - def check_runtime_perms(self, me: str) -> None: - for check in self.security_audit(me): + def check_runtime_perms(self) -> None: + for check in self.security_audit(): if check.severity == "err": raise KeychainError(check.message) diff --git a/src/keychain/state.py b/src/keychain/state.py index acb0696..d3af84e 100644 --- a/src/keychain/state.py +++ b/src/keychain/state.py @@ -141,7 +141,7 @@ def build(cls, args: Any, out: Output | None = None) -> KeychainState: args=args, ) k.out = out - paths.check_runtime_perms(me) + paths.check_runtime_perms() return k # ---- hostname (resolved by ``build``; reflected back for inspect) - @@ -361,7 +361,7 @@ def keydir_writable(self) -> bool: @property def security_audit(self) -> list[SecurityCheck]: socket_path = self.pidfile_socket if self.pidfile_socket_valid else "" - return self.paths.security_audit(self.user, socket_path) + return self.paths.security_audit(socket_path) # ---- key resolution (reflects user's --extended / cmdline) ------- diff --git a/src/keychain/util.py b/src/keychain/util.py index 2f96d3c..39f7097 100644 --- a/src/keychain/util.py +++ b/src/keychain/util.py @@ -10,7 +10,6 @@ import errno import os import socket -import stat import subprocess import sys import time @@ -211,14 +210,14 @@ def pid_alive(pid: int) -> bool: return True -def get_owner(path: PathLike) -> str: - """Return the username that owns *path*, or '' on error / non-POSIX.""" - if _pwd is None: - return "" - try: - return _pwd.getpwuid(os.stat(path).st_uid).pw_name - except (OSError, KeyError): - return "" +def user_name(uid: int) -> str: + """Display a UID as a username when available; never use this for authorization.""" + if _pwd is not None: + try: + return _pwd.getpwuid(uid).pw_name + except (KeyError, OSError): + pass + return str(uid) def current_uid() -> int | None: @@ -229,11 +228,8 @@ def current_uid() -> int | None: def current_user() -> str: """Best-effort username for the current process.""" uid = current_uid() - if _pwd is not None and uid is not None: - try: - return _pwd.getpwuid(uid).pw_name - except (KeyError, OSError): - pass + if uid is not None: + return user_name(uid) return os.environ.get("USER") or os.environ.get("LOGNAME") or os.environ.get("USERNAME") or "" @@ -247,15 +243,6 @@ def get_tty() -> str: return "" -def lax_perms(path: PathLike) -> bool: - """True if *path* is group/world readable, writable or executable.""" - try: - mode = stat.S_IMODE(os.stat(path).st_mode) - except OSError: - return False - return bool(mode & (stat.S_IRWXG | stat.S_IRWXO)) - - def lax_perm_warning(keydir: PathLike) -> str: """Canonical warning text for a keychain dir / pidfile with lax perms. diff --git a/tests/support.py b/tests/support.py index 0e939ca..9cb8e8e 100644 --- a/tests/support.py +++ b/tests/support.py @@ -13,3 +13,18 @@ def set_home(monkeypatch, home: Path, *, patch_path_home: bool = False) -> None: monkeypatch.setenv("USERPROFILE", str(home)) monkeypatch.delenv("HOMEDRIVE", raising=False) monkeypatch.delenv("HOMEPATH", raising=False) + + +def set_file_stat(monkeypatch, path: Path, *, uid: int = 1000, mode: int = 0o100600) -> None: + """Model POSIX ownership/mode for one test path, including on Windows.""" + original = Path.stat + + def stat_for_path(self, *args, **kwargs): + info = original(self, *args, **kwargs) + if self != path: + return info + fields = list(info) + fields[0], fields[4] = mode, uid + return os.stat_result(fields) + + monkeypatch.setattr(Path, "stat", stat_for_path) diff --git a/tests/test_agents.py b/tests/test_agents.py index ee1a791..7b95cdd 100644 --- a/tests/test_agents.py +++ b/tests/test_agents.py @@ -233,7 +233,7 @@ def test_prepare_load_can_skip_announcement(self, monkeypatch, capsys): plan = self._agent(monkeypatch).prepare_load(["/home/user/.ssh/key1"], announce=False) assert plan is not None - assert plan.commands == [["ssh-add", "/home/user/.ssh/key1"]] + assert plan.commands == [["ssh-add", "--", "/home/user/.ssh/key1"]] assert capsys.readouterr().err == "" def test_prepare_load_quiet_suppresses_success_reports(self, monkeypatch): @@ -243,7 +243,7 @@ def test_prepare_load_quiet_suppresses_success_reports(self, monkeypatch): assert plan is not None assert plan.commands == [ - ["ssh-add", "-q", "/home/user/.ssh/key1"], + ["ssh-add", "-q", "--", "/home/user/.ssh/key1"], ["ssh-add", "-q", "-s", "/usr/lib/pkcs11/opensc-pkcs11.so"], ] @@ -261,7 +261,7 @@ def test_prepare_load_combines_file_keys_and_pkcs11_provider(self, monkeypatch): assert plan is not None assert plan.commands == [ - ["ssh-add", "/home/user/.ssh/key1"], + ["ssh-add", "--", "/home/user/.ssh/key1"], ["ssh-add", "-s", "/usr/lib/pkcs11/opensc-pkcs11.so"], ] diff --git a/tests/test_cli_startup.py b/tests/test_cli_startup.py index e440176..751185a 100644 --- a/tests/test_cli_startup.py +++ b/tests/test_cli_startup.py @@ -4,7 +4,6 @@ import os import subprocess import sys -from pathlib import Path from types import SimpleNamespace import pytest @@ -12,7 +11,7 @@ from keychain import agents, main from keychain.paths import KeychainPaths from keychain.util import KeychainError -from tests.support import set_home +from tests.support import set_file_stat, set_home @pytest.mark.skipif(os.name == "nt", reason="requires POSIX file ownership") @@ -186,6 +185,7 @@ def _patch_default_startup(self, monkeypatch): lambda: SimpleNamespace(supported=True, name="linux", reason=""), ) monkeypatch.setattr("keychain.state.current_user", lambda: "me") + monkeypatch.setattr("keychain.paths.current_uid", lambda: 1000) monkeypatch.setattr( main.KeychainApp, "_resolve_requested_keys", @@ -198,22 +198,14 @@ def test_default_startup_no_lax_warning_when_home_keydir_is_tight(self, tmp_path home = tmp_path / "home" keydir = home / ".keychain" keydir.mkdir(parents=True, mode=0o700) - seen: list[Path] = [] - - def fake_lax_perms(path): - seen.append(Path(path)) - return False - set_home(monkeypatch, home, patch_path_home=True) monkeypatch.setenv("HOSTNAME", "testhost") monkeypatch.chdir(tmp_path) - monkeypatch.setattr("keychain.paths.get_owner", lambda _path: "me") - monkeypatch.setattr("keychain.paths.lax_perms", fake_lax_perms) + set_file_stat(monkeypatch, keydir, mode=0o40700) with pytest.raises(SystemExit) as exc: main.main([]) assert exc.value.code in (None, 0) - assert seen == [keydir] assert "lax permissions" not in capsys.readouterr().err def test_default_startup_fails_when_resolved_home_keydir_is_lax(self, tmp_path, monkeypatch, capsys): @@ -221,20 +213,12 @@ def test_default_startup_fails_when_resolved_home_keydir_is_lax(self, tmp_path, home = tmp_path / "home" keydir = home / ".keychain" keydir.mkdir(parents=True, mode=0o700) - seen: list[Path] = [] - - def fake_lax_perms(path): - seen.append(Path(path)) - return Path(path) == keydir - set_home(monkeypatch, home, patch_path_home=True) monkeypatch.setenv("HOSTNAME", "testhost") monkeypatch.chdir(tmp_path) - monkeypatch.setattr("keychain.paths.get_owner", lambda _path: "me") - monkeypatch.setattr("keychain.paths.lax_perms", fake_lax_perms) + set_file_stat(monkeypatch, keydir, mode=0o40777) with pytest.raises(SystemExit) as exc: main.main([]) assert exc.value.code == 1 - assert seen == [keydir] assert "lax permissions" in capsys.readouterr().err diff --git a/tests/test_e2e_playbooks.py b/tests/test_e2e_playbooks.py index 18071c6..f2e9bb8 100644 --- a/tests/test_e2e_playbooks.py +++ b/tests/test_e2e_playbooks.py @@ -466,19 +466,22 @@ def test_clear_does_not_wipe_when_requested_keys_do_not_resolve(playbook: Playbo @OPENSSH_AGENT_ONLY -def test_forget_removes_only_the_requested_ssh_identity(playbook: PlaybookRunner): +@pytest.mark.parametrize("filename", ["id_forgotten", "-D"]) +def test_forget_removes_only_the_requested_ssh_identity(playbook: PlaybookRunner, filename): """Verify forget evicts the requested key without disturbing another identity.""" host = "testhost" playbook.set_host(host) - forgotten_key = playbook.home / "id_forgotten" + forgotten_key = playbook.home / filename retained_key = playbook.home / "id_retained" forgotten_public = generate_ssh_key(forgotten_key) retained_public = generate_ssh_key(retained_key) - playbook.run("add", "--quiet", "--immediate", str(forgotten_key), str(retained_key)) + playbook.monkeypatch.chdir(playbook.home) + key_arg = f"sshk:{filename}" + playbook.run("add", "--quiet", "--immediate", key_arg, str(retained_key)) assert loaded_ssh_keys(playbook, host) == {forgotten_public, retained_public} - playbook.run("forget", "--quiet", str(forgotten_key)) + playbook.run("forget", "--quiet", key_arg) assert loaded_ssh_keys(playbook, host) == {retained_public} @@ -593,7 +596,7 @@ def test_confallhosts_catch_all_with_real_openssh(playbook: PlaybookRunner, home def isolated_ssh(command, **kwargs): # OpenSSH finds config through passwd, not HOME. Only redirect that file; # leave config evaluation and key loading to the real OpenSSH programs. - assert command == ["ssh", "-nG", "*"] + assert command == ["ssh", "-nG", "--", "*"] seen_hosts.append(command[-1]) return run(["ssh", "-F", str(config), *command[1:]], **kwargs) diff --git a/tests/test_keys.py b/tests/test_keys.py index 6763694..3e9d1c5 100644 --- a/tests/test_keys.py +++ b/tests/test_keys.py @@ -10,6 +10,7 @@ from __future__ import annotations import subprocess +from pathlib import Path import pytest @@ -175,6 +176,25 @@ def missing(*_args, **_kwargs): assert out.missing == ["ABCD1234"] +def test_gpg_lookup_keeps_dash_prefixed_key_out_of_options(fake_home, monkeypatch): + def lookup(command, **kwargs): + assert command == ["gpg", "--list-secret-keys", "--", "--version"] + return subprocess.CompletedProcess(command, 1, "", "not found") + + monkeypatch.setattr(keys, "run", lookup) + result = keys.resolve_requested_keys(False, False, ["--version"], "gpg", _Out()) + assert result.missing == ["--version"] + + +def test_ssh_config_keeps_dash_prefixed_host_out_of_options(monkeypatch): + def lookup(command, **kwargs): + assert command == ["ssh", "-nG", "--", "-oIdentityFile=unwanted"] + return subprocess.CompletedProcess(command, 0, "", "") + + monkeypatch.setattr(keys, "run", lookup) + assert keys.expand_host("-oIdentityFile=unwanted") == keys.ResolvedKeys() + + def test_expand_host_reports_ssh_probe_timeout(monkeypatch): def timeout(cmd, **kwargs): raise subprocess.TimeoutExpired(cmd, kwargs["timeout"]) @@ -199,7 +219,7 @@ def test_expand_host_resolves_identityfiles_from_openssh(monkeypatch, tmp_path): second.write_text("private", encoding="utf-8") def ssh_config(command, **kwargs): - assert command == ["ssh", "-nG", "example.com"] + assert command == ["ssh", "-nG", "--", "example.com"] assert kwargs == {"timeout": 10} return subprocess.CompletedProcess( command, @@ -223,7 +243,7 @@ def test_expand_host_accepts_home_prefix_or_expanded_path(monkeypatch, tmp_path, keys, "run", lambda *_a, **_kw: subprocess.CompletedProcess([], 0, f"identityfile {identity}\n", "") ) - assert keys.expand_host("example.com").ssh == [str(keyfile)] + assert [Path(path) for path in keys.expand_host("example.com").ssh] == [keyfile] def test_resolve_requested_keys_mixes_prefixed_and_bare(fake_home, monkeypatch): diff --git a/tests/test_paths.py b/tests/test_paths.py index b71eaef..ea3c530 100644 --- a/tests/test_paths.py +++ b/tests/test_paths.py @@ -6,15 +6,17 @@ import subprocess import tempfile from pathlib import Path +from types import SimpleNamespace from unittest.mock import patch import pytest +from keychain import util from keychain.env import SshAgentRef from keychain.output.core import Output from keychain.paths import KeychainPaths from keychain.util import KeychainError -from tests.support import set_home +from tests.support import set_file_stat, set_home def _out(): @@ -328,71 +330,63 @@ def test_renderers_reject_line_injection(self, tmp_path): # --------------------------------------------------------------------------- +@pytest.fixture +def audited_paths(tmp_path, monkeypatch): + monkeypatch.setattr("keychain.paths.current_uid", lambda: 1000) + monkeypatch.setattr("keychain.paths.user_name", lambda uid: {1000: "me", 2000: "attacker"}.get(uid, str(uid))) + set_file_stat(monkeypatch, tmp_path, mode=0o40700) + return KeychainPaths(keydir=tmp_path, host="h") + + class TestCheckRuntimePerms: - def test_no_pidfiles_no_error(self, tmp_path): - kp = KeychainPaths(keydir=tmp_path, host="h") - tmp_path.mkdir(exist_ok=True) - with ( - patch("keychain.paths.get_owner", return_value="me"), - patch("keychain.paths.lax_perms", return_value=False), - ): - kp.check_runtime_perms("me") - - def test_owned_by_us_passes(self, tmp_path): - kp = KeychainPaths(keydir=tmp_path, host="h") - kp.pidfile_path("sh").write_text("SSH_AUTH_SOCK=/tmp/foo\n") - with ( - patch("keychain.paths.get_owner", return_value="me"), - patch("keychain.paths.lax_perms", return_value=False), - ): - kp.check_runtime_perms("me") - - def test_foreign_owner_raises_keychain_error(self, tmp_path): - kp = KeychainPaths(keydir=tmp_path, host="h") - kp.pidfile_path("sh").write_text("SSH_AUTH_SOCK=/tmp/foo\n") - with ( - patch( - "keychain.paths.get_owner", - side_effect=lambda path: "attacker" if Path(path) == kp.pidfile_path("sh") else "me", - ), - patch("keychain.paths.lax_perms", return_value=False), - ): - with pytest.raises(KeychainError, match="owned by attacker"): - kp.check_runtime_perms("me") - - def test_lax_perms_raise_keychain_error(self, tmp_path): - kp = KeychainPaths(keydir=tmp_path, host="h") - kp.pidfile_path("sh").write_text("SSH_AUTH_SOCK=/tmp/foo\n") - with ( - patch("keychain.paths.get_owner", return_value="me"), - patch("keychain.paths.lax_perms", side_effect=lambda path: Path(path) == kp.pidfile_path("sh")), - ): - with pytest.raises(KeychainError, match="lax permissions"): - kp.check_runtime_perms("me") - - def test_coordination_state_is_checked(self, tmp_path): - kp = KeychainPaths(keydir=tmp_path, host="h") - kp.state_file.write_text("{}\n", encoding="utf-8") - with ( - patch( - "keychain.paths.get_owner", - side_effect=lambda path: "attacker" if Path(path) == kp.state_file else "me", - ), - patch("keychain.paths.lax_perms", return_value=False), - ): - with pytest.raises(KeychainError, match="owned by attacker"): - kp.check_runtime_perms("me") + def test_no_pidfiles_no_error(self, audited_paths): + audited_paths.check_runtime_perms() + assert [row.label for row in audited_paths.security_audit()] == ["keydir"] + def test_owned_by_us_passes(self, audited_paths, monkeypatch): + pidfile = audited_paths.pidfile_path("sh") + pidfile.write_text("SSH_AUTH_SOCK=/tmp/foo\n") + set_file_stat(monkeypatch, pidfile) + audited_paths.check_runtime_perms() -class TestEnsureKeydir: - def test_existing_lax_directory_is_rejected_by_runtime_audit(self, tmp_path): - keydir = tmp_path / ".keychain" - keydir.mkdir(mode=0o700) - kp = KeychainPaths(keydir=keydir, host="h") + @pytest.mark.parametrize( + "field", ["sh", "csh", "fish", "envfile", "state_file", "state_lockf", "activation_lockf", "waiters_dir"] + ) + def test_foreign_runtime_owner_is_rejected(self, audited_paths, monkeypatch, field): + path = ( + audited_paths.pidfile_path(field) if field in audited_paths.pid_formats else getattr(audited_paths, field) + ) + path.touch() + set_file_stat(monkeypatch, path, uid=2000) + with pytest.raises(KeychainError, match="owned by attacker"): + audited_paths.check_runtime_perms() + + def test_lax_perms_raise_keychain_error(self, audited_paths, monkeypatch): + pidfile = audited_paths.pidfile_path("sh") + pidfile.touch() + set_file_stat(monkeypatch, pidfile, mode=0o100644) + with pytest.raises(KeychainError, match="lax permissions"): + audited_paths.check_runtime_perms() + + def test_each_path_is_statted_once(self, audited_paths, monkeypatch): + original = Path.stat + seen = [] - with patch("keychain.paths.get_owner", return_value="me"), patch("keychain.paths.lax_perms", return_value=True): - with pytest.raises(KeychainError, match="lax permissions"): - kp.check_runtime_perms("me") + def record(path, *args, **kwargs): + seen.append(path) + return original(path, *args, **kwargs) + + monkeypatch.setattr(Path, "stat", record) + audited_paths.check_runtime_perms() + assert audited_paths.keydir in seen + assert len(seen) == len(set(seen)) + + +class TestEnsureKeydir: + def test_existing_lax_directory_is_rejected_by_runtime_audit(self, audited_paths, monkeypatch): + set_file_stat(monkeypatch, audited_paths.keydir, mode=0o40777) + with pytest.raises(KeychainError, match="lax permissions"): + audited_paths.check_runtime_perms() def test_creates_missing_directory(self, tmp_path): kp = KeychainPaths(keydir=tmp_path / ".keychain", host="h") @@ -400,3 +394,78 @@ def test_creates_missing_directory(self, tmp_path): kp.ensure_keydir() assert kp.keydir.is_dir() + + +class TestSecurityHardening: + @pytest.mark.parametrize("lookup_error", [KeyError, OSError]) + @pytest.mark.parametrize( + "owner_uid,mode,expected", + [(1000, 0o40700, ""), (1000, 0o40777, "lax permissions"), (54321, 0o40700, "owned by")], + ) + def test_missing_account_does_not_change_authorization( + self, audited_paths, monkeypatch, lookup_error, owner_uid, mode, expected + ): + def missing(_uid): + raise lookup_error("account lookup unavailable") + + monkeypatch.setattr(util, "_pwd", SimpleNamespace(getpwuid=missing)) + monkeypatch.setattr(util, "current_uid", lambda: 1000) + monkeypatch.setattr("keychain.paths.user_name", util.user_name) + set_file_stat(monkeypatch, audited_paths.keydir, uid=owner_uid, mode=mode) + + assert util.current_user() == "1000" + row = audited_paths.security_audit()[0] + assert row.owner == str(owner_uid) + if expected: + with pytest.raises(KeychainError, match=expected): + audited_paths.check_runtime_perms() + else: + audited_paths.check_runtime_perms() + + def test_numeric_username_cannot_authorize_another_uid(self, audited_paths, monkeypatch): + def lookup(uid): + if uid == 1000: + return SimpleNamespace(pw_name="54321") + raise KeyError(uid) + + monkeypatch.setattr(util, "_pwd", SimpleNamespace(getpwuid=lookup)) + monkeypatch.setattr(util, "current_uid", lambda: 1000) + monkeypatch.setattr("keychain.paths.user_name", util.user_name) + set_file_stat(monkeypatch, audited_paths.keydir, uid=54321, mode=0o40700) + + assert util.current_user() == "54321" + assert audited_paths.security_audit()[0].owner == "54321" + with pytest.raises(KeychainError, match="not UID 1000"): + audited_paths.check_runtime_perms() + + def test_unreadable_metadata_is_an_error(self, audited_paths, monkeypatch): + original = Path.stat + + def unreadable(path, *args, **kwargs): + if path == audited_paths.keydir: + raise PermissionError("denied") + return original(path, *args, **kwargs) + + monkeypatch.setattr(Path, "stat", unreadable) + with pytest.raises(KeychainError, match="Cannot inspect"): + audited_paths.check_runtime_perms() + + def test_socket_owner_is_checked_without_requiring_private_mode(self, audited_paths, monkeypatch): + sock = audited_paths.keydir / "agent.sock" + sock.touch() + set_file_stat(monkeypatch, sock, mode=0o140777) + assert audited_paths.security_audit(str(sock))[-1].severity == "" + set_file_stat(monkeypatch, sock, uid=2000, mode=0o140777) + assert audited_paths.security_audit(str(sock))[-1].severity == "err" + + def test_no_posix_uid_does_not_claim_owner_validation(self, audited_paths, monkeypatch): + monkeypatch.setattr("keychain.paths.current_uid", lambda: None) + set_file_stat(monkeypatch, audited_paths.keydir, mode=0o40777) + row = audited_paths.security_audit()[0] + assert row.owner == "" + assert row.severity == "" + + @pytest.mark.parametrize("host", ["../evil", "a/b", "..", ".", "", "a\0b"]) + def test_host_cannot_leave_the_keydir(self, tmp_path, host): + with pytest.raises(KeychainError, match="Invalid host name"): + KeychainPaths.build(str(tmp_path), False, host) diff --git a/tests/test_state.py b/tests/test_state.py index 681c584..66b34b1 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -16,6 +16,7 @@ from keychain.paths import KeychainPaths from keychain.runtime import platform from keychain.runtime.config import RuntimeConfig +from tests.support import set_file_stat @contextmanager @@ -299,12 +300,12 @@ def test_render_inspect_json_includes_resolved_keys_when_args(tmp_path, paths, c class TestSecurityAudit: - def test_keydir_owner_and_mode_share_one_record(self, paths): + def test_keydir_owner_and_mode_share_one_record(self, paths, monkeypatch): + set_file_stat(monkeypatch, paths.keydir, mode=0o40700) with ( - patch("keychain.paths.get_owner", return_value="me"), - patch("keychain.paths.os.stat") as st_mock, + patch("keychain.paths.user_name", return_value="me"), + patch("keychain.paths.current_uid", return_value=1000), ): - st_mock.return_value.st_mode = 0o40700 # dir, 0700 ks = state.KeychainState(paths=paths, user="me") record = next(check for check in ks.security_audit if check.label == "keydir") assert record.path == paths.keydir @@ -315,12 +316,12 @@ def test_keydir_owner_and_mode_share_one_record(self, paths): assert record.severity == "" assert record.status == "ok" - def test_keydir_lax_perms_emits_hint(self, paths): + def test_keydir_lax_perms_emits_hint(self, paths, monkeypatch): + set_file_stat(monkeypatch, paths.keydir, mode=0o40777) with ( - patch("keychain.paths.get_owner", return_value="me"), - patch("keychain.paths.os.stat") as st_mock, + patch("keychain.paths.user_name", return_value="me"), + patch("keychain.paths.current_uid", return_value=1000), ): - st_mock.return_value.st_mode = 0o40777 # dir, 0777 ks = state.KeychainState(paths=paths, user="me") row = next(check for check in ks.security_audit if check.label == "keydir") assert row.mode == "0777" @@ -328,12 +329,12 @@ def test_keydir_lax_perms_emits_hint(self, paths): assert row.severity == "err" assert row.status == "error" - def test_foreign_keydir_owner_emits_hint(self, paths): + def test_foreign_keydir_owner_emits_hint(self, paths, monkeypatch): + set_file_stat(monkeypatch, paths.keydir, uid=2000, mode=0o40700) with ( - patch("keychain.paths.get_owner", return_value="attacker"), - patch("keychain.paths.os.stat") as st_mock, + patch("keychain.paths.user_name", return_value="attacker"), + patch("keychain.paths.current_uid", return_value=1000), ): - st_mock.return_value.st_mode = 0o40700 ks = state.KeychainState(paths=paths, user="me") row = next(check for check in ks.security_audit if check.label == "keydir") assert row.owner == "attacker" From 50cb91f645f5d75763c7b3ed541607838fb2e76a Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:21:19 -0500 Subject: [PATCH 08/11] Encapsulate macOS SSH confirmation in the platform API --- src/keychain/agents.py | 43 ++++---------------------------- src/keychain/runtime/platform.py | 42 +++++++++++++++++++++++++++++-- tests/test_agents.py | 12 ++++----- tests/test_runtime.py | 37 ++++++++++++++++++++++++++- 4 files changed, 87 insertions(+), 47 deletions(-) diff --git a/src/keychain/agents.py b/src/keychain/agents.py index 0512564..77a0b84 100644 --- a/src/keychain/agents.py +++ b/src/keychain/agents.py @@ -18,7 +18,7 @@ from .env import SshAgentRef from .output.core import Output -from .util import KeychainError, LockFile, current_uid, get_tty, run, tempdir, unlink_quiet, write_atomic +from .util import KeychainError, LockFile, current_uid, get_tty, run, tempdir, unlink_quiet if TYPE_CHECKING: from .state import KeychainState @@ -49,34 +49,6 @@ def _split_agent_args(value: str, agent: str) -> list[str]: raise KeychainError(f"Invalid {agent} agent arguments: {exc}") from exc -_MACOS_ASKPASS = """\ -#!/bin/sh -[ "${SSH_ASKPASS_PROMPT-}" = "confirm" ] || exit 1 -exec /usr/bin/osascript - "$1" <<'APPLESCRIPT' -on run argv - try - set answer to display dialog (item 1 of argv) with title "Keychain SSH Confirmation" buttons {"Deny", "Allow"} default button "Deny" cancel button "Deny" - if button returned of answer is "Allow" then return "yes" - on error number -128 - end try - error number 1 -end run -APPLESCRIPT -""" - - -def ensure_macos_askpass(path: Path) -> Path: - """Install Keychain's confirmation-only macOS askpass helper securely.""" - try: - if path.read_text(encoding="utf-8") == _MACOS_ASKPASS and stat.S_IMODE(path.stat().st_mode) == 0o700: - return path - except OSError: - pass - - write_atomic(path, _MACOS_ASKPASS, 0o700) - return path - - # --------------------------------------------------------------------------- # Regex patterns # --------------------------------------------------------------------------- @@ -399,8 +371,8 @@ def _validate_candidate(self, source: str, agent_env: SshAgentRef, *, announce: def select_existing(self, *, pidfile_only: bool = False, announce: bool = False) -> SshAgentRef: """Select an existing SSH agent according to Keychain policy.""" candidates = [("pidfile", self.keychain_state.pidfile_env)] - native_confirm = bool(self._option("confirm")) and self.keychain_state.platform.name == "darwin" - if not pidfile_only and not (bool(self._option("no_inherit")) or native_confirm): + own_agent = bool(self._option("confirm")) and self.keychain_state.platform.confirm_requires_own_agent + if not pidfile_only and not (bool(self._option("no_inherit")) or own_agent): candidates.append(("env", self.keychain_state.inherited_env)) self.env = SshAgentRef() @@ -435,7 +407,6 @@ def start(self, state_lock: LockFile) -> bool: a = self.keychain_state.args paths = self.keychain_state.paths confirm = bool(a.get_value("confirm")) - native_confirm = confirm and self.keychain_state.platform.name == "darwin" if confirm and bool(a.get_value("no_gui")): raise KeychainError("--confirm requires graphical confirmation and cannot be combined with --no-gui") @@ -495,12 +466,8 @@ def start(self, state_lock: LockFile) -> bool: raise KeychainError(f"Invalid SSH agent arguments: {exc}") from exc ssh_agent_socket = dict(options)["-a"] spawn_env = dict(self.keychain_state.env) - if native_confirm: - askpass = spawn_env.get("SSH_ASKPASS") - if not askpass: - askpass = str(ensure_macos_askpass(paths.keydir / "ssh-askpass-macos")) - spawn_env["SSH_ASKPASS"] = askpass - spawn_env["SSH_ASKPASS_REQUIRE"] = "force" + if confirm: + self.keychain_state.platform.configure_ssh_confirmation(spawn_env, paths.keydir) try: r = run(cmd, env=spawn_env) except (FileNotFoundError, OSError) as exc: diff --git a/src/keychain/runtime/platform.py b/src/keychain/runtime/platform.py index 0424b5b..d43a74c 100644 --- a/src/keychain/runtime/platform.py +++ b/src/keychain/runtime/platform.py @@ -18,9 +18,11 @@ import os import re import shutil +import stat import subprocess +from pathlib import Path -from ..util import KeychainError +from ..util import KeychainError, write_atomic class Platform: @@ -35,6 +37,10 @@ class Platform: name = "unknown" reason = "" + confirm_requires_own_agent = False + + def configure_ssh_confirmation(self, env: dict[str, str], keydir: Path) -> None: + """Prepare a new agent's confirmation environment; normally no changes.""" @property def supported(self) -> bool: @@ -115,6 +121,37 @@ class _BSDPlatform(_PsPlatform): ps_command = ("ps", "-ww", "-A", "-o", "pid=", "-o", "uid=", "-o", "comm=") +class _DarwinPlatform(_BSDPlatform): + # A pre-existing inherited agent cannot acquire our askpass environment. + confirm_requires_own_agent = True + _ASKPASS = """\ +#!/bin/sh +[ "${SSH_ASKPASS_PROMPT-}" = "confirm" ] || exit 1 +exec /usr/bin/osascript - "$1" <<'APPLESCRIPT' +on run argv + try + set answer to display dialog (item 1 of argv) with title "Keychain SSH Confirmation" buttons {"Deny", "Allow"} default button "Deny" cancel button "Deny" + if button returned of answer is "Allow" then return "yes" + on error number -128 + end try + error number 1 +end run +APPLESCRIPT +""" + + def configure_ssh_confirmation(self, env: dict[str, str], keydir: Path) -> None: + if not env.get("SSH_ASKPASS"): + path = keydir / "ssh-askpass-macos" + try: + installed = path.read_text(encoding="utf-8") == self._ASKPASS and stat.S_IMODE(path.stat().st_mode) == 0o700 + except OSError: + installed = False + if not installed: + write_atomic(path, self._ASKPASS, 0o700) + env["SSH_ASKPASS"] = str(path) + env["SSH_ASKPASS_REQUIRE"] = "force" + + class _SolarisPlatform(_PsPlatform): # comm comes from bounded argv text. fname avoids path truncation; # a 16-character header widens its default eight-character field. @@ -219,7 +256,8 @@ def _classify(platform_name: str, has_ps: bool | None = None) -> Platform: implementation: type[_PsPlatform] = _PsPlatform for prefixes, candidate in ( (("linux", "android"), _LinuxPlatform), - (("darwin", "freebsd", "openbsd", "netbsd", "dragonfly"), _BSDPlatform), + (("darwin",), _DarwinPlatform), + (("freebsd", "openbsd", "netbsd", "dragonfly"), _BSDPlatform), (("sunos",), _SolarisPlatform), (("cygwin", "msys"), _CygwinPlatform), ): diff --git a/tests/test_agents.py b/tests/test_agents.py index 7b95cdd..3ab1588 100644 --- a/tests/test_agents.py +++ b/tests/test_agents.py @@ -760,7 +760,7 @@ def _agent( env=inherited.as_dict(), inherited_env=inherited, pidfile_env=pidfile, - platform=SimpleNamespace(name=platform_name), + platform=platform._classify(platform_name, has_ps=True), ssh_pid_status=lambda pid: "verified" if pid in ( [11, 22] if ssh_agent_pids is None else ssh_agent_pids ) else "unverified", @@ -1059,7 +1059,7 @@ def test_confirm_and_no_gui_are_rejected(self, short_keydir): def test_macos_confirm_configures_new_agent_with_native_askpass(self, short_keydir, monkeypatch): """A managed macOS agent must inherit the helper needed for later signing prompts.""" agent, paths = self._agent_with_args(short_keydir, "--confirm") - monkeypatch.setattr(agent.keychain_state, "platform", SimpleNamespace(name="darwin")) + monkeypatch.setattr(agent.keychain_state, "platform", platform._classify("darwin", has_ps=True)) captured_env = None def fake_run(cmd, *_args, **kwargs): @@ -1090,7 +1090,7 @@ def fake_run(cmd, *_args, **kwargs): def test_macos_confirm_preserves_external_askpass(self, short_keydir, monkeypatch): """An explicitly configured helper takes precedence over Keychain's macOS helper.""" agent, paths = self._agent_with_args(short_keydir, "--confirm") - monkeypatch.setattr(agent.keychain_state, "platform", SimpleNamespace(name="darwin")) + monkeypatch.setattr(agent.keychain_state, "platform", platform._classify("darwin", has_ps=True)) agent.keychain_state.env["SSH_ASKPASS"] = "/custom/askpass" captured_env = None @@ -1116,7 +1116,7 @@ def fake_run(cmd, *_args, **kwargs): def test_macos_confirm_does_not_inherit_agent(self, short_keydir, monkeypatch): """Native confirmation requires an agent born with Keychain's askpass environment.""" agent, paths = self._agent_with_args(short_keydir, "--confirm", inherit=True) - monkeypatch.setattr(agent.keychain_state, "platform", SimpleNamespace(name="darwin")) + monkeypatch.setattr(agent.keychain_state, "platform", platform._classify("darwin", has_ps=True)) agent.keychain_state.env.update({"SSH_AUTH_SOCK": "/tmp/inherited.sock", "SSH_AGENT_PID": "42"}) checked_sources: list[str] = [] @@ -1135,7 +1135,7 @@ def fake_validation(source, agent_env, *, announce=False): def test_macos_confirm_still_reuses_pidfile_agent(self, short_keydir, monkeypatch): """Implicit --no-inherit must not bypass Keychain's normal pidfile lookup.""" agent, paths = self._agent_with_args(short_keydir, "--confirm", inherit=True) - monkeypatch.setattr(agent.keychain_state, "platform", SimpleNamespace(name="darwin")) + monkeypatch.setattr(agent.keychain_state, "platform", platform._classify("darwin", has_ps=True)) pidfile_agent = SshAgentRef(sock="/tmp/pidfile.sock", pid="42") paths.write(pidfile_agent, _out()) monkeypatch.setattr(agent, "_validate_candidate", lambda _source, agent_env, **_kwargs: agent_env) @@ -1149,7 +1149,7 @@ def test_macos_confirm_still_reuses_pidfile_agent(self, short_keydir, monkeypatc def test_implicit_no_inherit_is_macos_confirm_only(self, short_keydir, monkeypatch, platform_name, extra_args): """Normal macOS starts and confirmed Linux starts retain inherited-agent behavior.""" agent, _paths = self._agent_with_args(short_keydir, *extra_args, inherit=True) - monkeypatch.setattr(agent.keychain_state, "platform", SimpleNamespace(name=platform_name)) + monkeypatch.setattr(agent.keychain_state, "platform", platform._classify(platform_name, has_ps=True)) inherited = SshAgentRef(sock="/tmp/inherited.sock", pid="42") agent.keychain_state.env.update(inherited.as_dict()) monkeypatch.setattr(agent, "_validate_candidate", lambda _source, agent_env, **_kwargs: agent_env) diff --git a/tests/test_runtime.py b/tests/test_runtime.py index db859cd..2a12f60 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -77,9 +77,44 @@ def test_detection_is_cached(): assert first is second +@pytest.mark.parametrize("name", ["linux", "freebsd14", "openbsd8", "sunos5", "cygwin", "msys2"]) +def test_confirmation_environment_is_unchanged_outside_macos(name, tmp_path): + p = platform._classify(name, has_ps=True) + env = {"SSH_ASKPASS": "/custom/askpass", "SSH_ASKPASS_REQUIRE": "prefer"} + p.configure_ssh_confirmation(env, tmp_path) + assert not p.confirm_requires_own_agent + assert env == {"SSH_ASKPASS": "/custom/askpass", "SSH_ASKPASS_REQUIRE": "prefer"} + assert not list(tmp_path.iterdir()) + + +def test_macos_confirmation_preserves_explicit_helper(tmp_path): + p = platform._classify("darwin", has_ps=True) + p.name = "freebsd14" # Behavior belongs to the class, not the display label. + env = {"SSH_ASKPASS": "/custom/askpass"} + p.configure_ssh_confirmation(env, tmp_path) + assert p.confirm_requires_own_agent + assert env == {"SSH_ASKPASS": "/custom/askpass", "SSH_ASKPASS_REQUIRE": "force"} + assert not list(tmp_path.iterdir()) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX helper permissions") +def test_macos_confirmation_repairs_helper_and_avoids_rewrites(tmp_path, monkeypatch): + p = platform._classify("darwin", has_ps=True) + helper = tmp_path / "ssh-askpass-macos" + helper.write_text("stale helper") + helper.chmod(0o755) + env = {} + p.configure_ssh_confirmation(env, tmp_path) + assert helper.read_text() == p._ASKPASS + assert helper.stat().st_mode & 0o777 == 0o700 + assert env == {"SSH_ASKPASS": str(helper), "SSH_ASKPASS_REQUIRE": "force"} + monkeypatch.setattr(platform, "write_atomic", lambda *_a: pytest.fail("helper is already current")) + p.configure_ssh_confirmation({}, tmp_path) + + @pytest.mark.parametrize("name, implementation", [ ("linux", platform._LinuxPlatform), ("android", platform._LinuxPlatform), - ("darwin", platform._BSDPlatform), ("freebsd14", platform._BSDPlatform), + ("darwin", platform._DarwinPlatform), ("freebsd14", platform._BSDPlatform), ("openbsd7", platform._BSDPlatform), ("netbsd10", platform._BSDPlatform), ("dragonfly6", platform._BSDPlatform), ("sunos5", platform._SolarisPlatform), ("cygwin", platform._CygwinPlatform), ("msys2", platform._CygwinPlatform), From 77084537af370fe1939ef4dd1e157c53ee14e3b1 Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:21:24 -0500 Subject: [PATCH 09/11] Centralize process liveness checks in the platform API --- src/keychain/runtime/platform.py | 40 +++++++++++++--- src/keychain/state.py | 5 +- src/keychain/util.py | 27 +---------- tests/test_runtime.py | 78 +++++++++++++++++++++++++++++++- tests/test_state.py | 11 +++++ tests/test_util.py | 8 +--- 6 files changed, 126 insertions(+), 43 deletions(-) diff --git a/src/keychain/runtime/platform.py b/src/keychain/runtime/platform.py index d43a74c..46cd170 100644 --- a/src/keychain/runtime/platform.py +++ b/src/keychain/runtime/platform.py @@ -21,6 +21,7 @@ import stat import subprocess from pathlib import Path +from typing import Any, cast from ..util import KeychainError, write_atomic @@ -42,6 +43,16 @@ class Platform: def configure_ssh_confirmation(self, env: dict[str, str], keydir: Path) -> None: """Prepare a new agent's confirmation environment; normally no changes.""" + def pid_alive(self, pid: int) -> bool: + """Best-effort liveness, not proof of agent identity or permission to signal.""" + if pid <= 0: + return False + try: + os.kill(pid, 0) + except (OSError, OverflowError): + return False + return True + @property def supported(self) -> bool: """``True`` when keychain can manage agents on this host.""" @@ -187,11 +198,7 @@ def process_details_unavailable(self, pid: int) -> bool: except (FileNotFoundError, PermissionError): # hidepid can return ENOENT for a live, non-dumpable ssh-agent. # Check liveness after the read, so an exit during it is not "hidden". - try: - os.kill(pid, 0) - except (OSError, OverflowError): - return False - return True + return self.pid_alive(pid) except OSError: pass return False @@ -226,6 +233,27 @@ def __init__(self, name: str, reason: str) -> None: self.reason = reason +class _WindowsPlatform(_UnsupportedPlatform): + """Liveness for development tests; native Windows remains unsupported.""" + + def pid_alive(self, pid: int) -> bool: + if pid <= 0: + return False + import ctypes + + kernel32 = cast(Any, ctypes).windll.kernel32 + handle = kernel32.OpenProcess(0x1000, False, pid) + if not handle: + return False + try: + exit_code = ctypes.c_ulong() + if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)): + return False + return exit_code.value == 259 + finally: + kernel32.CloseHandle(handle) + + _UNSUPPORTED_WINDOWS_REASON = ( "Native Windows is not a supported keychain target: there is no " "ssh-agent process to manage in the POSIX sense, no UNIX-domain " @@ -251,7 +279,7 @@ def _classify(platform_name: str, has_ps: bool | None = None) -> Platform: # Native Windows is unsupported regardless of ps. if p == "win32": - return _UnsupportedPlatform("windows", _UNSUPPORTED_WINDOWS_REASON) + return _WindowsPlatform("windows", _UNSUPPORTED_WINDOWS_REASON) implementation: type[_PsPlatform] = _PsPlatform for prefixes, candidate in ( diff --git a/src/keychain/state.py b/src/keychain/state.py index d3af84e..1decd87 100644 --- a/src/keychain/state.py +++ b/src/keychain/state.py @@ -33,7 +33,6 @@ from .util import ( KeychainError, current_user, - pid_alive, run, ) @@ -295,7 +294,7 @@ def pidfile_pid_alive(self) -> bool: if not pid: return False pid_int = self.pidfile_env.pid_int - return bool(pid_int and pid_alive(pid_int)) + return bool(pid_int and self.platform.pid_alive(pid_int)) # ---- inherited shell environment ---------------------------------- @@ -325,7 +324,7 @@ def inherited_pid_alive(self) -> bool: if not pid: return False pid_int = self.inherited_env.pid_int - return bool(pid_int and pid_alive(pid_int)) + return bool(pid_int and self.platform.pid_alive(pid_int)) # ---- agent contents (loaded keys) --------------------------------- diff --git a/src/keychain/util.py b/src/keychain/util.py index 39f7097..5551368 100644 --- a/src/keychain/util.py +++ b/src/keychain/util.py @@ -15,7 +15,7 @@ import time from collections.abc import Iterable from pathlib import Path -from typing import TYPE_CHECKING, Any, Union, cast +from typing import TYPE_CHECKING, Any, Union if TYPE_CHECKING: from .output.core import Output @@ -185,31 +185,6 @@ def release(self) -> None: # --------------------------------------------------------------------------- -def pid_alive(pid: int) -> bool: - """Best-effort process liveness probe.""" - if pid <= 0: - return False - if os.name == "nt": - import ctypes - - kernel32 = cast(Any, ctypes).windll.kernel32 - handle = kernel32.OpenProcess(0x1000, False, pid) - if not handle: - return False - try: - exit_code = ctypes.c_ulong() - if not kernel32.GetExitCodeProcess(handle, ctypes.byref(exit_code)): - return False - return exit_code.value == 259 - finally: - kernel32.CloseHandle(handle) - try: - os.kill(pid, 0) - except OSError: - return False - return True - - def user_name(uid: int) -> str: """Display a UID as a username when available; never use this for authorization.""" if _pwd is not None: diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 2a12f60..272a7ea 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -9,11 +9,13 @@ import sys import time from types import SimpleNamespace +from unittest.mock import Mock import pytest from keychain.runtime import platform from keychain.util import KeychainError +from tests.support import set_file_stat @pytest.fixture(autouse=True) @@ -77,6 +79,59 @@ def test_detection_is_cached(): assert first is second +def test_current_process_is_alive(): + assert platform.detect().pid_alive(os.getpid()) + + +@pytest.mark.parametrize("name", ["linux", "darwin", "freebsd14", "sunos5", "cygwin", "win32"]) +@pytest.mark.parametrize("pid", [0, -1]) +def test_invalid_pids_never_probe_processes(name, pid, monkeypatch): + monkeypatch.setattr(platform.os, "kill", lambda *_a: pytest.fail("must not signal a process group")) + assert not platform._classify(name, has_ps=True).pid_alive(pid) + + +@pytest.mark.parametrize("name", ["linux", "android", "darwin", "freebsd14", "sunos5", "cygwin", "msys2"]) +def test_posix_liveness_uses_signal_zero(name, monkeypatch): + kill = Mock() + monkeypatch.setattr(platform.os, "kill", kill) + assert platform._classify(name, has_ps=True).pid_alive(123) + kill.assert_called_once_with(123, 0) + + +@pytest.mark.parametrize("error", [ProcessLookupError(), PermissionError(), OverflowError()]) +def test_liveness_failure_is_not_proof_of_a_live_process(error, monkeypatch): + monkeypatch.setattr(platform.os, "kill", Mock(side_effect=error)) + assert not platform.Platform().pid_alive(123) + + +@pytest.mark.parametrize("opened,queried,exit_code,alive", [ + (True, True, 259, True), (True, True, 0, False), + (True, False, 259, False), (False, False, 259, False), +]) +def test_windows_liveness_closes_handles(opened, queried, exit_code, alive, monkeypatch): + import ctypes + + def query(handle, code): + assert handle == 1234 + code._obj.value = exit_code + return queried + + kernel = SimpleNamespace( + OpenProcess=Mock(return_value=1234 if opened else 0), + GetExitCodeProcess=Mock(side_effect=query), CloseHandle=Mock(), + ) + monkeypatch.setattr(ctypes, "windll", SimpleNamespace(kernel32=kernel), raising=False) + p = platform._classify("win32") + assert not p.supported + assert p.pid_alive(123) is alive + kernel.OpenProcess.assert_called_once_with(0x1000, False, 123) + if opened: + kernel.CloseHandle.assert_called_once_with(1234) + else: + kernel.GetExitCodeProcess.assert_not_called() + kernel.CloseHandle.assert_not_called() + + @pytest.mark.parametrize("name", ["linux", "freebsd14", "openbsd8", "sunos5", "cygwin", "msys2"]) def test_confirmation_environment_is_unchanged_outside_macos(name, tmp_path): p = platform._classify(name, has_ps=True) @@ -97,7 +152,28 @@ def test_macos_confirmation_preserves_explicit_helper(tmp_path): assert not list(tmp_path.iterdir()) -@pytest.mark.skipif(os.name == "nt", reason="POSIX helper permissions") +@pytest.mark.parametrize("condition", ["missing", "stale", "wrong-mode", "current"]) +def test_macos_confirmation_helper_install_policy(condition, tmp_path, monkeypatch): + p = platform._classify("darwin", has_ps=True) + helper = tmp_path / "ssh-askpass-macos" + if condition != "missing": + helper.write_text("stale helper" if condition == "stale" else p._ASKPASS, encoding="utf-8") + set_file_stat(monkeypatch, helper, mode=0o100755 if condition == "wrong-mode" else 0o100700) + writer = Mock() + monkeypatch.setattr(platform, "write_atomic", writer) + env = {} + p.configure_ssh_confirmation(env, tmp_path) + if condition == "current": + writer.assert_not_called() + else: + writer.assert_called_once_with(helper, p._ASKPASS, 0o700) + assert env == {"SSH_ASKPASS": str(helper), "SSH_ASKPASS_REQUIRE": "force"} + + +@pytest.mark.skipif( + os.name == "nt" or sys.platform.startswith(("cygwin", "msys")), + reason="native POSIX permissions; MSYS2's filesystem may synthesize modes", +) def test_macos_confirmation_repairs_helper_and_avoids_rewrites(tmp_path, monkeypatch): p = platform._classify("darwin", has_ps=True) helper = tmp_path / "ssh-askpass-macos" diff --git a/tests/test_state.py b/tests/test_state.py index 66b34b1..585d0df 100644 --- a/tests/test_state.py +++ b/tests/test_state.py @@ -137,6 +137,17 @@ def test_inherited_env_empty_when_unset(paths): assert st.inherited_pid == "" +@pytest.mark.parametrize("alive", [True, False]) +def test_liveness_uses_the_selected_platform(paths, out, alive): + ref = SshAgentRef("/test.sock", "123") + paths.write(ref, out) + st = state.KeychainState(paths=paths, env=ref.as_dict()) + with patch.object(st.platform, "pid_alive", return_value=alive) as probe: + assert st.pidfile_pid_alive is alive + assert st.inherited_pid_alive is alive + assert [call.args for call in probe.call_args_list] == [(123,), (123,)] + + def test_keydir_introspection(paths): st = state.KeychainState(paths=paths) assert st.keydir_exists is True diff --git a/tests/test_util.py b/tests/test_util.py index 4f59ae8..be07caa 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -11,7 +11,7 @@ import pytest from keychain.output.core import Output -from keychain.util import KeychainError, LockFile, pid_alive +from keychain.util import KeychainError, LockFile # --------------------------------------------------------------------------- # Helpers @@ -147,9 +147,3 @@ def contend() -> bool: release.set() assert sum(future.result() for future in futures) == 1 - - -class TestPidAlive: - def test_current_process_is_reported_alive(self): - assert pid_alive(os.getpid()) is True - assert os.getpid() > 0 From 68cf9e93c4e58ec33d1e05612d22ae2e22de2e36 Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:21:28 -0500 Subject: [PATCH 10/11] Prepare Keychain 3.0.9 release --- ChangeLog.md | 15 +++++++++++++++ VERSION | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/ChangeLog.md b/ChangeLog.md index 51a88ee..7679311 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -1,5 +1,20 @@ # ChangeLog +## 3.0.9 + +Keychain 3.0.9 makes everyday shell startup faster and more dependable across operating systems, with more reliable agent discovery and tighter checks on saved state and command arguments. + +- Reduced startup overhead, particularly for commands that do not load keys. On Linux, Keychain now reads process information directly from `/proc`, avoiding the cost of launching `ps` and working without it on minimal systems such as BusyBox-based installations. +- Some Linux and Android configurations hide running SSH agents from process listings, causing Keychain to reject an otherwise usable agent. Keychain can now reuse a responding, user-owned socket when the recorded PID is alive but its details are inaccessible. `keychain inspect` explains this restriction; stopping an agent still requires verifying its process identity (#270). +- Differences in `ps` output could make existing agents go undetected. Corrected discovery on Cygwin and MSYS2, and addressed truncated process names on macOS, BSD and Solaris/illumos. Linux discovery also skips zombie processes and tolerates processes disappearing during a scan. +- A failed or unusable process listing could previously look like no agents were running. Keychain now reports a clear error instead of starting replacement agents or discarding saved references on that basis. +- The legacy `--stop mine` and `--stop all` selections were reversed. Restored their Keychain 2.x behavior: `mine` stops the agent recorded in Keychain's pidfile, while `all` stops all visible SSH agents owned by the calling user. Updated help text and diagnostics to make agent selection clearer. +- An SSH configuration containing only `Host *` could leave `--confallhosts` with no identities to load. Keychain now asks OpenSSH for those catch-all settings when there are no concrete host names, and resolves home-directory paths in the returned identities. +- A missing username entry could cause ownership and permission checks to be skipped. Keychain now checks numeric user IDs directly, so a missing account name neither bypasses checks nor rejects a directory that belongs to you. +- Invalid hostname overrides are now rejected before they can affect Keychain's file paths. Names beginning with `-` are passed to SSH and GPG tools as operands, preventing them from being interpreted as command options. + +Expanded regression coverage includes real-agent reuse on MSYS2, restricted Linux process visibility, minimal Linux environments, and native FreeBSD, OpenBSD and OmniOS tests. Platform-specific behavior is now isolated to make future fixes less likely to affect other systems. Thanks to Fumiyuki Shimizu for the Cygwin/MSYS2 fix, and @tarilka0gg for startup improvements, security fixes, review and follow-up fixes. + ## 3.0.8 This release improves reliability in less common shell setups and makes Keychain's documentation available through standard system tools. diff --git a/VERSION b/VERSION index 67786e2..747457c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -3.0.8 +3.0.9 From 6e285fc5b3c6a7b76107b9290f5db6ef8d3c839e Mon Sep 17 00:00:00 2001 From: Daniel Robbins Date: Wed, 4 Nov 2026 20:33:18 -0500 Subject: [PATCH 11/11] Credit the Cygwin/MSYS2 contribution in the 3.0.9 release notes Include the original PR number and Fumiyuki Shimizu's GitHub handle. The release branch includes the fix with additional robustness work and tests. Closes #276. --- ChangeLog.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ChangeLog.md b/ChangeLog.md index 7679311..907622c 100644 --- a/ChangeLog.md +++ b/ChangeLog.md @@ -6,14 +6,14 @@ Keychain 3.0.9 makes everyday shell startup faster and more dependable across op - Reduced startup overhead, particularly for commands that do not load keys. On Linux, Keychain now reads process information directly from `/proc`, avoiding the cost of launching `ps` and working without it on minimal systems such as BusyBox-based installations. - Some Linux and Android configurations hide running SSH agents from process listings, causing Keychain to reject an otherwise usable agent. Keychain can now reuse a responding, user-owned socket when the recorded PID is alive but its details are inaccessible. `keychain inspect` explains this restriction; stopping an agent still requires verifying its process identity (#270). -- Differences in `ps` output could make existing agents go undetected. Corrected discovery on Cygwin and MSYS2, and addressed truncated process names on macOS, BSD and Solaris/illumos. Linux discovery also skips zombie processes and tolerates processes disappearing during a scan. +- Differences in `ps` output could make existing agents go undetected. Corrected discovery on Cygwin and MSYS2 (PR #276), and addressed truncated process names on macOS, BSD and Solaris/illumos. Linux discovery also skips zombie processes and tolerates processes disappearing during a scan. - A failed or unusable process listing could previously look like no agents were running. Keychain now reports a clear error instead of starting replacement agents or discarding saved references on that basis. - The legacy `--stop mine` and `--stop all` selections were reversed. Restored their Keychain 2.x behavior: `mine` stops the agent recorded in Keychain's pidfile, while `all` stops all visible SSH agents owned by the calling user. Updated help text and diagnostics to make agent selection clearer. - An SSH configuration containing only `Host *` could leave `--confallhosts` with no identities to load. Keychain now asks OpenSSH for those catch-all settings when there are no concrete host names, and resolves home-directory paths in the returned identities. - A missing username entry could cause ownership and permission checks to be skipped. Keychain now checks numeric user IDs directly, so a missing account name neither bypasses checks nor rejects a directory that belongs to you. - Invalid hostname overrides are now rejected before they can affect Keychain's file paths. Names beginning with `-` are passed to SSH and GPG tools as operands, preventing them from being interpreted as command options. -Expanded regression coverage includes real-agent reuse on MSYS2, restricted Linux process visibility, minimal Linux environments, and native FreeBSD, OpenBSD and OmniOS tests. Platform-specific behavior is now isolated to make future fixes less likely to affect other systems. Thanks to Fumiyuki Shimizu for the Cygwin/MSYS2 fix, and @tarilka0gg for startup improvements, security fixes, review and follow-up fixes. +Expanded regression coverage includes real-agent reuse on MSYS2, restricted Linux process visibility, minimal Linux environments, and native FreeBSD, OpenBSD and OmniOS tests. Platform-specific behavior is now isolated to make future fixes less likely to affect other systems. Thanks to Fumiyuki Shimizu (@fmrns) for the Cygwin/MSYS2 fix, and @tarilka0gg for startup improvements, security fixes, review and follow-up fixes. ## 3.0.8