feat: gpgtools configure_ssh, store_publickey, --file source, initialize (v0.7.0-v0.9.0)

- configure_ssh (0.7.0): marker-managed per-host ssh client block in
  ~/.ssh/config, idempotent, unmanaged-alias guard (exit 11)
- store_publickey (0.8.0): on-site bootstrap mirror of send_pubkey -
  run on the machine access is granted to, installs the key into the
  local authorized_keys (multi-key preserving, material dedup, 700/600,
  no possession check by design); shared --file PATH source (USB
  stick) for both store subcommands; identity block printed before
  acting (line, source, SHA-256 material digest)
- initialize (0.9.0): gnupg readiness check + install, no card
  expectations; --dry-run; initialize_yubikey step 1 shares the flow
- spec-first per SPEC 6.11/6.12: gpgtools spec.md items 2.6/2.7,
  4.1.5, 4.8, sections 10-12; 91 tests in test_gpgtools.py;
  README/registry/CHANGELOG/version pins through 0.9.0

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
nvaldez
2026-11-19 08:57:30 +01:00
parent 85e8342a74
commit e9b716b399
9 changed files with 1283 additions and 74 deletions
+533 -9
View File
@@ -5,6 +5,7 @@ Pure functions, main with argument lists, and the full
initialize_yukikey flow driven by a fake runner - no hardware,
no network, no card (daedalus agent rule 5.6).
"""
import hashlib
import pathlib
import pytest
@@ -13,14 +14,14 @@ from daedalus.gpgtools import gpgtools
CARD_OK = """
Reader ...........: Yubico YubiKey OTP FIDO CCID 00 00
Application ID ...: D2760001240100000006385060530000
Application ID ...: D2760001240100000006054321090000
Application type .: OpenPGP
Version ..........: 3.4
Serial number ....: 38506053
Serial number ....: 54321098
PIN retry counter : 3 0 3
KDF setting ......: off
UIF setting ......: Sign=off Decrypt=off Auth=off
URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/A126
URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/0123
Signature key ....: F4D1 6935 15EF CB83
Encryption key....: 3DC6 203C F1EE 3F88
Authentication key: CF8B 1604 25DE B2CA
@@ -33,7 +34,7 @@ CARD_UNPAIRED = CARD_OK.replace(
)
CARD_NO_URL = CARD_UNPAIRED.replace(
"URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/A126",
"URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/0123",
"URL of public key : [not set]",
)
@@ -51,9 +52,9 @@ def test_parse_card_status_reads_present_card():
"""A healthy card-status output yields serial, auth key, and URL."""
info = gpgtools.parse_card_status(CARD_OK)
assert info.present is True
assert info.serial == "38506053"
assert info.serial == "54321098"
assert info.has_auth_subkey is True
assert info.key_url == "https://keys.openpgp.org/vks/v1/by-fingerprint/A126"
assert info.key_url == "https://keys.openpgp.org/vks/v1/by-fingerprint/0123"
assert info.keyring_paired is True
@@ -208,7 +209,7 @@ def test_initialize_happy_path(tmp_path, happy_runner):
assert oct(home.stat().st_mode)[-3:] == "700"
fetched = [cmd for cmd in happy_runner.calls if cmd[:2] == ["gpg", "--fetch-keys"]]
assert fetched == [["gpg", "--fetch-keys",
"https://keys.openpgp.org/vks/v1/by-fingerprint/A126"]]
"https://keys.openpgp.org/vks/v1/by-fingerprint/0123"]]
killed = [cmd for cmd in happy_runner.calls if cmd[:2] == ["gpgconf", "--kill"]]
assert killed == [["gpgconf", "--kill", "gpg-agent"]]
@@ -313,7 +314,7 @@ def test_main_help_exits_zero():
# --- send_pubkey: validation, sources, verification, sending
FP = "A126B97CB5A18E923DE2A4FF23B8D25BC4A17EAB"
FP = "0123456789ABCDEF0123456789ABCDEF01234567"
GOOD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEXAMPLEBASE64KEY daedalus-test"
OTHER_KEY = "ssh-rsa AAAAB3NzaC1yc2E someone-else"
CANDIDATE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICANDIDATEKEY candidate"
@@ -349,7 +350,7 @@ def test_validate_pubkey_line():
def test_normalize_fingerprint():
"""Fingerprints normalize: lower, spaced, 0x-prefixed all work."""
spaced = "a126 b97c b5a1 8e92 3de2 a4ff 23b8 d25b c4a1 7eab"
spaced = "0123 4567 89ab cdef 0123 4567 89ab cdef 0123 4567"
assert gpgtools.normalize_fingerprint(spaced) == FP
assert gpgtools.normalize_fingerprint("0x" + FP.lower()) == FP
assert gpgtools.normalize_fingerprint(FP) == FP
@@ -686,3 +687,526 @@ def test_cmd_send_pubkey_blocked_by_verification(tmp_path, capsys):
assert code == gpgtools.EXIT_VERIFY_FAILED
assert not any(cmd and cmd[0] == "ssh" for cmd in calls)
assert "no private key" in capsys.readouterr().out
# --- --file source (gpgtools spec item 4.1.5) and the 4.8 output
def test_source_file_reads_the_key_line(tmp_path):
"""--file yields the key line from a carried .pub file."""
path = tmp_path / "yubikey_auth.pub"
path.write_text(GOOD_KEY + "\n", encoding="utf-8")
line, source = gpgtools.source_file(path)
assert line == GOOD_KEY
assert str(path) in source
def test_source_file_missing(tmp_path):
"""A missing key file is a source error naming the file."""
with pytest.raises(gpgtools.SendPubkeyError) as err:
gpgtools.source_file(tmp_path / "nope.pub")
assert "nope.pub" in str(err.value)
def test_source_file_without_any_key(tmp_path):
"""A file with no valid key line is refused."""
path = tmp_path / "notes.txt"
path.write_text("just some text\n", encoding="utf-8")
with pytest.raises(gpgtools.SendPubkeyError):
gpgtools.source_file(path)
def test_source_file_several_keys_refuses(tmp_path):
"""Several keys refuse with the list and the --pubkey hint."""
path = tmp_path / "keys.pub"
path.write_text(GOOD_KEY + "\n" + OTHER_KEY + "\n", encoding="utf-8")
with pytest.raises(gpgtools.SendPubkeyError) as err:
gpgtools.source_file(path)
assert "--pubkey" in str(err.value)
assert GOOD_KEY in str(err.value)
def test_material_digest_ignores_comments():
"""The SHA-256 material digest is identity, comments are not."""
digest = hashlib.sha256(
" ".join(GOOD_KEY.split()[:2]).encode()).hexdigest()
assert gpgtools.material_digest(GOOD_KEY) == digest
renamed = GOOD_KEY.replace("daedalus-test", "cardno:12_345_678")
assert gpgtools.material_digest(renamed) == digest
def test_cmd_send_pubkey_prints_identity_block(tmp_path, capsys):
"""Send prints the line, source, and material digest (4.8)."""
digest = hashlib.sha256(
" ".join(GOOD_KEY.split()[:2]).encode()).hexdigest()
path = tmp_path / "yubikey_auth.pub"
path.write_text(GOOD_KEY + "\n", encoding="utf-8")
args = gpgtools.parse_args(["send_pubkey", "--file", str(path),
"--dry-run", "you@server"])
calls = []
runner = make_runner({}, calls)
assert gpgtools.cmd_send_pubkey(args, runner,
lambda _u: b"") == gpgtools.EXIT_OK
out = capsys.readouterr().out
assert GOOD_KEY in out
assert str(path) in out
assert digest in out
assert calls == [] # a file source needs no command at all
# --- store_publickey (gpgtools spec section 11)
def test_store_key_appends_and_enforces_perms(tmp_path):
"""A fresh authorized_keys gets the line, dir 700, file 600."""
target = tmp_path / "ssh" / "authorized_keys"
assert gpgtools.store_key(GOOD_KEY, target) is True
assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n"
assert oct(target.parent.stat().st_mode)[-3:] == "700"
assert oct(target.stat().st_mode)[-3:] == "600"
def test_store_key_preserves_existing_entries(tmp_path):
"""Other keys in the file stay untouched (multi-key file)."""
target = tmp_path / "authorized_keys"
target.write_text(OTHER_KEY + "\n", encoding="utf-8")
assert gpgtools.store_key(GOOD_KEY, target) is True
content = target.read_text(encoding="utf-8")
assert content == OTHER_KEY + "\n" + GOOD_KEY + "\n"
def test_store_key_repairs_missing_newline(tmp_path):
"""A file without a trailing newline never glues two keys."""
target = tmp_path / "authorized_keys"
target.write_text(OTHER_KEY, encoding="utf-8")
assert gpgtools.store_key(GOOD_KEY, target) is True
content = target.read_text(encoding="utf-8")
assert content == OTHER_KEY + "\n" + GOOD_KEY + "\n"
def test_store_key_idempotent_by_material(tmp_path):
"""Same material with another comment is already present."""
target = tmp_path / "authorized_keys"
target.write_text(GOOD_KEY.replace("daedalus-test", "cardno:12_345_678")
+ "\n", encoding="utf-8")
before = target.read_text(encoding="utf-8")
assert gpgtools.store_key(GOOD_KEY, target) is False
assert target.read_text(encoding="utf-8") == before
def test_cmd_store_publickey_full_flow(tmp_path, capsys):
"""--pubkey resolves, prints the identity block, appends."""
digest = hashlib.sha256(
" ".join(GOOD_KEY.split()[:2]).encode()).hexdigest()
target = tmp_path / "ssh" / "authorized_keys"
calls = []
runner = make_runner({}, calls)
args = gpgtools.parse_args(["store_publickey", "--pubkey", GOOD_KEY,
"--authorized-keys", str(target)])
assert gpgtools.cmd_store_publickey(args, runner,
None) == gpgtools.EXIT_OK
out = capsys.readouterr().out
assert GOOD_KEY in out
assert digest in out
assert str(target) in out
assert "appended" in out
assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n"
assert calls == [] # store never runs a command (spec 11.8)
def test_cmd_store_publickey_already_present(tmp_path, capsys):
"""Present material is reported; the file is not touched."""
target = tmp_path / "authorized_keys"
target.write_text(GOOD_KEY + "\n", encoding="utf-8")
args = gpgtools.parse_args(["store_publickey", "--pubkey", GOOD_KEY,
"--authorized-keys", str(target)])
assert gpgtools.cmd_store_publickey(
args, make_runner({}), None) == gpgtools.EXIT_OK
assert "already present" in capsys.readouterr().out
assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n"
def test_cmd_store_publickey_dry_run(tmp_path, capsys):
"""--dry-run prints creating and writes nothing."""
target = tmp_path / "ssh" / "authorized_keys"
args = gpgtools.parse_args(["store_publickey", "--pubkey", GOOD_KEY,
"--authorized-keys", str(target),
"--dry-run"])
assert gpgtools.cmd_store_publickey(
args, make_runner({}), None) == gpgtools.EXIT_OK
out = capsys.readouterr().out
assert GOOD_KEY in out
assert "creating" in out
assert not target.parent.exists()
def test_cmd_store_publickey_invalid_line_is_exit_8(tmp_path, capsys):
"""A garbage line is refused before any write."""
target = tmp_path / "authorized_keys"
args = gpgtools.parse_args(["store_publickey", "--pubkey", "garbage",
"--authorized-keys", str(target)])
assert gpgtools.cmd_store_publickey(
args, make_runner({}), None) == gpgtools.EXIT_NO_KEY
assert not target.exists()
def test_cmd_store_publickey_fingerprint_source(tmp_path):
"""A remote source resolves through the injected runner/fetch."""
target = tmp_path / "authorized_keys"
def fake_gpg(cmd, input_text="", env=None):
if cmd == ["gpg", "--export-ssh-key", "0x" + FP]:
return (0, GOOD_KEY + "\n")
raise AssertionError(f"unexpected {cmd}")
args = gpgtools.parse_args(["store_publickey", "--fingerprint", FP,
"--authorized-keys", str(target)])
assert gpgtools.cmd_store_publickey(
args, fake_gpg, lambda _u: b"") == gpgtools.EXIT_OK
assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n"
def test_cmd_store_publickey_file_source(tmp_path):
"""A --file source stores without network or runner commands."""
path = tmp_path / "yubikey_auth.pub"
path.write_text(GOOD_KEY + "\n", encoding="utf-8")
target = tmp_path / "authorized_keys"
args = gpgtools.parse_args(["store_publickey", "--file", str(path),
"--authorized-keys", str(target)])
assert gpgtools.cmd_store_publickey(
args, make_runner({}), None) == gpgtools.EXIT_OK
assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n"
def test_cmd_store_publickey_no_source_is_exit_8(tmp_path, capsys):
"""A source that cannot resolve is exit 8 (spec 11.2)."""
target = tmp_path / "authorized_keys"
args = gpgtools.parse_args(["store_publickey", "--fingerprint", FP,
"--authorized-keys", str(target)])
def fake_gpg(cmd, input_text="", env=None):
return (1, "not found\n")
assert gpgtools.cmd_store_publickey(
args, fake_gpg, lambda _u: None) == gpgtools.EXIT_NO_KEY
assert not target.exists()
def test_cli_store_publickey_wires_flow(monkeypatch):
"""The CLI dispatches store_publickey with runner and fetcher."""
seen = {}
def fake_store(args, run_cmd, fetch):
seen["args"] = args
seen["runner"] = run_cmd
return gpgtools.EXIT_OK
monkeypatch.setattr(gpgtools, "cmd_store_publickey", fake_store)
code = gpgtools.main(["store_publickey", "--pubkey", GOOD_KEY])
assert code == 0
assert seen["args"].pubkey == GOOD_KEY
assert seen["runner"] is gpgtools.run_command
def test_cli_store_publickey_requires_source():
"""No source flag is a usage error, like send_pubkey."""
with pytest.raises(SystemExit) as exc:
gpgtools.main(["store_publickey"])
assert exc.value.code == 2
# --- initialize: gnupg readiness and install (gpgtools spec 12)
def test_ensure_gnupg_already_ready():
"""A working gpg means ready: no install command is run."""
calls = []
runner = make_runner({("gpg", "--version"):
(0, "gpg (GnuPG) 2.4.7\n")}, calls)
assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_OK
assert not any(cmd[:1] == ["sudo"] for cmd in calls)
def test_ensure_gnupg_installs_when_missing(monkeypatch):
"""Missing gpg: install via the detected manager, then re-check."""
monkeypatch.setattr(gpgtools.shutil, "which",
lambda name: "/usr/bin/apt-get"
if name == "apt-get" else None)
calls = []
state = {"ready": False}
def runner(cmd, input_text="", env=None):
calls.append(list(cmd))
if cmd == ["gpg", "--version"]:
if state["ready"]:
return (0, "gpg (GnuPG) 2.4.7\n")
return (1, "not found")
if cmd[:2] == ["sudo", "apt-get"]:
state["ready"] = True
return (0, "installed\n")
raise AssertionError(f"unexpected command: {cmd}")
assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_OK
assert ["sudo", "apt-get", "install", "-y", "gnupg"] in calls
checks = [cmd for cmd in calls if cmd == ["gpg", "--version"]]
assert len(checks) == 2 # initial check + post-install re-check
def test_ensure_gnupg_no_known_manager(monkeypatch, caplog):
"""Missing gpg with no known manager stops with exit 3."""
monkeypatch.setattr(gpgtools.shutil, "which", lambda _name: None)
runner = make_runner({("gpg", "--version"): (1, "not found")})
assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_NO_GPG
assert "manually" in caplog.text
def test_ensure_gnupg_install_fails(monkeypatch):
"""A failed package install is exit 2."""
monkeypatch.setattr(gpgtools.shutil, "which",
lambda name: "/usr/bin/dnf" if name == "dnf" else None)
runner = make_runner({
("gpg", "--version"): (1, "not found"),
("sudo", "dnf"): (1, "no network\n"),
})
assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_INSTALL_FAILED
def test_ensure_gnupg_still_broken_after_install(monkeypatch):
"""Installed but still unusable re-checks once, then exit 2."""
monkeypatch.setattr(gpgtools.shutil, "which",
lambda name: "/usr/bin/apt-get"
if name == "apt-get" else None)
calls = []
def runner(cmd, input_text="", env=None):
calls.append(list(cmd))
if cmd == ["gpg", "--version"]:
return (1, "still broken\n")
if cmd[:2] == ["sudo", "apt-get"]:
return (0, "installed\n")
raise AssertionError(f"unexpected command: {cmd}")
assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_INSTALL_FAILED
assert len([cmd for cmd in calls if cmd == ["gpg", "--version"]]) == 2
def test_main_initialize_dry_run_ready(monkeypatch, capsys):
"""Dry run with gpg present prints ready and installs nothing."""
calls = []
runner = make_runner({("gpg", "--version"):
(0, "gpg (GnuPG) 2.4.7\n")}, calls)
monkeypatch.setattr(gpgtools, "run_command", runner)
assert gpgtools.main(["initialize", "--dry-run"]) == 0
out = capsys.readouterr().out
assert "dry run" in out
assert "2.4.7" in out
assert not any(cmd[:1] == ["sudo"] for cmd in calls)
def test_main_initialize_dry_run_missing_prints_plan(monkeypatch, capsys):
"""Dry run with gpg missing prints the install command, runs none."""
monkeypatch.setattr(gpgtools.shutil, "which",
lambda name: "/usr/bin/apt-get"
if name == "apt-get" else None)
calls = []
runner = make_runner({("gpg", "--version"): (1, "not found")}, calls)
monkeypatch.setattr(gpgtools, "run_command", runner)
assert gpgtools.main(["initialize", "--dry-run"]) == 0
out = capsys.readouterr().out
assert "apt-get install -y gnupg" in out
assert not any(cmd[:1] == ["sudo"] for cmd in calls)
def test_main_initialize_wires_flow(monkeypatch):
"""The CLI dispatches initialize to ensure_gnupg with the runner."""
seen = {}
def fake_ensure(run_cmd):
seen["runner"] = run_cmd
return gpgtools.EXIT_OK
monkeypatch.setattr(gpgtools, "ensure_gnupg", fake_ensure)
assert gpgtools.main(["initialize"]) == 0
assert seen["runner"] is gpgtools.run_command
# --- configure_ssh: block building, merge, guards, file writes
SAIKA_BLOCK = (
"# BEGIN daedalus gpgtools: vault1\n"
"Host vault1\n"
" HostName 203.0.113.10\n"
" User admin\n"
" IdentityFile /pub/yubikey_auth.pub\n"
" IdentityFile /pub/id_ed25519\n"
" IdentitiesOnly yes\n"
"# END daedalus gpgtools: vault1\n")
def test_build_block_full():
"""The managed block renders exactly, markers included."""
block = gpgtools.build_block(alias="vault1",
hostname="203.0.113.10",
user="admin",
pubkey="/pub/yubikey_auth.pub",
fallback="/pub/id_ed25519")
assert block == SAIKA_BLOCK
def test_build_block_minimal():
"""Without user and fallback the lines are omitted."""
block = gpgtools.build_block(alias="host1", hostname="host1",
user=None,
pubkey="/pub/yubikey_auth.pub",
fallback=None)
assert "User " not in block
assert "id_ed25519" not in block
assert "Host host1\n" in block
assert "IdentitiesOnly yes\n" in block
def test_merge_into_empty_config():
"""An empty config receives the block."""
merged = gpgtools.merge_managed_block("", "vault1", SAIKA_BLOCK)
assert merged == SAIKA_BLOCK
def test_merge_replaces_managed_block_only():
"""A marked block is replaced; surrounding config survives."""
existing = ("Host other\n"
" HostName 10.0.0.1\n\n" + SAIKA_BLOCK +
"\nHost third\n HostName 10.0.0.2\n")
new_block = SAIKA_BLOCK.replace("HostName 203.0.113.10",
"HostName 198.51.100.5")
merged = gpgtools.merge_managed_block(existing, "vault1",
new_block)
assert "HostName 198.51.100.5" in merged
assert "203.0.113.10" not in merged
assert merged.startswith("Host other\n HostName 10.0.0.1\n\n")
assert merged.endswith("Host third\n HostName 10.0.0.2\n")
assert merged.count("# BEGIN daedalus gpgtools: vault1") == 1
def test_unmanaged_alias_detection():
"""A Host line naming the alias outside the markers conflicts."""
managed = SAIKA_BLOCK
assert gpgtools.unmanaged_alias_exists(managed, "vault1") is False
assert gpgtools.unmanaged_alias_exists(
SAIKA_BLOCK + "\nHost vault1\n HostName x\n",
"vault1") is True
assert gpgtools.unmanaged_alias_exists(
"Host other vault1\n HostName x\n",
"vault1") is True
def test_cmd_configure_ssh_creates_config(tmp_path):
"""A full run creates the ssh dir and config with the block."""
ssh_dir = tmp_path / "ssh"
pubkey = tmp_path / "yubikey_auth.pub"
pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8")
fallback = tmp_path / "id_ed25519"
fallback.write_text("secret", encoding="utf-8")
args = gpgtools.parse_args([
"configure_ssh", "--alias", "vault1",
"--hostname", "203.0.113.10", "--user", "admin",
"--pubkey", str(pubkey), "--fallback", str(fallback),
"--config", str(ssh_dir / "config")])
assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_OK
config = (ssh_dir / "config").read_text(encoding="utf-8")
assert config == SAIKA_BLOCK.replace(
"IdentityFile /pub/yubikey_auth.pub",
f"IdentityFile {pubkey}").replace(
"IdentityFile /pub/id_ed25519",
f"IdentityFile {fallback}")
assert oct(ssh_dir.stat().st_mode)[-3:] == "700"
assert oct((ssh_dir / "config").stat().st_mode)[-3:] == "600"
def test_cmd_configure_ssh_idempotent(tmp_path):
"""Running twice with the same args leaves the file unchanged."""
pubkey = tmp_path / "yubikey_auth.pub"
pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8")
config = tmp_path / "config"
argv = ["configure_ssh", "--alias", "h1", "--pubkey", str(pubkey),
"--config", str(config)]
first = gpgtools.cmd_configure_ssh(gpgtools.parse_args(argv))
content = config.read_text(encoding="utf-8")
assert first == gpgtools.EXIT_OK
assert gpgtools.cmd_configure_ssh(
gpgtools.parse_args(argv)) == gpgtools.EXIT_OK
assert config.read_text(encoding="utf-8") == content
assert content.count("# BEGIN daedalus gpgtools: h1") == 1
def test_cmd_configure_ssh_missing_pubkey(tmp_path):
"""A missing pubkey file is exit 8 with the derive hint."""
args = gpgtools.parse_args([
"configure_ssh", "--alias", "h1",
"--pubkey", str(tmp_path / "nope.pub"),
"--config", str(tmp_path / "config")])
assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_NO_KEY
assert not (tmp_path / "config").exists()
def test_cmd_configure_ssh_alias_conflict(tmp_path):
"""An unmanaged Host with the same alias refuses (exit 11)."""
pubkey = tmp_path / "yubikey_auth.pub"
pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8")
config = tmp_path / "config"
config.write_text("Host h1\n HostName 10.0.0.9\n",
encoding="utf-8")
args = gpgtools.parse_args([
"configure_ssh", "--alias", "h1", "--pubkey", str(pubkey),
"--config", str(config)])
assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_ALIAS_CONFLICT
assert config.read_text(encoding="utf-8") == "Host h1\n HostName 10.0.0.9\n"
def test_cmd_configure_ssh_missing_fallback_omitted(tmp_path, caplog):
"""A nonexistent default fallback is omitted without error."""
pubkey = tmp_path / "yubikey_auth.pub"
pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8")
args = gpgtools.parse_args([
"configure_ssh", "--alias", "h1", "--pubkey", str(pubkey),
"--fallback", str(tmp_path / "missing_key"),
"--config", str(tmp_path / "config")])
assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_OK
content = (tmp_path / "config").read_text(encoding="utf-8")
assert "missing_key" not in content
def test_cmd_configure_ssh_dry_run(tmp_path, capsys):
"""--dry-run prints the block and writes nothing."""
pubkey = tmp_path / "yubikey_auth.pub"
pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8")
config = tmp_path / "config"
args = gpgtools.parse_args([
"configure_ssh", "--alias", "h1", "--pubkey", str(pubkey),
"--config", str(config), "--dry-run"])
assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_OK
out = capsys.readouterr().out
assert "Host h1" in out
assert not config.exists()
def test_cli_configure_ssh_wires_flow(monkeypatch):
"""The CLI dispatches configure_ssh to cmd_configure_ssh."""
seen = {}
def fake_cmd(args):
seen["args"] = args
return gpgtools.EXIT_OK
monkeypatch.setattr(gpgtools, "cmd_configure_ssh", fake_cmd)
code = gpgtools.main(["configure_ssh", "--alias", "h1",
"--hostname", "198.51.100.5"])
assert code == 0
assert seen["args"].alias == "h1"
assert seen["args"].hostname == "198.51.100.5"
def test_cli_configure_ssh_requires_alias():
"""--alias is required."""
with pytest.raises(SystemExit) as exc:
gpgtools.main(["configure_ssh"])
assert exc.value.code == 2