Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 115 additions & 2 deletions .github/workflows/python-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand All @@ -93,6 +93,103 @@ 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

# 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.
#
Expand Down Expand Up @@ -174,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 }}
Expand All @@ -199,12 +296,20 @@ jobs:
needs:
- static-analysis
- test-fast
- test-msys2
- test-freebsd
- test-openbsd
- test-omnios
- 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_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: >-
Expand All @@ -219,6 +324,10 @@ jobs:
run: |
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})"

Expand All @@ -227,6 +336,10 @@ jobs:
for result in \
"${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
Expand Down
15 changes: 15 additions & 0 deletions ChangeLog.md
Original file line number Diff line number Diff line change
@@ -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 (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 (@fmrns) 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.
Expand Down
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.0.8
3.0.9
26 changes: 14 additions & 12 deletions man/embedded-docs.txt
Original file line number Diff line number Diff line change
Expand Up @@ -97,19 +97,19 @@ See also: `topic:extkeys`, `topic:coordination`.

@syntax keychain agent <start|stop> [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)

@syntax keychain agent start [OPTIONS]

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.

Expand Down Expand Up @@ -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

Expand All @@ -319,17 +321,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

Expand Down
51 changes: 51 additions & 0 deletions scripts/test_posix_vm.py
Original file line number Diff line number Diff line change
@@ -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())
8 changes: 5 additions & 3 deletions src/keychain/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__"]

Expand All @@ -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):
Expand All @@ -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:
Expand Down
Loading
Loading