feat: gpgtools - YubiKey GPG/SSH helpers (v0.6.0)
initialize_yubikey (guide steps 1-4): gnupg install fallback (apt-get/dnf/pacman), card check, public-key fetch from the card's URL field, idempotent gpg-agent SSH config merge, GNUPGHOME chmod 700; --dry-run, --gnupg-home. send_pubkey (guide steps 5-6): resolve the SSH public key from four sources (--yubikey via gpg-agent ssh socket, --url, --fingerprint via store chain local keyring -> keys.openpgp.org -> keyserver.ubuntu.com with fingerprint checking, --pubkey literal), prove possession of the private half with a random challenge signature (ssh-keygen -Y sign -U / verify) before anything is stored, then append idempotently to the target's authorized_keys (dedup by key material, comments ignored). --no-verify opts out explicitly; --dry-run resolves only. 51 tests (flow via injected runner: no hardware, network, or interactive terminal); steps 1-6 of the wiki guide (yubikey-ssh-guide.md) are now one command each. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
@@ -0,0 +1,688 @@
|
||||
"""Tests for gpgtools: card parsing, agent config merge, and the
|
||||
initialize_yubikey flow with an injected command runner.
|
||||
|
||||
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 pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
from daedalus.gpgtools import gpgtools
|
||||
|
||||
CARD_OK = """
|
||||
Reader ...........: Yubico YubiKey OTP FIDO CCID 00 00
|
||||
Application ID ...: D2760001240100000006385060530000
|
||||
Application type .: OpenPGP
|
||||
Version ..........: 3.4
|
||||
Serial number ....: 38506053
|
||||
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
|
||||
Signature key ....: F4D1 6935 15EF CB83
|
||||
Encryption key....: 3DC6 203C F1EE 3F88
|
||||
Authentication key: CF8B 1604 25DE B2CA
|
||||
General key info..: sub ed25519/2B3B632C
|
||||
"""
|
||||
|
||||
CARD_UNPAIRED = CARD_OK.replace(
|
||||
"General key info..: sub ed25519/2B3B632C",
|
||||
"General key info..: [none]",
|
||||
)
|
||||
|
||||
CARD_NO_URL = CARD_UNPAIRED.replace(
|
||||
"URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/A126",
|
||||
"URL of public key : [not set]",
|
||||
)
|
||||
|
||||
CARD_NO_AUTH = "\n".join(
|
||||
line for line in CARD_OK.splitlines() if not line.startswith("Authentication key")
|
||||
)
|
||||
|
||||
CARD_MISSING = "gpg: selecting OpenPGP failed: No such device\n"
|
||||
|
||||
|
||||
# --- parse_card_status
|
||||
|
||||
|
||||
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.has_auth_subkey is True
|
||||
assert info.key_url == "https://keys.openpgp.org/vks/v1/by-fingerprint/A126"
|
||||
assert info.keyring_paired is True
|
||||
|
||||
|
||||
def test_parse_card_status_without_card():
|
||||
"""gpg's 'no card' stderr parses to an absent card."""
|
||||
info = gpgtools.parse_card_status(CARD_MISSING)
|
||||
assert info.present is False
|
||||
assert info.serial is None
|
||||
assert info.key_url is None
|
||||
|
||||
|
||||
def test_parse_card_status_empty_output():
|
||||
"""No output at all is an absent card, not a crash."""
|
||||
assert gpgtools.parse_card_status("").present is False
|
||||
|
||||
|
||||
def test_parse_card_status_url_not_set():
|
||||
"""'[not set]' URL parses to None, the card stays present."""
|
||||
info = gpgtools.parse_card_status(CARD_NO_URL)
|
||||
assert info.present is True
|
||||
assert info.key_url is None
|
||||
|
||||
|
||||
def test_parse_card_status_without_auth_subkey():
|
||||
"""A card without an authentication key is reported as such."""
|
||||
assert gpgtools.parse_card_status(CARD_NO_AUTH).has_auth_subkey is False
|
||||
|
||||
|
||||
def test_parse_card_status_unpaired_keyring():
|
||||
"""A fresh machine without the public key shows an unpaired card."""
|
||||
assert gpgtools.parse_card_status(CARD_UNPAIRED).keyring_paired is False
|
||||
|
||||
|
||||
# --- merge_agent_config
|
||||
|
||||
|
||||
def test_merge_agent_config_from_empty():
|
||||
"""An empty config gets the three required lines."""
|
||||
merged = gpgtools.merge_agent_config("")
|
||||
assert merged == ("enable-ssh-support\n"
|
||||
"default-cache-ttl 600\n"
|
||||
"max-cache-ttl 7200\n")
|
||||
|
||||
|
||||
def test_merge_agent_config_preserves_and_dedupes():
|
||||
"""Existing lines stay, required lines are added once."""
|
||||
existing = "default-cache-ttl 300\nextra-option 1\n"
|
||||
merged = gpgtools.merge_agent_config(existing)
|
||||
assert "extra-option 1" in merged
|
||||
assert "default-cache-ttl 300" in merged
|
||||
assert "enable-ssh-support" in merged
|
||||
assert "max-cache-ttl 7200" in merged
|
||||
assert merged.count("default-cache-ttl") == 1
|
||||
assert merged.endswith("\n")
|
||||
|
||||
|
||||
def test_merge_agent_config_already_complete():
|
||||
"""A config that already has everything is returned unchanged."""
|
||||
complete = "enable-ssh-support\ndefault-cache-ttl 600\nmax-cache-ttl 7200\n"
|
||||
assert gpgtools.merge_agent_config(complete) == complete
|
||||
|
||||
|
||||
# --- package manager mapping
|
||||
|
||||
|
||||
def test_install_command_for_each_manager():
|
||||
"""apt, dnf, and pacman map to their install commands."""
|
||||
assert gpgtools.install_command("apt-get") == \
|
||||
["sudo", "apt-get", "install", "-y", "gnupg"]
|
||||
assert gpgtools.install_command("dnf") == \
|
||||
["sudo", "dnf", "install", "-y", "gnupg2"]
|
||||
assert gpgtools.install_command("pacman") == \
|
||||
["sudo", "pacman", "--noconfirm", "-S", "gnupg"]
|
||||
|
||||
|
||||
def test_install_command_unknown_manager():
|
||||
"""An unknown manager has no command."""
|
||||
assert gpgtools.install_command("brew") is None
|
||||
|
||||
|
||||
def test_detect_package_manager(monkeypatch):
|
||||
"""The first known manager on PATH wins."""
|
||||
monkeypatch.setattr(gpgtools.shutil, "which",
|
||||
lambda name: "/usr/bin/" + name if name == "dnf" else None)
|
||||
assert gpgtools.detect_package_manager() == "dnf"
|
||||
|
||||
|
||||
def test_detect_package_manager_none(monkeypatch):
|
||||
"""No known manager means no install possible."""
|
||||
monkeypatch.setattr(gpgtools.shutil, "which", lambda _name: None)
|
||||
assert gpgtools.detect_package_manager() is None
|
||||
|
||||
|
||||
# --- gnupg_home
|
||||
|
||||
|
||||
def test_gnupg_home_default(monkeypatch):
|
||||
"""Without GNUPGHOME the default is ~/.gnupg."""
|
||||
monkeypatch.delenv("GNUPGHOME", raising=False)
|
||||
assert gpgtools.gnupg_home() == pathlib.Path.home() / ".gnupg"
|
||||
|
||||
|
||||
def test_gnupg_home_env_override(monkeypatch, tmp_path):
|
||||
"""GNUPGHOME (or --gnupg-home) relocates every write."""
|
||||
monkeypatch.setenv("GNUPGHOME", str(tmp_path))
|
||||
assert gpgtools.gnupg_home() == tmp_path
|
||||
|
||||
|
||||
# --- initialize_yubikey flow (injected runner: no hardware, no network)
|
||||
|
||||
|
||||
class FakeRunner:
|
||||
"""Replies to known commands with scripted output and code."""
|
||||
|
||||
def __init__(self, card_before, card_after, gpg_missing=False):
|
||||
self._card_before = card_before
|
||||
self._card_after = card_after
|
||||
self._gpg_missing = gpg_missing
|
||||
self.calls: list[list[str]] = []
|
||||
|
||||
def __call__(self, cmd):
|
||||
self.calls.append(list(cmd))
|
||||
if cmd[:2] == ["gpg", "--version"]:
|
||||
if self._gpg_missing:
|
||||
return 1, "command not found"
|
||||
return 0, "gpg (GnuPG) 2.4.7\n"
|
||||
if cmd == ["gpg", "--card-status"]:
|
||||
return (0, self._card_after) if self._paired else (0, self._card_before)
|
||||
if cmd[:2] == ["gpg", "--fetch-keys"]:
|
||||
self._paired = True
|
||||
return 0, "imported\n"
|
||||
if cmd[:2] == ["gpgconf", "--kill"]:
|
||||
return 0, ""
|
||||
raise AssertionError(f"unexpected command: {cmd}")
|
||||
|
||||
|
||||
@pytest.fixture(name="happy_runner")
|
||||
def fixture_happy_runner():
|
||||
"""Runner that simulates a present card, a URL, and pairing."""
|
||||
runner = FakeRunner(CARD_UNPAIRED, CARD_OK)
|
||||
runner._paired = False
|
||||
return runner
|
||||
|
||||
|
||||
def test_initialize_happy_path(tmp_path, happy_runner):
|
||||
"""Steps 1-4 complete: card, fetch, config write, agent restart."""
|
||||
home = tmp_path / "gnupg"
|
||||
code = gpgtools.initialize_yubikey(home=home, run_cmd=happy_runner)
|
||||
assert code == 0
|
||||
config = (home / "gpg-agent.conf").read_text(encoding="utf-8")
|
||||
assert "enable-ssh-support" in config
|
||||
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"]]
|
||||
killed = [cmd for cmd in happy_runner.calls if cmd[:2] == ["gpgconf", "--kill"]]
|
||||
assert killed == [["gpgconf", "--kill", "gpg-agent"]]
|
||||
|
||||
|
||||
def test_initialize_preserves_existing_config(tmp_path, happy_runner):
|
||||
"""An existing gpg-agent.conf keeps its lines."""
|
||||
home = tmp_path / "gnupg"
|
||||
home.mkdir()
|
||||
(home / "gpg-agent.conf").write_text("extra-option 1\n", encoding="utf-8")
|
||||
assert gpgtools.initialize_yubikey(home=home, run_cmd=happy_runner) == 0
|
||||
assert "extra-option 1" in (home / "gpg-agent.conf").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_initialize_card_absent(tmp_path):
|
||||
"""No card terminates with the 'card' exit code."""
|
||||
runner = FakeRunner(CARD_MISSING, CARD_OK)
|
||||
runner._paired = False
|
||||
code = gpgtools.initialize_yubikey(home=tmp_path / "gnupg", run_cmd=runner)
|
||||
assert code == 4
|
||||
|
||||
|
||||
def test_initialize_without_gpg_and_no_manager(tmp_path, monkeypatch):
|
||||
"""Missing gpg with no installable manager stops with the 'install' code."""
|
||||
monkeypatch.setattr(gpgtools.shutil, "which", lambda _name: None)
|
||||
runner = FakeRunner(CARD_OK, CARD_OK, gpg_missing=True)
|
||||
code = gpgtools.initialize_yubikey(home=tmp_path / "gnupg", run_cmd=runner)
|
||||
assert code == 3
|
||||
|
||||
|
||||
def test_initialize_without_url(tmp_path):
|
||||
"""A card without a URL stops with the 'url missing' code."""
|
||||
runner = FakeRunner(CARD_NO_URL, CARD_NO_URL)
|
||||
runner._paired = True
|
||||
code = gpgtools.initialize_yubikey(home=tmp_path / "gnupg", run_cmd=runner)
|
||||
assert code == 6
|
||||
|
||||
|
||||
def test_initialize_without_auth_subkey_warns_but_configures(tmp_path, caplog):
|
||||
"""Without an [A] subkey the machine still gets a working gpg setup."""
|
||||
runner = FakeRunner(CARD_NO_AUTH, CARD_NO_AUTH)
|
||||
runner._paired = True
|
||||
code = gpgtools.initialize_yubikey(home=tmp_path / "gnupg", run_cmd=runner)
|
||||
assert code == 0
|
||||
assert (tmp_path / "gnupg" / "gpg-agent.conf").exists()
|
||||
|
||||
|
||||
def test_run_command_success():
|
||||
"""run_command returns the exit code and combined output."""
|
||||
code, output = gpgtools.run_command(["true"])
|
||||
assert code == 0
|
||||
assert output == ""
|
||||
|
||||
|
||||
def test_run_command_missing_binary():
|
||||
"""A missing binary reports 127 with a message instead of crashing."""
|
||||
code, output = gpgtools.run_command(["daedalus-no-such-binary-xyz"])
|
||||
assert code == 127
|
||||
assert "not found" in output
|
||||
|
||||
|
||||
# --- CLI
|
||||
|
||||
|
||||
def test_main_requires_no_subcommand(capsys):
|
||||
"""Bare `daedalus gpgtools` prints the overview and exits 0."""
|
||||
assert gpgtools.main([]) == 0
|
||||
assert "initialize_yubikey" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_main_initialize_dry_run(tmp_path, capsys):
|
||||
"""--dry-run explains the steps and writes nothing, needs nothing."""
|
||||
code = gpgtools.main(["initialize_yubikey", "--dry-run",
|
||||
"--gnupg-home", str(tmp_path / "g")])
|
||||
assert code == 0
|
||||
assert "fetch" in capsys.readouterr().out
|
||||
assert not (tmp_path / "g").exists()
|
||||
|
||||
|
||||
def test_main_initialize_calls_flow(tmp_path, monkeypatch):
|
||||
"""The CLI wires initialize_yubikey to the real runner."""
|
||||
seen = {}
|
||||
|
||||
def fake_initialize(home, run_cmd):
|
||||
seen["home"] = home
|
||||
seen["runner"] = run_cmd
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(gpgtools, "initialize_yubikey", fake_initialize)
|
||||
code = gpgtools.main(["initialize_yubikey", "--gnupg-home", str(tmp_path)])
|
||||
assert code == 0
|
||||
assert seen["home"] == tmp_path
|
||||
assert seen["runner"] is gpgtools.run_command
|
||||
|
||||
|
||||
def test_main_help_exits_zero():
|
||||
"""--help prints usage."""
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
gpgtools.main(["--help"])
|
||||
assert exc.value.code == 0
|
||||
|
||||
|
||||
# --- send_pubkey: validation, sources, verification, sending
|
||||
|
||||
|
||||
FP = "A126B97CB5A18E923DE2A4FF23B8D25BC4A17EAB"
|
||||
GOOD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEXAMPLEBASE64KEY daedalus-test"
|
||||
OTHER_KEY = "ssh-rsa AAAAB3NzaC1yc2E someone-else"
|
||||
CANDIDATE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICANDIDATEKEY candidate"
|
||||
|
||||
|
||||
def make_runner(script, calls=None):
|
||||
"""Build an injectable run_cmd from {(cmd prefix): (code, output)}.
|
||||
|
||||
Also records (cmd, input_text) pairs into calls when given.
|
||||
"""
|
||||
|
||||
def run_cmd(cmd, input_text="", env=None):
|
||||
if calls is not None:
|
||||
calls.append((list(cmd), input_text))
|
||||
for prefix, reply in script.items():
|
||||
if list(cmd)[:len(prefix)] == list(prefix):
|
||||
return reply
|
||||
raise AssertionError(f"unexpected command: {cmd}")
|
||||
|
||||
return run_cmd
|
||||
|
||||
|
||||
def test_validate_pubkey_line():
|
||||
"""Valid ssh public key lines pass, garbage does not."""
|
||||
assert gpgtools.validate_pubkey_line(GOOD_KEY) is True
|
||||
assert gpgtools.validate_pubkey_line(OTHER_KEY) is True
|
||||
assert gpgtools.validate_pubkey_line("ssh-ed25519 AAAA") is True
|
||||
assert gpgtools.validate_pubkey_line("") is False
|
||||
assert gpgtools.validate_pubkey_line("not-a-key") is False
|
||||
assert gpgtools.validate_pubkey_line("ssh-ed448 AAAA comment") is False
|
||||
assert gpgtools.validate_pubkey_line("ssh-ed25519") is False
|
||||
|
||||
|
||||
def test_normalize_fingerprint():
|
||||
"""Fingerprints normalize: lower, spaced, 0x-prefixed all work."""
|
||||
spaced = "a126 b97c b5a1 8e92 3de2 a4ff 23b8 d25b c4a1 7eab"
|
||||
assert gpgtools.normalize_fingerprint(spaced) == FP
|
||||
assert gpgtools.normalize_fingerprint("0x" + FP.lower()) == FP
|
||||
assert gpgtools.normalize_fingerprint(FP) == FP
|
||||
assert gpgtools.normalize_fingerprint("123") is None
|
||||
assert gpgtools.normalize_fingerprint("Z" * 40) is None
|
||||
|
||||
|
||||
def test_keyserver_urls():
|
||||
"""The store chain is VKS first, then keyserver.ubuntu.com."""
|
||||
vks, ubuntu = gpgtools.keyserver_urls(FP)
|
||||
assert vks.startswith("https://keys.openpgp.org/vks/v1/by-fingerprint/")
|
||||
assert FP in vks
|
||||
assert "keyserver.ubuntu.com" in ubuntu
|
||||
assert "0x" + FP in ubuntu
|
||||
|
||||
|
||||
def test_cli_send_pubkey_requires_source():
|
||||
"""No key source flag is a usage error."""
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
gpgtools.main(["send_pubkey", "you@server"])
|
||||
assert exc.value.code == 2
|
||||
|
||||
|
||||
def test_cli_send_pubkey_requires_target():
|
||||
"""A source without a you@server target is a usage error."""
|
||||
with pytest.raises(SystemExit) as exc:
|
||||
gpgtools.main(["send_pubkey", "--yubikey"])
|
||||
assert exc.value.code == 2
|
||||
|
||||
|
||||
def test_cli_send_pubkey_dry_run(monkeypatch, capsys):
|
||||
"""--dry-run resolves and prints the key, sends and verifies nothing."""
|
||||
calls = []
|
||||
runner = make_runner({
|
||||
("gpgconf", "--list-dirs", "agent-ssh-socket"):
|
||||
(0, "/run/agent.sock\n"),
|
||||
("ssh-add", "-L"): (0, GOOD_KEY + "\n"),
|
||||
}, calls)
|
||||
monkeypatch.setattr(gpgtools, "run_command", runner)
|
||||
code = gpgtools.main(["send_pubkey", "--yubikey", "--dry-run",
|
||||
"you@server"])
|
||||
assert code == 0
|
||||
out = capsys.readouterr().out
|
||||
assert GOOD_KEY in out
|
||||
assert "you@server" in out
|
||||
assert not any(cmd[:1] == ["ssh"] for cmd, _ in calls)
|
||||
|
||||
|
||||
def test_cli_send_pubkey_wires_flow(monkeypatch):
|
||||
"""The CLI passes source, target, and flags into cmd_send_pubkey."""
|
||||
seen = {}
|
||||
|
||||
def fake_send(args, run_cmd, fetch):
|
||||
seen["args"] = args
|
||||
seen["runner"] = run_cmd
|
||||
return gpgtools.EXIT_OK
|
||||
|
||||
monkeypatch.setattr(gpgtools, "cmd_send_pubkey", fake_send)
|
||||
code = gpgtools.main(["send_pubkey", "--pubkey", GOOD_KEY,
|
||||
"--no-verify", "you@server"])
|
||||
assert code == 0
|
||||
assert seen["args"].pubkey == GOOD_KEY
|
||||
assert seen["args"].no_verify is True
|
||||
assert seen["runner"] is gpgtools.run_command
|
||||
|
||||
|
||||
def test_agent_env_parses_bare_and_prefixed_socket():
|
||||
"""gpgconf prints a bare path; the prefixed form also works."""
|
||||
runner = make_runner({("gpgconf", "--list-dirs",
|
||||
"agent-ssh-socket"): (0, "/run/agent.sock\n")})
|
||||
assert gpgtools.agent_ssh_env(runner) == {"SSH_AUTH_SOCK":
|
||||
"/run/agent.sock"}
|
||||
runner = make_runner({("gpgconf", "--list-dirs",
|
||||
"agent-ssh-socket"):
|
||||
(0, "agent-ssh-socket:/run/agent.sock\n")})
|
||||
assert gpgtools.agent_ssh_env(runner) == {"SSH_AUTH_SOCK":
|
||||
"/run/agent.sock"}
|
||||
|
||||
|
||||
def test_source_yubikey():
|
||||
"""--yubikey reads the agent's key via the gpg ssh socket."""
|
||||
runner = make_runner({
|
||||
("gpgconf", "--list-dirs", "agent-ssh-socket"):
|
||||
(0, "/run/agent.sock\n"),
|
||||
("ssh-add", "-L"): (0, GOOD_KEY + "\n"),
|
||||
})
|
||||
line, source = gpgtools.source_yubikey(runner)
|
||||
assert line == GOOD_KEY
|
||||
assert "agent" in source
|
||||
|
||||
|
||||
def test_source_yubikey_requires_gpg_ready():
|
||||
"""No agent socket means gpg is not initialized; message points there."""
|
||||
runner = make_runner({("gpgconf", "--list-dirs", "agent-ssh-socket"):
|
||||
(1, "")})
|
||||
with pytest.raises(gpgtools.SendPubkeyError) as err:
|
||||
gpgtools.source_yubikey(runner)
|
||||
assert "initialize_yubikey" in str(err.value)
|
||||
|
||||
|
||||
def test_source_yubikey_multiple_keys():
|
||||
"""Multiple agent keys refuse with a list instead of guessing."""
|
||||
runner = make_runner({
|
||||
("gpgconf", "--list-dirs", "agent-ssh-socket"):
|
||||
(0, "/run/agent.sock\n"),
|
||||
("ssh-add", "-L"): (0, GOOD_KEY + "\n" + OTHER_KEY + "\n"),
|
||||
})
|
||||
with pytest.raises(gpgtools.SendPubkeyError) as err:
|
||||
gpgtools.source_yubikey(runner)
|
||||
assert "--pubkey" in str(err.value)
|
||||
|
||||
|
||||
def test_source_pubkey_validates():
|
||||
"""--pubkey with a valid line passes through untouched."""
|
||||
line, source = gpgtools.source_pubkey(GOOD_KEY)
|
||||
assert line == GOOD_KEY
|
||||
assert "literal" in source
|
||||
with pytest.raises(gpgtools.SendPubkeyError):
|
||||
gpgtools.source_pubkey("garbage")
|
||||
|
||||
|
||||
def test_source_fingerprint_local_keyring_first():
|
||||
"""A fingerprint resolvable locally never touches the network."""
|
||||
calls = []
|
||||
runner = make_runner({
|
||||
("gpg", "--export-ssh-key", "0x" + FP): (0, GOOD_KEY + "\n"),
|
||||
}, calls)
|
||||
line, source = gpgtools.source_fingerprint(FP, runner, lambda _u: b"")
|
||||
assert line == GOOD_KEY
|
||||
assert source == "local keyring"
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_source_fingerprint_falls_back_to_stores(tmp_path):
|
||||
"""Local miss -> VKS fetch -> import -> fingerprint check -> export."""
|
||||
armor = b"-----BEGIN PGP PUBLIC KEY BLOCK-----"
|
||||
fetches = []
|
||||
|
||||
def fetch(url):
|
||||
fetches.append(url)
|
||||
return armor
|
||||
|
||||
calls = []
|
||||
|
||||
def fake_gpg(cmd, input_text="", env=None):
|
||||
calls.append((list(cmd), input_text))
|
||||
if cmd == ["gpg", "--export-ssh-key", "0x" + FP]:
|
||||
return (1, "")
|
||||
if cmd[:2] == ["gpg", "--homedir"]:
|
||||
if cmd[3] == "--import":
|
||||
assert armor.decode() in input_text
|
||||
return (0, "imported\n")
|
||||
if cmd[3:] == ["--list-keys", "--with-colons"]:
|
||||
return (0, "pub:u:4096:1:ABC:\nfpr:" + FP.lower() + ":x:x:\n")
|
||||
if cmd[3] == "--export-ssh-key":
|
||||
assert cmd[4] == "0x" + FP
|
||||
return (0, GOOD_KEY + "\n")
|
||||
raise AssertionError(f"unexpected {cmd}")
|
||||
|
||||
line, source = gpgtools.source_fingerprint(FP, fake_gpg, fetch)
|
||||
assert line == GOOD_KEY
|
||||
assert source == fetches[0]
|
||||
|
||||
|
||||
def test_source_fingerprint_rejects_wrong_key(tmp_path):
|
||||
"""A store returning a different fingerprint is skipped, next tried."""
|
||||
def fetch(_url):
|
||||
return b"-----BEGIN PGP PUBLIC KEY BLOCK-----"
|
||||
|
||||
def fake_gpg(cmd, input_text="", env=None):
|
||||
if cmd == ["gpg", "--export-ssh-key", "0x" + FP]:
|
||||
return (1, "")
|
||||
if cmd[:2] == ["gpg", "--homedir"]:
|
||||
return (0, "fpr:" + "F" * 40 + ":x:x:\n")
|
||||
raise AssertionError(f"unexpected {cmd}")
|
||||
|
||||
with pytest.raises(gpgtools.SendPubkeyError) as err:
|
||||
gpgtools.source_fingerprint(FP, fake_gpg, fetch)
|
||||
assert "no store" in str(err.value)
|
||||
|
||||
|
||||
def test_source_url_resolves_armored_key():
|
||||
"""--url fetches, imports into a temp home, exports the ssh line."""
|
||||
armor = b"-----BEGIN PGP PUBLIC KEY BLOCK-----"
|
||||
|
||||
def fake_gpg(cmd, input_text="", env=None):
|
||||
if cmd[:2] == ["gpg", "--homedir"]:
|
||||
if cmd[3] == "--import":
|
||||
assert armor.decode() in input_text
|
||||
return (0, "imported\n")
|
||||
if cmd[3:] == ["--list-keys", "--with-colons"]:
|
||||
return (0, "pub:u:4096:1:ABC:\nfpr:" + FP.lower() + ":x:x:\n")
|
||||
if cmd[3] == "--export-ssh-key":
|
||||
return (0, GOOD_KEY + "\n")
|
||||
raise AssertionError(f"unexpected {cmd}")
|
||||
|
||||
line, source = gpgtools.source_url("https://example.com/key.asc",
|
||||
fake_gpg, lambda _u: armor)
|
||||
assert line == GOOD_KEY
|
||||
assert "example.com" in source
|
||||
|
||||
|
||||
def test_verify_possession_sign_and_check(tmp_path):
|
||||
"""A successful agent signature over the challenge verifies the key."""
|
||||
calls = []
|
||||
|
||||
def fake_runner(cmd, input_text="", env=None):
|
||||
calls.append(list(cmd))
|
||||
if cmd == ["gpgconf", "--list-dirs", "agent-ssh-socket"]:
|
||||
return (0, "/run/agent.sock\n")
|
||||
if cmd[:3] == ["ssh-keygen", "-Y", "sign"]:
|
||||
pathlib.Path(cmd[-1] + ".sig").write_text("sig", encoding="utf-8")
|
||||
return (0, "Signing.\n")
|
||||
if cmd[:3] == ["ssh-keygen", "-Y", "verify"]:
|
||||
return (0, "Good signature.\n")
|
||||
raise AssertionError(f"unexpected {cmd}")
|
||||
|
||||
assert gpgtools.verify_possession(CANDIDATE_KEY, tmp_path,
|
||||
fake_runner) is True
|
||||
verifiers = [c for c in calls if c[:1] == ["ssh-keygen"]]
|
||||
assert len(verifiers) == 2 # sign + verify, both present
|
||||
|
||||
|
||||
def test_verify_possession_failing_sign(tmp_path):
|
||||
"""A private key that cannot sign the challenge fails verification."""
|
||||
calls = []
|
||||
|
||||
def fake_runner(cmd, input_text="", env=None):
|
||||
calls.append(list(cmd))
|
||||
if cmd == ["gpgconf", "--list-dirs", "agent-ssh-socket"]:
|
||||
return (0, "/run/agent.sock\n")
|
||||
return (1, "agent refused\n")
|
||||
|
||||
assert gpgtools.verify_possession(CANDIDATE_KEY, tmp_path,
|
||||
fake_runner) is False
|
||||
signers = [c for c in calls if c[:1] == ["ssh-keygen"]]
|
||||
assert len(signers) == 1 # sign only: verify is never reached
|
||||
|
||||
|
||||
def test_send_key_appends_when_absent(tmp_path):
|
||||
"""A new key is appended exactly once, via stdin, with perms."""
|
||||
calls = []
|
||||
|
||||
def fake_ssh(cmd, input_text="", env=None):
|
||||
calls.append((list(cmd), input_text))
|
||||
if len(cmd) > 2 and cmd[2] == "cat ~/.ssh/authorized_keys 2>/dev/null":
|
||||
return (0, OTHER_KEY + "\n")
|
||||
return (0, "")
|
||||
|
||||
code = gpgtools.send_key(GOOD_KEY, "you@server", fake_ssh)
|
||||
assert code == gpgtools.SENT_APPENDED
|
||||
appended = [(cmd, data) for cmd, data in calls
|
||||
if len(cmd) > 2 and "cat >>" in cmd[2]]
|
||||
assert len(appended) == 1
|
||||
assert appended[0][1] == GOOD_KEY + "\n"
|
||||
|
||||
|
||||
def test_send_key_idempotent_when_present():
|
||||
"""An already-present key is reported as such and never re-appended."""
|
||||
calls = []
|
||||
|
||||
def fake_ssh(cmd, input_text="", env=None):
|
||||
calls.append(list(cmd))
|
||||
return (0, GOOD_KEY + "\n")
|
||||
|
||||
assert gpgtools.send_key(GOOD_KEY, "you@server",
|
||||
fake_ssh) == gpgtools.SENT_PRESENT
|
||||
assert len(calls) == 1 # only the read
|
||||
|
||||
|
||||
def test_send_key_idempotent_across_comments():
|
||||
"""Same key material with a different comment is still a duplicate.
|
||||
|
||||
--yubikey yields a cardno comment, --fingerprint an openpgp one;
|
||||
authorized_keys comments are annotations, not identity.
|
||||
"""
|
||||
calls = []
|
||||
existing = GOOD_KEY.replace("daedalus-test", "cardno:12_345_678")
|
||||
|
||||
def fake_ssh(cmd, input_text="", env=None):
|
||||
calls.append(list(cmd))
|
||||
return (0, existing + "\n")
|
||||
|
||||
assert gpgtools.send_key(GOOD_KEY, "you@server",
|
||||
fake_ssh) == gpgtools.SENT_PRESENT
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_send_key_ssh_failure():
|
||||
"""An unreachable target returns the target exit code."""
|
||||
def fake_ssh(cmd, input_text="", env=None):
|
||||
return (255, "connection refused\n")
|
||||
|
||||
assert gpgtools.send_key(GOOD_KEY, "you@server",
|
||||
fake_ssh) == gpgtools.EXIT_TARGET
|
||||
|
||||
|
||||
def test_cmd_send_pubkey_full_flow(tmp_path, capsys):
|
||||
"""Verified key, absent on the server, is appended."""
|
||||
def fake_all(cmd, input_text="", env=None):
|
||||
if cmd == ["gpgconf", "--list-dirs", "agent-ssh-socket"]:
|
||||
return (0, "/run/agent.sock\n")
|
||||
if cmd == ["ssh-add", "-L"]:
|
||||
return (0, GOOD_KEY + "\n")
|
||||
if cmd[:3] == ["ssh-keygen", "-Y", "sign"]:
|
||||
pathlib.Path(cmd[-1] + ".sig").write_text("sig", encoding="utf-8")
|
||||
return (0, "Signing.\n")
|
||||
if cmd[:3] == ["ssh-keygen", "-Y", "verify"]:
|
||||
return (0, "Good signature.\n")
|
||||
if len(cmd) > 1 and cmd[1] == "cat ~/.ssh/authorized_keys 2>/dev/null":
|
||||
return (0, "")
|
||||
return (0, "")
|
||||
|
||||
args = gpgtools.parse_args(["send_pubkey", "--yubikey", "you@server"])
|
||||
code = gpgtools.cmd_send_pubkey(args, fake_all, lambda _u: b"")
|
||||
assert code == gpgtools.EXIT_OK
|
||||
assert "appended" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_cmd_send_pubkey_blocked_by_verification(tmp_path, capsys):
|
||||
"""Without proof of possession nothing is ever sent."""
|
||||
calls = []
|
||||
|
||||
def fake_all(cmd, input_text="", env=None):
|
||||
calls.append(list(cmd))
|
||||
if cmd == ["gpgconf", "--list-dirs", "agent-ssh-socket"]:
|
||||
return (0, "/run/agent.sock\n")
|
||||
if cmd == ["ssh-add", "-L"]:
|
||||
return (0, GOOD_KEY + "\n")
|
||||
return (1, "nope\n")
|
||||
|
||||
args = gpgtools.parse_args(["send_pubkey", "--yubikey", "you@server"])
|
||||
code = gpgtools.cmd_send_pubkey(args, fake_all, lambda _u: b"")
|
||||
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
|
||||
@@ -34,7 +34,7 @@ def test_app_version_falls_back_to_pyproject(monkeypatch):
|
||||
raise hello.importlib.metadata.PackageNotFoundError(_name)
|
||||
|
||||
monkeypatch.setattr(hello.importlib.metadata, "version", not_found)
|
||||
assert hello.app_version() == "0.4.0"
|
||||
assert hello.app_version() == "0.6.0"
|
||||
|
||||
|
||||
def test_help_exits_zero(capsys):
|
||||
|
||||
Reference in New Issue
Block a user