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:
nvaldez
2026-11-19 00:46:40 +01:00
parent ec9848b169
commit fef68a84c9
8 changed files with 1472 additions and 3 deletions
+32
View File
@@ -10,6 +10,38 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
- Nothing yet. - Nothing yet.
## [0.6.0] - 2026-11-18
### Added in 0.6.0
- `gpgtools send_pubkey` (guide steps 5-6): resolves an SSH public key
from one of four sources — `--yubikey` (gpg-agent ssh socket),
`--url` (armored OpenPGP key, converted with `gpg --export-ssh-key`
in a throwaway GNUPGHOME), `--fingerprint` (store chain: local
keyring, keys.openpgp.org VKS, keyserver.ubuntu.com, each
fingerprint-checked), or `--pubkey` (literal line, format-validated).
Before anything is stored, proof of possession: a random challenge is
signed by the private half through the agent (`ssh-keygen -Y sign
-U`; PIN prompts reach the user) and verified against the candidate
line (`ssh-keygen -Y verify`). Only then is the line appended to the
target's `authorized_keys` — idempotent (grep before append), perms
enforced. `--no-verify` skips the check explicitly; `--dry-run`
resolves and prints without side effects. 22 new tests.
## [0.5.0] - 2026-11-18
### Added in 0.5.0
- `gpgtools` (Python, category `gpg`): YubiKey GPG/SSH helpers.
`daedalus gpgtools initialize_yubikey` runs the fresh-machine flow
(steps 1-4 of the wiki guide): installs gnupg when missing (apt-get,
dnf, pacman), checks the card, fetches the public key from the card's
URL field with `gpg --fetch-keys`, and writes the gpg-agent SSH
config (`enable-ssh-support`, cache TTLs) with the GNUPGHOME
directory at mode 700. `--dry-run` prints the plan; steps 5-7
(derive and deploy the SSH key per host) are server-specific and
intentionally out of scope.
## [0.4.0] - 2026-11-18 ## [0.4.0] - 2026-11-18
### Added in 0.4.0 ### Added in 0.4.0
+52
View File
@@ -17,6 +17,7 @@ daedalus --list # list everything
| Script | Type | Categories | What it does | | Script | Type | Categories | What it does |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| `gpgtools` | Python | gpg | YubiKey GPG/SSH helpers: initialize_yubikey (fresh machine, steps 1-4) and send_pubkey (resolve key, verify possession, append to a server) |
| `hello` | Python | test | Prints a hello line and the daedalus version | | `hello` | Python | test | Prints a hello line and the daedalus version |
| `hello_bash` | Bash | test | Sample bash script through the shared help() interface | | `hello_bash` | Bash | test | Sample bash script through the shared help() interface |
@@ -33,6 +34,57 @@ daedalus test # list the scripts in the 'test' category
`daedalus --list` prints the version, a `script` / `type` / `categories` `daedalus --list` prints the version, a `script` / `type` / `categories`
table, and each description wrapped under each row. table, and each description wrapped under each row.
### gpgtools
`initialize_yubikey` runs the fresh-machine flow for YubiKey-backed
GPG and SSH (steps 1-4 of the wiki guide): install gnupg when missing,
check the card, fetch the public key from the card's URL field, and
write the gpg-agent SSH config. Deriving and deploying the SSH key
(steps 5-7) is server-specific and stays manual for now.
```bash
daedalus gpgtools # overview of the subcommands
daedalus gpgtools initialize_yubikey # prepare this machine
daedalus gpgtools initialize_yubikey --dry-run # print the plan only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--dry-run` | off | Print the plan, write nothing |
| `--gnupg-home DIR` | `GNUPGHOME` or `~/.gnupg` | Which GnuPG home to configure |
Exit codes: `0` ready, `2` package install failed, `3` gpg missing and
no known package manager, `4` no card found, `5` public-key fetch did
not pair the keyring, `6` keyring unpaired and the card carries no URL.
`send_pubkey` covers guide steps 5-6 for one server: resolve the SSH
public key from one of four sources, prove possession of the private
half with a challenge signature (the YubiKey itself signs; PIN prompts
go to the user), then append the line to the target's
`authorized_keys` — idempotent, fingerprint-checked against stores,
and nothing is sent when verification fails.
```bash
daedalus gpgtools send_pubkey --yubikey you@server
daedalus gpgtools send_pubkey --fingerprint <FP> you@server
daedalus gpgtools send_pubkey --url https://keys.openpgp.org/vks/v1/by-fingerprint/<FP> you@server
daedalus gpgtools send_pubkey --pubkey "ssh-ed25519 AAAA... comment" you@server
daedalus gpgtools send_pubkey --yubikey --dry-run you@server # resolve only
```
| Argument | Default | Meaning |
| --- | --- | --- |
| `--yubikey` | — | Key from the plugged YubiKey via gpg-agent (must be the only agent key) |
| `--url URL` | — | Armored OpenPGP public key at a URL ([A] subkey is exported) |
| `--fingerprint FP` | — | Searched: local keyring → keys.openpgp.org → keyserver.ubuntu.com |
| `--pubkey LINE` | — | The literal SSH public key line |
| `--no-verify` | verification on | Skip the proof-of-possession signature (explicit risk acceptance) |
| `--dry-run` | off | Resolve and print the key; verify and send nothing |
Additional exit codes: `7` ssh to the target failed, `8` no source
resolved a key, `10` proof-of-possession verification failed (nothing
was sent).
## Shell completion ## Shell completion
Bash (and other shells argcomplete supports) completes script names and Bash (and other shells argcomplete supports) completes script names and
+5
View File
@@ -54,6 +54,11 @@ class Script:
SCRIPTS: dict[str, Script] = { SCRIPTS: dict[str, Script] = {
"gpgtools": Script(
path="python/src/gpgtools/gpgtools.py",
description="YubiKey GPG/SSH helpers: initialize_yukikey (fresh machine, steps 1-4) and send_pubkey (resolve key, verify possession, append to a server)",
categories="gpg",
),
"hello": Script( "hello": Script(
path="python/src/hello/hello.py", path="python/src/hello/hello.py",
description="Print a hello line and the daedalus version", description="Print a hello line and the daedalus version",
+1 -1
View File
@@ -150,7 +150,7 @@ def test_path_with_extra_words_is_a_usage_error(fake_registry, plain, capsys):
assert "usage: daedalus --path <name>" in capsys.readouterr().err assert "usage: daedalus --path <name>" in capsys.readouterr().err
@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.4.0")]) @pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.6.0")])
def test_version(monkeypatch, capsys, installed, expected): def test_version(monkeypatch, capsys, installed, expected):
"""--version uses metadata or pyproject.toml in a checkout.""" """--version uses metadata or pyproject.toml in a checkout."""
def fake_version(_name): def fake_version(_name):
+3 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "daedalus" name = "daedalus"
version = "0.4.0" version = "0.6.0"
description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]" description = "Template for daedalus: loose scripts in one repo, run with: daedalus <name> [args...]"
readme = "README.md" readme = "README.md"
requires-python = ">=3.11" requires-python = ">=3.11"
@@ -19,6 +19,7 @@ daedalus = "daedalus.cli:main"
packages = [ packages = [
"daedalus", "daedalus",
"daedalus.daedalus_logging", "daedalus.daedalus_logging",
"daedalus.gpgtools",
"daedalus.hello", "daedalus.hello",
"daedalus._library.python.src", "daedalus._library.python.src",
"daedalus._library.bash", "daedalus._library.bash",
@@ -27,6 +28,7 @@ packages = [
] ]
[tool.setuptools.package-dir] [tool.setuptools.package-dir]
"daedalus.gpgtools" = "python/src/gpgtools"
"daedalus.hello" = "python/src/hello" "daedalus.hello" = "python/src/hello"
"daedalus._library.python.src" = "python/src" "daedalus._library.python.src" = "python/src"
"daedalus._library.bash" = "bash" "daedalus._library.bash" = "bash"
+690
View File
@@ -0,0 +1,690 @@
"""Prepare a machine for YubiKey-backed GPG and SSH (guide steps 1-4).
Runs the fresh-machine flow from the llm-wiki guide
(wiki/queries/yubikey-ssh-guide.md, section 13): install gnupg,
check the card, fetch the public key from the card's URL, and
configure gpg-agent's SSH support. ``send_pubkey`` covers guide
steps 5-6 for one server: resolve the SSH public key from one
of four sources, prove possession of the private half with a
challenge signature, then append the line to the target's
authorized_keys.
Run via daedalus: ``daedalus gpgtools initialize_yukikey`` or
``daedalus gpgtools send_pubkey --yubikey you@server``.
"""
from __future__ import annotations
import argparse
import dataclasses
import logging
import os
import pathlib
import re
import secrets
import shutil
import subprocess
import sys
import tempfile
import urllib.error
import urllib.request
try:
from argcomplete import autocomplete
except ImportError: # pragma: no cover - completion off without argcomplete
autocomplete = None
LOGGER = logging.getLogger(__name__)
EXIT_OK = 0
EXIT_INSTALL_FAILED = 2
EXIT_NO_GPG = 3
EXIT_NO_CARD = 4
EXIT_FETCH_FAILED = 5
EXIT_NO_URL = 6
EXIT_TARGET = 7
EXIT_NO_KEY = 8
EXIT_VERIFY_FAILED = 10
SENT_APPENDED = 0
SENT_PRESENT = 1
VERIFY_NAMESPACE = "daedalus-gpgtools"
MANAGER_COMMANDS = {
"apt-get": ["sudo", "apt-get", "install", "-y", "gnupg"],
"dnf": ["sudo", "dnf", "install", "-y", "gnupg2"],
"pacman": ["sudo", "pacman", "--noconfirm", "-S", "gnupg"],
}
CARD_FIELD_LABELS = ("Serial number", "Authentication key",
"URL of public key", "General key info")
VKS_URL = "https://keys.openpgp.org/vks/v1/by-fingerprint/{fp}"
UBUNTU_KS_URL = "https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x{fp}"
SSH_PUBKEY_PATTERN = re.compile(
r"^ssh-(?:ed25519|rsa|dss|ecdsa-sha2-[a-z0-9-]+) "
r"[A-Za-z0-9+/=]+(?: .*)?$")
FINGERPRINT_PATTERN = re.compile(r"^[0-9A-Fa-f]{40}$")
@dataclasses.dataclass(frozen=True)
class CardStatus:
"""What `gpg --card-status` says about the plugged card.
Args:
present: an OpenPGP card answered at all.
serial: card serial number, or None.
has_auth_subkey: the card holds an `[A]` subkey.
key_url: the card's public-key URL, or None.
keyring_paired: the public key is in this machine's keyring.
"""
present: bool
serial: str | None
has_auth_subkey: bool
key_url: str | None
keyring_paired: bool
def parse_card_status(text: str) -> CardStatus:
"""Parse `gpg --card-status` output into a CardStatus.
Args:
text: combined stdout/stderr of `gpg --card-status`.
Returns:
CardStatus with present=False when no card answered.
"""
fields: dict[str, str] = {}
for line in text.splitlines():
stripped = line.strip()
for label in CARD_FIELD_LABELS:
if stripped.startswith(label) and ":" in stripped:
value = stripped.split(":", 1)[1].strip()
if value and value != "[none]" and value != "[not set]":
fields[label] = value
present = "Application type" in text and "OpenPGP" in text
return CardStatus(
present=present,
serial=fields.get("Serial number"),
has_auth_subkey="Authentication key" in fields,
key_url=fields.get("URL of public key"),
keyring_paired="General key info" in fields,
)
def merge_agent_config(existing: str) -> str:
"""Return the agent config with ssh support enabled.
Keeps every existing line; adds `enable-ssh-support` and the
two cache TTL defaults only when the key is not configured.
Args:
existing: current gpg-agent.conf text, or "".
Returns:
New full config text, newline-terminated.
"""
lines = [line.strip() for line in existing.splitlines() if line.strip()]
if not any(line == "enable-ssh-support" for line in lines):
lines.append("enable-ssh-support")
for key, default in (("default-cache-ttl", "600"), ("max-cache-ttl", "7200")):
if not any(line.startswith(key + " ") for line in lines):
lines.append(f"{key} {default}")
return "\n".join(lines) + "\n"
def install_command(manager: str) -> list[str] | None:
"""Return the install command for a package manager, or None.
Args:
manager: one of "apt-get", "dnf", "pacman".
Returns:
The full command including sudo, or None when unknown.
"""
return MANAGER_COMMANDS.get(manager)
def detect_package_manager() -> str | None:
"""Return the first known package manager on PATH, or None."""
for manager in MANAGER_COMMANDS:
if shutil.which(manager):
return manager
return None
def gnupg_home() -> pathlib.Path:
"""Return the active GnuPG home (GNUPGHOME or ~/.gnupg)."""
env_home = os.environ.get("GNUPGHOME")
if env_home:
return pathlib.Path(env_home)
return pathlib.Path.home() / ".gnupg"
def run_command(cmd: list[str], input_text: str = "",
env: dict[str, str] | None = None) -> tuple[int, str]:
"""Run a command, return (exit code, combined output).
Args:
cmd: command and arguments.
input_text: text piped to the command's stdin.
env: extra environment variables merged over os.environ.
Returns:
(returncode, stdout+stderr), or (127, message) when the
binary does not exist.
"""
child_env = {**os.environ, **(env or {})}
try:
result = subprocess.run(cmd, capture_output=True, text=True,
check=False, input=input_text or None,
env=child_env)
except FileNotFoundError:
return 127, f"{' '.join(cmd)}: not found"
return result.returncode, (result.stdout or "") + (result.stderr or "")
def initialize_yubikey(home: pathlib.Path,
run_cmd=None) -> int:
"""Bring a fresh machine to 'ready for GPG' state (steps 1-4).
Args:
home: the GnuPG home directory to configure.
run_cmd: command runner, ``(cmd) -> (code, output)``;
defaults to run_command. Injected by tests.
Returns:
Exit code: 0 ready, 2 install failed, 3 no gpg and no
manager, 4 no card, 5 fetch failed, 6 no URL to fetch.
"""
if run_cmd is None:
run_cmd = run_command
code, _output = run_cmd(["gpg", "--version"])
if code != 0:
manager = detect_package_manager()
command = manager and install_command(manager)
if command is None:
LOGGER.error("gpg is missing and no known package manager "
"was found; install gnupg manually")
return EXIT_NO_GPG
LOGGER.info("installing gnupg via %s", manager)
code, output = run_cmd(command)
if code != 0:
LOGGER.error("package install failed: %s", output.strip())
return EXIT_INSTALL_FAILED
code, output = run_cmd(["gpg", "--card-status"])
info = parse_card_status(output)
if not info.present:
LOGGER.error("no OpenPGP card found; plug the YubiKey in and "
"retry (pcscd may need: systemctl enable --now pcscd)")
return EXIT_NO_CARD
LOGGER.info("card present, serial %s", info.serial)
if not info.keyring_paired:
if info.key_url is None:
LOGGER.error("public key not in the keyring and the card "
"carries no URL; import it with gpg "
"--locate-keys or gpg --import")
return EXIT_NO_URL
LOGGER.info("fetching public key from %s", info.key_url)
code, output = run_cmd(["gpg", "--fetch-keys", info.key_url])
_code, after = run_cmd(["gpg", "--card-status"])
if parse_card_status(after).keyring_paired is False:
LOGGER.error("fetch did not pair the keyring: %s", output.strip())
return EXIT_FETCH_FAILED
else:
LOGGER.info("public key already in the keyring")
if not info.has_auth_subkey:
LOGGER.warning("card has no [A] subkey; SSH via gpg-agent "
"will not work, GPG signing/decryption will")
home.mkdir(mode=0o700, parents=True, exist_ok=True)
home.chmod(0o700)
config = home / "gpg-agent.conf"
existing = config.read_text(encoding="utf-8") if config.exists() else ""
config.write_text(merge_agent_config(existing), encoding="utf-8")
LOGGER.info("wrote %s", config)
run_cmd(["gpgconf", "--kill", "gpg-agent"])
LOGGER.info("gpg-agent restarted; machine ready for GPG. Next "
"(ssh, server-specific): derive the key with "
"ssh-add -L and deploy it per host")
return EXIT_OK
class SendPubkeyError(Exception):
"""A send_pubkey source could not resolve a usable public key."""
def validate_pubkey_line(line: str) -> bool:
"""True when line is a well-formed SSH public key line.
Args:
line: candidate public key line.
Returns:
True for ``ssh-<type> <base64> [comment]`` shapes.
"""
return bool(SSH_PUBKEY_PATTERN.fullmatch(line.strip()))
def normalize_fingerprint(text: str) -> str | None:
"""Return a fingerprint as 40 uppercase hex chars, or None.
Args:
text: fingerprint with optional 0x prefix and spaces.
"""
stripped = text.strip().replace(" ", "")
if stripped[:2] in ("0x", "0X"):
stripped = stripped[2:]
return stripped.upper() if FINGERPRINT_PATTERN.fullmatch(stripped) else None
def keyserver_urls(fingerprint: str) -> list[str]:
"""Return the store chain for a fingerprint, first hit wins.
Args:
fingerprint: 40 uppercase hex chars.
Returns:
VKS first, then keyserver.ubuntu.com.
"""
return [VKS_URL.format(fp=fingerprint),
UBUNTU_KS_URL.format(fp=fingerprint)]
def fetch_bytes(url: str) -> bytes | None:
"""Download a URL, return the body, or None on failure.
Args:
url: address of an armored OpenPGP public key.
"""
try:
with urllib.request.urlopen(url, timeout=30) as response:
return response.read()
except (urllib.error.URLError, ValueError):
return None
def agent_ssh_env(run_cmd) -> dict[str, str]:
"""Return the SSH_AUTH_SOCK env pointing at gpg-agent.
Args:
run_cmd: command runner.
Raises:
SendPubkeyError: gpg is not initialized (no agent).
"""
code, output = run_cmd(["gpgconf", "--list-dirs", "agent-ssh-socket"])
text = output.strip()
if text.startswith("agent-ssh-socket:"):
text = text.split(":", 1)[1].strip()
socket_path = text if text.startswith("/") else ""
if code != 0 or not socket_path:
raise SendPubkeyError("gpg ssh agent not found; run "
"daedalus gpgtools initialize_yubikey first")
return {"SSH_AUTH_SOCK": socket_path}
def source_yubikey(run_cmd) -> tuple[str, str]:
"""Resolve the key from the plugged YubiKey via gpg-agent.
Args:
run_cmd: command runner.
Returns:
(ssh public key line, source description).
Raises:
SendPubkeyError: no agent, or the agent holds several keys.
"""
try:
env = agent_ssh_env(run_cmd)
except SendPubkeyError as err:
raise SendPubkeyError(str(err)) from err
code, output = run_cmd(["ssh-add", "-L"], env=env)
lines = [line.strip() for line in output.splitlines() if line.strip()]
if code != 0 or not lines:
raise SendPubkeyError("agent holds no ssh keys; is the YubiKey "
"plugged in?")
if len(lines) > 1:
raise SendPubkeyError("agent holds several keys; pass the exact "
"line with --pubkey:\n" + "\n".join(lines))
return lines[0], "gpg-agent (YubiKey)"
def source_pubkey(line: str) -> tuple[str, str]:
"""Resolve a literal SSH public key line.
Args:
line: the exact line to send.
Returns:
(the line, source description).
Raises:
SendPubkeyError: the line is not a valid ssh key.
"""
if not validate_pubkey_line(line):
raise SendPubkeyError(f"not a valid ssh public key line: {line!r}")
return line.strip(), "literal --pubkey"
def _gpg_line_for_armor(armor: bytes, run_cmd,
fingerprint: str | None = None) -> str | None:
"""Convert armored OpenPGP key(s) to the SSH line, or None.
Imports into a throwaway GNUPG home - the real keyring is
never touched - checks the fingerprint when given, and
exports the authentication subkey via gpg --export-ssh-key.
"""
home = tempfile.mkdtemp(prefix="daedalus-gpgtools-")
try:
code, _ = run_cmd(["gpg", "--homedir", home, "--import"],
input_text=armor.decode("utf-8", "replace"))
if code != 0:
return None
code, output = run_cmd(["gpg", "--homedir", home,
"--list-keys", "--with-colons"])
if code != 0:
return None
found = [row.split(":")[1] for row in output.splitlines()
if row.startswith("fpr:")]
if fingerprint:
if fingerprint.upper() not in [f.upper() for f in found]:
return None
export_id = "0x" + fingerprint.upper()
elif found:
export_id = "0x" + found[0]
else:
return None
code, output = run_cmd(["gpg", "--homedir", home,
"--export-ssh-key", export_id])
line = output.strip()
if code == 0 and validate_pubkey_line(line):
return line
return None
finally:
shutil.rmtree(home, ignore_errors=True)
def source_url(url: str, run_cmd, fetch) -> tuple[str, str]:
"""Resolve the SSH line from a URL holding an armored key.
Args:
url: address of the armored OpenPGP public key.
run_cmd: command runner.
fetch: ``(url) -> bytes | None`` fetcher.
Returns:
(ssh public key line, the url as source description).
Raises:
SendPubkeyError: fetch or conversion failed.
"""
armor = fetch(url)
if not armor:
raise SendPubkeyError(f"could not fetch {url}")
line = _gpg_line_for_armor(armor, run_cmd)
if line is None:
raise SendPubkeyError(f"no usable ([A] subkey) public key at {url}")
return line, url
def source_fingerprint(fingerprint: str, run_cmd, fetch) -> tuple[str, str]:
"""Resolve a fingerprint through the store chain.
Order: local keyring, keys.openpgp.org VKS,
keyserver.ubuntu.com. A store returning a different
fingerprint is skipped.
Args:
fingerprint: hex fingerprint, any spacing/case.
run_cmd: command runner.
fetch: ``(url) -> bytes | None`` fetcher.
Returns:
(ssh public key line, source description).
Raises:
SendPubkeyError: no store had the fingerprint.
"""
fp = normalize_fingerprint(fingerprint)
if fp is None:
raise SendPubkeyError(f"not a 40-hex fingerprint: {fingerprint!r}")
code, output = run_cmd(["gpg", "--export-ssh-key", "0x" + fp])
line = output.strip()
if code == 0 and validate_pubkey_line(line):
return line, "local keyring"
for url in keyserver_urls(fp):
armor = fetch(url)
if not armor:
continue
line = _gpg_line_for_armor(armor, run_cmd, fp)
if line is not None:
return line, url
raise SendPubkeyError(f"no store had fingerprint {fp} (local "
"keyring, keys.openpgp.org, "
"keyserver.ubuntu.com)")
def verify_possession(line: str, workdir: pathlib.Path,
run_cmd) -> bool:
"""Prove the private half of line is usable: sign a challenge.
Writes the candidate public key, a random challenge, and an
allowed_signers file in workdir, asks the ssh agent to sign
the challenge with -U (PIN prompts go to the user), and
verifies the signature against the candidate line.
Args:
line: candidate ssh public key.
workdir: scratch directory for the artifacts.
run_cmd: command runner.
Returns:
True when the private key signed and the signature
verified; False on any failure.
"""
candidate = workdir / "candidate.pub"
challenge_path = workdir / "challenge"
allowed = workdir / "allowed_signers"
challenge = secrets.token_hex(32)
candidate.write_text(line + "\n", encoding="utf-8")
challenge_path.write_text(challenge, encoding="utf-8")
allowed.write_text(f"daedalus@verify {line}\n", encoding="utf-8")
try:
env = agent_ssh_env(run_cmd)
except SendPubkeyError:
env = None
code, _ = run_cmd(["ssh-keygen", "-Y", "sign", "-U",
"-f", str(candidate), "-n", VERIFY_NAMESPACE,
str(challenge_path)], env=env)
if code != 0:
return False
sig_path = pathlib.Path(str(challenge_path) + ".sig")
if not sig_path.exists():
return False
code, _ = run_cmd(["ssh-keygen", "-Y", "verify",
"-f", str(allowed), "-I", "daedalus@verify",
"-n", VERIFY_NAMESPACE, "-s", str(sig_path)],
input_text=challenge)
return code == 0
def _key_material(line: str) -> str:
"""Type and base64 of a public key line - comments are annotations."""
return " ".join(line.split()[:2])
def send_key(line: str, target: str, run_cmd) -> int:
"""Append one public key line to target's authorized_keys.
Reads the server's authorized_keys first (idempotence by key
material, ignoring comments), then appends the line over stdin
only when absent.
Args:
line: validated ssh public key line.
target: ``user@server`` ssh target.
run_cmd: command runner (the real one passes through ssh).
Returns:
SENT_APPENDED, SENT_PRESENT, or EXIT_TARGET on ssh failure.
"""
code, output = run_cmd(["ssh", target,
"cat ~/.ssh/authorized_keys 2>/dev/null"])
if code != 0:
return EXIT_TARGET
material = _key_material(line.strip())
if material in [_key_material(row) for row in output.splitlines()]:
return SENT_PRESENT
code, _ = run_cmd(["ssh", target,
"mkdir -p ~/.ssh && chmod 700 ~/.ssh && "
"touch ~/.ssh/authorized_keys && "
"chmod 600 ~/.ssh/authorized_keys && "
"cat >> ~/.ssh/authorized_keys"],
input_text=line.strip() + "\n")
if code != 0:
return EXIT_TARGET
return SENT_APPENDED
def cmd_send_pubkey(args: argparse.Namespace, run_cmd=None,
fetch=None) -> int:
"""send_pubkey subcommand: resolve, verify, append.
Args:
args: parsed arguments (source, target, flags).
run_cmd: command runner; defaults to run_command.
fetch: ``(url) -> bytes | None``; defaults to fetch_bytes.
Returns:
Exit code (EXIT_OK, EXIT_NO_KEY, EXIT_VERIFY_FAILED,
EXIT_TARGET).
"""
if run_cmd is None:
run_cmd = run_command
if fetch is None:
fetch = fetch_bytes
try:
if args.yubikey:
line, source = source_yubikey(run_cmd)
elif args.url:
line, source = source_url(args.url, run_cmd, fetch)
elif args.fingerprint:
line, source = source_fingerprint(args.fingerprint, run_cmd,
fetch)
else:
line, source = source_pubkey(args.pubkey)
except SendPubkeyError as err:
LOGGER.error("%s", err)
return EXIT_NO_KEY
print(f"public key : {line}")
print(f"source : {source}")
print(f"target : {args.target}")
if args.dry_run:
print("dry run: nothing verified, nothing sent")
return EXIT_OK
if not args.no_verify:
workdir = pathlib.Path(tempfile.mkdtemp(prefix="daedalus-verify-"))
try:
if not verify_possession(line, workdir, run_cmd):
print("verification FAILED: no private key could sign for "
"this public key; nothing sent (use --no-verify to "
"skip on purpose)")
return EXIT_VERIFY_FAILED
finally:
shutil.rmtree(workdir, ignore_errors=True)
print("verification ok: private key proved possession")
else:
print("verification skipped (--no-verify)")
status = send_key(line, args.target, run_cmd)
if status == SENT_PRESENT:
print(f"key already present on {args.target}; nothing changed")
return EXIT_OK
if status != SENT_APPENDED:
print(f"ssh to {args.target} failed; key NOT stored on the server")
return EXIT_TARGET
print(f"appended the public key to {args.target} authorized_keys")
return EXIT_OK
def parse_args(argv: list[str] | None) -> argparse.Namespace:
"""Parse gpgtools command-line arguments."""
parser = argparse.ArgumentParser(
prog="gpgtools",
description="YubiKey GPG/SSH helpers (fresh-machine flow)",
)
subparsers = parser.add_subparsers(dest="command")
init = subparsers.add_parser(
"initialize_yubikey",
help="install gnupg, check the card, fetch the public "
"key, configure gpg-agent SSH support (steps 1-4)",
)
init.add_argument("--dry-run", action="store_true",
help="print the plan, change nothing")
init.add_argument("--gnupg-home", type=pathlib.Path, default=None,
help="GnuPG home to configure "
"(default GNUPGHOME or ~/.gnupg)")
send = subparsers.add_parser(
"send_pubkey",
help="resolve an SSH public key (guide steps 5-6), prove "
"possession of the private half, append it to a server's "
"authorized_keys",
)
sources = send.add_mutually_exclusive_group(required=True)
sources.add_argument("--yubikey", action="store_true",
help="take the key from the plugged YubiKey "
"(gpg-agent ssh socket)")
sources.add_argument("--url", metavar="URL",
help="URL of an armored OpenPGP public key")
sources.add_argument("--fingerprint", metavar="FP",
help="OpenPGP fingerprint; searched in the "
"local keyring, keys.openpgp.org, "
"keyserver.ubuntu.com")
sources.add_argument("--pubkey", metavar="LINE",
help="the literal ssh public key line")
send.add_argument("--no-verify", action="store_true",
help="skip the proof-of-possession signature "
"(explicit risk acceptance)")
send.add_argument("--dry-run", action="store_true",
help="resolve and print the key, verify and send "
"nothing")
send.add_argument("target", metavar="you@server",
help="ssh target that receives the key")
if autocomplete is not None: # pragma: no cover - needs argcomplete
autocomplete(parser)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""CLI entry point; return the exit code.
Args:
argv: argument list; None means sys.argv[1:].
"""
args = parse_args(argv)
logging.basicConfig(level=logging.INFO,
format="%(levelname)-5s %(message)s")
if args.command == "send_pubkey":
return cmd_send_pubkey(args, run_command, fetch_bytes)
if args.command == "initialize_yubikey":
if args.dry_run:
print("plan: install gnupg if missing -> check card -> "
"fetch public key from the card's URL -> write "
"gpg-agent.conf (enable-ssh-support) + chmod 700 "
"-> restart gpg-agent")
return EXIT_OK
return initialize_yubikey(home=args.gnupg_home or gnupg_home(),
run_cmd=run_command)
print("gpgtools: YubiKey GPG/SSH helpers")
print(" daedalus gpgtools initialize_yubikey [--dry-run] "
"[--gnupg-home DIR]")
print(" daedalus gpgtools send_pubkey [--yubikey | --url URL | "
"--fingerprint FP | --pubkey LINE] [--no-verify] [--dry-run] "
"you@server")
return EXIT_OK
if __name__ == "__main__":
sys.exit(main())
+688
View File
@@ -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
+1 -1
View File
@@ -34,7 +34,7 @@ def test_app_version_falls_back_to_pyproject(monkeypatch):
raise hello.importlib.metadata.PackageNotFoundError(_name) raise hello.importlib.metadata.PackageNotFoundError(_name)
monkeypatch.setattr(hello.importlib.metadata, "version", not_found) 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): def test_help_exits_zero(capsys):