41c8b99bd6
- read-only: one row per marker-managed block in ~/.ssh/config (or --config PATH): alias, hostname, user, key id (first 8 chars of the identity's SHA256 fingerprint via ssh-keygen -lf, material digest as fallback), and the fallback identity's name - no managed blocks / missing config: fact + configure_ssh hint, exit 0 always (read-only command) - spec items 2.8 + section 13 first, then tests, then code (SPEC 6.12); 10 new tests (100 in test_gpgtools.py), registry description, README section, CHANGELOG 0.11.0, version pins Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
1332 lines
50 KiB
Python
1332 lines
50 KiB
Python
"""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 hashlib
|
|
import pathlib
|
|
|
|
import pytest
|
|
|
|
from daedalus.gpgtools import gpgtools
|
|
|
|
CARD_OK = """
|
|
Reader ...........: Yubico YubiKey OTP FIDO CCID 00 00
|
|
Application ID ...: D2760001240100000006054321090000
|
|
Application type .: OpenPGP
|
|
Version ..........: 3.4
|
|
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/0123
|
|
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/0123",
|
|
"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 == "54321098"
|
|
assert info.has_auth_subkey is True
|
|
assert info.key_url == "https://keys.openpgp.org/vks/v1/by-fingerprint/0123"
|
|
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/0123"]]
|
|
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 = "0123456789ABCDEF0123456789ABCDEF01234567"
|
|
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 = "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
|
|
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
|
|
|
|
|
|
# --- --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
|
|
|
|
|
|
# --- ssh-config-summary (gpgtools spec section 13)
|
|
|
|
|
|
def summary_config(tmp_path):
|
|
"""A config with one full managed block and one minimal one."""
|
|
pubkey = tmp_path / "yubikey_auth.pub"
|
|
fallback = tmp_path / "id_ed25519"
|
|
full = gpgtools.build_block("vault1", "203.0.113.10", "admin",
|
|
str(pubkey), str(fallback))
|
|
minimal = gpgtools.build_block("host1", "host1", None,
|
|
str(pubkey), None)
|
|
config = gpgtools.merge_managed_block(
|
|
gpgtools.merge_managed_block("", "vault1", full),
|
|
"host1", minimal)
|
|
return config, pubkey, fallback
|
|
|
|
|
|
def test_parse_managed_blocks_fields(tmp_path):
|
|
"""Each block yields alias, hostname, user, identities in order."""
|
|
config, pubkey, fallback = summary_config(tmp_path)
|
|
blocks = gpgtools.parse_managed_blocks(config)
|
|
assert [(b.alias, b.hostname, b.user) for b in blocks] == \
|
|
[("vault1", "203.0.113.10", "admin"), ("host1", "host1", None)]
|
|
assert blocks[0].identities == (pubkey, fallback)
|
|
assert blocks[1].identities == (pubkey,)
|
|
|
|
|
|
def test_parse_managed_blocks_without_markers():
|
|
"""A config without managed blocks parses to an empty list."""
|
|
assert gpgtools.parse_managed_blocks(
|
|
"Host other\n HostName 10.0.0.1\n") == []
|
|
|
|
|
|
def test_ssh_key_id_from_ssh_keygen(tmp_path):
|
|
"""sshd-style ssh-keygen output yields the bare fingerprint."""
|
|
pubkey = tmp_path / "yubikey_auth.pub"
|
|
pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8")
|
|
runner = make_runner({("ssh-keygen", "-lf"):
|
|
(0, "256 SHA256:AAAA1111BBBB2222 "
|
|
"cardno:12 (ED25519)\n")})
|
|
assert gpgtools.ssh_key_id(pubkey, runner) == "AAAA1111BBBB2222"
|
|
|
|
|
|
def test_ssh_key_id_falls_back_to_digest(tmp_path):
|
|
"""Without ssh-keygen, a readable key yields the material digest."""
|
|
pubkey = tmp_path / "yubikey_auth.pub"
|
|
pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8")
|
|
runner = make_runner({("ssh-keygen", "-lf"): (127, "not found")})
|
|
digest = gpgtools.material_digest(GOOD_KEY)
|
|
assert gpgtools.ssh_key_id(pubkey, runner) == digest
|
|
|
|
|
|
def test_ssh_key_id_missing_file(tmp_path):
|
|
"""A missing identity file yields None (row prints -)."""
|
|
runner = make_runner({("ssh-keygen", "-lf"): (1, "no such file\n")})
|
|
assert gpgtools.ssh_key_id(tmp_path / "nope.pub", runner) is None
|
|
|
|
|
|
def test_cmd_summary_prints_the_table(tmp_path, capsys):
|
|
"""Two blocks render with header, 8-char ids, and fallbacks."""
|
|
config, pubkey, fallback = summary_config(tmp_path)
|
|
target = tmp_path / "config"
|
|
target.write_text(config, encoding="utf-8")
|
|
runner = make_runner({("ssh-keygen", "-lf"):
|
|
(0, "256 SHA256:AAAA1111BBBB2222 "
|
|
"cardno:12 (ED25519)\n")})
|
|
args = gpgtools.parse_args(["ssh-config-summary",
|
|
"--config", str(target)])
|
|
assert gpgtools.cmd_ssh_config_summary(
|
|
args, runner) == gpgtools.EXIT_OK
|
|
out = capsys.readouterr().out
|
|
assert "alias" in out and "hostname" in out and "key id" in out
|
|
assert "vault1" in out and "203.0.113.10" in out and "admin" in out
|
|
assert "host1" in out
|
|
assert "AAAA1111" in out # truncated id
|
|
assert "BBBB2222" not in out # only the first 8 chars
|
|
assert fallback.name in out # vault1's fallback
|
|
assert "-" in out # host1's missing fallback/user
|
|
|
|
|
|
def test_cmd_summary_empty_config(tmp_path, capsys):
|
|
"""No managed blocks: fact plus configure_ssh hint, exit 0."""
|
|
target = tmp_path / "config"
|
|
target.write_text("Host other\n HostName 10.0.0.1\n",
|
|
encoding="utf-8")
|
|
args = gpgtools.parse_args(["ssh-config-summary",
|
|
"--config", str(target)])
|
|
assert gpgtools.cmd_ssh_config_summary(
|
|
args, make_runner({})) == gpgtools.EXIT_OK
|
|
out = capsys.readouterr().out
|
|
assert "no daedalus gpgtools" in out
|
|
assert "configure_ssh" in out
|
|
|
|
|
|
def test_cmd_summary_missing_config(tmp_path, capsys):
|
|
"""A missing config file is the same empty case, exit 0."""
|
|
args = gpgtools.parse_args(["ssh-config-summary",
|
|
"--config",
|
|
str(tmp_path / "nope")])
|
|
assert gpgtools.cmd_ssh_config_summary(
|
|
args, make_runner({})) == gpgtools.EXIT_OK
|
|
assert "no daedalus gpgtools" in capsys.readouterr().out
|
|
|
|
|
|
def test_cli_summary_wires_flow(monkeypatch):
|
|
"""The CLI dispatches the summary with the runner."""
|
|
seen = {}
|
|
|
|
def fake_summary(args, run_cmd):
|
|
seen["args"] = args
|
|
seen["runner"] = run_cmd
|
|
return gpgtools.EXIT_OK
|
|
|
|
monkeypatch.setattr(gpgtools, "cmd_ssh_config_summary",
|
|
fake_summary)
|
|
assert gpgtools.main(["ssh-config-summary"]) == 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
|