diff --git a/CHANGELOG.md b/CHANGELOG.md index 14aaddd..49f14de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,15 +8,70 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and ## [Unreleased] -### Added +- Nothing yet. +## [0.9.0] - 2026-11-19 + +### Added in 0.9.0 + +- `gpgtools initialize`: checks that gnupg is ready on this machine + (`gpg --version`) and installs what is missing — the gnupg-only + half of `initialize_yubikey`, with no card expectations. Missing gpg + triggers the same manager detection and sudo install; the check + re-runs once after a successful install. `--dry-run` prints + `already ready` or the install command and changes nothing. Intended + as the on-site companion to `store_publickey --fingerprint` on a + bare server. Spec section 12 written first, then tests, then code + (SPEC 6.12); `initialize_yubikey` step 1 now runs the same shared + flow instead of its own inline copy. + +## [0.8.0] - 2026-11-19 + +### Added in 0.8.0 + +- `gpgtools store_publickey`: the on-site bootstrap mirror of + `send_pubkey`. Run on the machine that access is being granted + **to** (a server with ssh password authentication disabled, no key + there yet, you at its console), it resolves one SSH public key and + appends it to this machine's `authorized_keys` — so the machine + holding the YubiKey can ssh in afterwards. Same five sources as + `send_pubkey`; by design there is no proof-of-possession (the + private half is elsewhere). Existing entries preserved verbatim, + idempotent by key material, `~/.ssh`/file modes forced to 700/600, + `--authorized-keys` override, `--dry-run`. Spec section 11 written + first, then tests, then code (SPEC 6.12). +- New shared source `--file PATH` for both `send_pubkey` and + `store_publickey`: a file holding the SSH public key line, + typically `yubikey_auth.pub` carried on a USB stick — no network, + no gpg needed. Several keys in one file refuse rather than guess. +- Both resolve-and-store subcommands now print an identity block (key + line, source, and the key material's SHA-256 digest) before acting, + so what was resolved can be compared across machines. + +## [0.7.0] - 2026-11-19 + +### Added in 0.7.0 + +- `gpgtools configure_ssh` (guide step 7): writes a marker-managed + `Host ` block into the ssh client config — YubiKey identity + first, fallback identity only when it exists, `IdentitiesOnly yes`. + Idempotent (re-runs replace the block; everything outside the + markers is preserved), `--dry-run`, and a guard that refuses when an + unmanaged `Host` with the same alias would shadow the block. Spec + items 2.5 and 10 written first, then tests, then code (SPEC 6.12). - Per-script local specs (SPEC items 6.11, 6.12): every script gets a spec that completely describes it — `spec.md` in a Python script's folder, `.spec.md` beside bash/PowerShell/batch scripts — in the sectionized format of SPEC.md. Script work is spec first, then - tests, then code (SPEC item 6.12). First specs added: + tests, then code. First specs added: `gpgtools`, `hello`, `hello_bash`. +### Fixed in 0.7.0 + +- Test fixtures no longer carry private values: the real server IP, + host alias, card serial, and public key fingerprint were replaced + with documentation-range placeholders. + ## [0.6.0] - 2026-11-18 ### Added in 0.6.0 diff --git a/README.md b/README.md index fb9ce55..b8496f2 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ daedalus --list # list everything | 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) | +| `gpgtools` | Python | gpg | YubiKey GPG/SSH helpers: initialize (gnupg readiness check + install), initialize_yubikey (fresh machine, steps 1-4), send_pubkey (resolve key, verify possession, append to a server), store_publickey (install the key from the machine being granted access), configure_ssh (marker-managed per-host ssh block) | | `hello` | Python | test | Prints a hello line and the daedalus version | | `hello_bash` | Bash | test | Sample bash script through the shared help() interface | @@ -36,11 +36,30 @@ table, and each description wrapped under each row. ### gpgtools +`initialize` checks that gnupg is ready on this machine and installs +what is missing — the gnupg-only half of `initialize_yubikey`, with no +card expectations. Its use is on-site: on a bare server where you are +about to run `store_publickey --fingerprint`, this is the command that +makes the gpg-dependent sources work. + +```bash +daedalus gpgtools initialize # check gnupg, install when missing +daedalus gpgtools initialize --dry-run # already ready, or the install command +``` + +| Argument | Default | Meaning | +| --- | --- | --- | +| `--dry-run` | off | Print what would happen (already ready or the install command); change nothing | + +Exit codes: `0` gnupg ready (installed or already present), `2` package +install failed or gpg still unusable after it, `3` gpg missing and no +known package manager. + `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. +write the gpg-agent SSH config. Steps 5-7 are per-server and covered +by the subcommands below. ```bash daedalus gpgtools # overview of the subcommands @@ -58,7 +77,7 @@ 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 +public key from one of five 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, @@ -69,6 +88,7 @@ daedalus gpgtools send_pubkey --yubikey you@server daedalus gpgtools send_pubkey --fingerprint you@server daedalus gpgtools send_pubkey --url https://keys.openpgp.org/vks/v1/by-fingerprint/ you@server daedalus gpgtools send_pubkey --pubkey "ssh-ed25519 AAAA... comment" you@server +daedalus gpgtools send_pubkey --file /media/usb/yubikey_auth.pub you@server daedalus gpgtools send_pubkey --yubikey --dry-run you@server # resolve only ``` @@ -78,6 +98,7 @@ daedalus gpgtools send_pubkey --yubikey --dry-run you@server # resolve only | `--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 | +| `--file PATH` | — | File holding the key line, e.g. a `.pub` from a USB stick (no network, no gpg) | | `--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 | @@ -85,6 +106,58 @@ Additional exit codes: `7` ssh to the target failed, `8` no source resolved a key, `10` proof-of-possession verification failed (nothing was sent). +`store_publickey` is the mirror for the on-site bootstrap: run it on +the machine that access is being granted *to* — a server with ssh +password authentication disabled that no key authorizes yet, where +you are logged in at the console. It resolves the same five sources +and appends the key into this machine's `authorized_keys`, so the +machine holding the YubiKey can ssh in afterwards. There is no +proof-of-possession (the private half is, by design, elsewhere); +instead both resolve-and-store subcommands print an identity block — +line, source, and the key material's SHA-256 — to compare across +machines. Existing entries are preserved, nothing is duplicated, and +directory/file modes are forced to 700/600. + +```bash +daedalus gpgtools store_publickey --file /media/usb/yubikey_auth.pub +daedalus gpgtools store_publickey --fingerprint +daedalus gpgtools store_publickey --pubkey "ssh-ed25519 AAAA... comment" +daedalus gpgtools store_publickey --file /media/usb/yubikey_auth.pub --dry-run # print only +``` + +| Argument | Default | Meaning | +| --- | --- | --- | +| sources | — | Same five sources as `send_pubkey` (exactly one required) | +| `--authorized-keys FILE` | `~/.ssh/authorized_keys` | Where to install the key | +| `--dry-run` | off | Resolve and print the key; write nothing | + +Additional exit codes: `8` no source resolved a key. + +`configure_ssh` covers guide step 7 for one host: it writes a +marker-managed `Host ` block into the ssh client config. +Outside the markers your config is preserved byte-for-byte; re-runs +replace the block (idempotent), and an unmanaged `Host` with the same +alias is refused rather than shadowed. It never connects anywhere. + +```bash +daedalus gpgtools configure_ssh --alias vault1 --hostname 203.0.113.10 --user admin +daedalus gpgtools configure_ssh --alias vault1 --dry-run # print only +daedalus gpgtools configure_ssh --alias vault1 --no-fallback # YubiKey only +``` + +| Argument | Default | Meaning | +| --- | --- | --- | +| `--alias NAME` | required | The ssh Host alias to configure | +| `--hostname HOST` | the alias | HostName value | +| `--user USER` | ssh's default | User value | +| `--pubkey FILE` | `~/.ssh/yubikey_auth.pub` | Primary IdentityFile (must exist) | +| `--fallback FILE` | `~/.ssh/id_ed25519` | Fallback IdentityFile, included only when it exists | +| `--no-fallback` | off | Never add a fallback IdentityFile | +| `--config PATH` | `~/.ssh/config` | Which ssh client config to edit | + +Additional exit code: `11` an unmanaged `Host ` exists in the +config (move it into the managed markers or rename the alias). + ## Shell completion Bash (and other shells argcomplete supports) completes script names and diff --git a/daedalus/registry.py b/daedalus/registry.py index 4caebc1..fda868a 100644 --- a/daedalus/registry.py +++ b/daedalus/registry.py @@ -56,7 +56,7 @@ class 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)", + description="YubiKey GPG/SSH helpers: initialize (gnupg readiness check + install), initialize_yukikey (fresh machine, steps 1-4), send_pubkey (resolve key, verify possession, append to a server), store_publickey (install the key from the machine being granted access), configure_ssh (marker-managed per-host ssh block)", categories="gpg", ), "hello": Script( diff --git a/daedalus/tests/test_cli.py b/daedalus/tests/test_cli.py index 393559f..d018823 100644 --- a/daedalus/tests/test_cli.py +++ b/daedalus/tests/test_cli.py @@ -150,7 +150,7 @@ def test_path_with_extra_words_is_a_usage_error(fake_registry, plain, capsys): assert "usage: daedalus --path " in capsys.readouterr().err -@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.6.0")]) +@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.9.0")]) def test_version(monkeypatch, capsys, installed, expected): """--version uses metadata or pyproject.toml in a checkout.""" def fake_version(_name): diff --git a/pyproject.toml b/pyproject.toml index f545863..013f1e7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "daedalus" -version = "0.6.0" +version = "0.9.0" description = "Template for daedalus: loose scripts in one repo, run with: daedalus [args...]" readme = "README.md" requires-python = ">=3.11" diff --git a/python/src/gpgtools/gpgtools.py b/python/src/gpgtools/gpgtools.py index 8a9dfb3..a3043ec 100644 --- a/python/src/gpgtools/gpgtools.py +++ b/python/src/gpgtools/gpgtools.py @@ -4,10 +4,12 @@ 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 +steps 5-6 for one server: resolve the SSH public key from one of +five sources, prove possession of the private half with a challenge signature, then append the line to the target's -authorized_keys. +authorized_keys. ``store_publickey`` is the mirror for the +on-site bootstrap: run on the machine access is being granted +to, it installs the key into the local authorized_keys. Run via daedalus: ``daedalus gpgtools initialize_yukikey`` or ``daedalus gpgtools send_pubkey --yubikey you@server``. @@ -16,6 +18,7 @@ from __future__ import annotations import argparse import dataclasses +import hashlib import logging import os import pathlib @@ -44,12 +47,16 @@ EXIT_NO_URL = 6 EXIT_TARGET = 7 EXIT_NO_KEY = 8 EXIT_VERIFY_FAILED = 10 +EXIT_ALIAS_CONFLICT = 11 SENT_APPENDED = 0 SENT_PRESENT = 1 VERIFY_NAMESPACE = "daedalus-gpgtools" +MANAGED_BEGIN = "# BEGIN daedalus gpgtools: {alias}" +MANAGED_END = "# END daedalus gpgtools: {alias}" + MANAGER_COMMANDS = { "apt-get": ["sudo", "apt-get", "install", "-y", "gnupg"], "dnf": ["sudo", "dnf", "install", "-y", "gnupg2"], @@ -186,6 +193,81 @@ def run_command(cmd: list[str], input_text: str = "", return result.returncode, (result.stdout or "") + (result.stderr or "") +def ensure_gnupg(run_cmd) -> int: + """Check gnupg is ready; when missing, install it (item 12.1). + + Readiness is `gpg --version`. A missing gpg triggers manager + detection and the sudo install; the check re-runs once after + a successful install. + + Args: + run_cmd: command runner; injected by tests. + + Returns: + EXIT_OK ready (or installed and re-checked), 2 install + failed or still unusable, 3 no known package manager. + """ + code, output = run_cmd(["gpg", "--version"]) + if code == 0: + LOGGER.info("gnupg ready: %s", output.splitlines()[0].strip()) + return EXIT_OK + 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", "--version"]) + if code != 0: + LOGGER.error("gnupg still not usable after install: %s", + output.strip()) + return EXIT_INSTALL_FAILED + LOGGER.info("gnupg ready: %s", output.splitlines()[0].strip()) + return EXIT_OK + + +def cmd_initialize(args: argparse.Namespace, run_cmd=None) -> int: + """initialize subcommand (gpgtools spec section 12). + + The gnupg-only half of initialize_yubikey: check readiness, + install what is missing. No card, keyring, or agent + expectations - the on-site companion to store_publickey + (item 12.4). + + Args: + args: parsed arguments (dry_run). + run_cmd: command runner; defaults to run_command. + + Returns: + EXIT_OK, EXIT_INSTALL_FAILED, or EXIT_NO_GPG. A dry run + always exits 0. + """ + if run_cmd is None: + run_cmd = run_command + if args.dry_run: + code, output = run_cmd(["gpg", "--version"]) + if code == 0: + print("dry run: gnupg already ready: " + + output.splitlines()[0].strip()) + else: + manager = detect_package_manager() + command = manager and install_command(manager) + if command is None: + print("dry run: gpg missing and no known package " + "manager; install gnupg manually") + else: + print("dry run: gpg missing; would install via: " + + " ".join(command) + + "; then re-check gpg --version") + return EXIT_OK + return ensure_gnupg(run_cmd) + + def initialize_yubikey(home: pathlib.Path, run_cmd=None) -> int: """Bring a fresh machine to 'ready for GPG' state (steps 1-4). @@ -201,19 +283,9 @@ def initialize_yubikey(home: pathlib.Path, """ 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 = ensure_gnupg(run_cmd) + if code != EXIT_OK: + return code code, output = run_cmd(["gpg", "--card-status"]) info = parse_card_status(output) if not info.present: @@ -369,6 +441,76 @@ def source_pubkey(line: str) -> tuple[str, str]: return line.strip(), "literal --pubkey" +def source_file(path) -> tuple[str, str]: + """Resolve the SSH public key line from a file (item 4.1.5). + + Typically a `.pub` file carried on a USB stick; needs no + network and no gpg. Refuses rather than guess when the file + holds several keys. + + Args: + path: file holding the key line. + + Returns: + (ssh public key line, the path as source description). + + Raises: + SendPubkeyError: unreadable file, no valid key line, or + several valid lines. + """ + try: + text = pathlib.Path(path).read_text(encoding="utf-8") + except OSError as err: + raise SendPubkeyError(f"could not read key file {path}: {err}") + valid = [line.strip() for line in text.splitlines() + if validate_pubkey_line(line)] + if not valid: + raise SendPubkeyError(f"no valid ssh public key line in {path}") + if len(valid) > 1: + raise SendPubkeyError(f"several keys in {path}; pass the exact " + "line with --pubkey:\n" + "\n".join(valid)) + return valid[0], str(path) + + +def resolve_source(args: argparse.Namespace, run_cmd, + fetch) -> tuple[str, str]: + """Return (key line, source) for whichever source flag was set. + + Shared by send_pubkey and store_publickey (items 4.1.1-4.1.5). + + Args: + args: parsed arguments with the source flags. + run_cmd: command runner. + fetch: ``(url) -> bytes | None`` fetcher. + + Returns: + (ssh public key line, source description). + + Raises: + SendPubkeyError: the picked source failed; the caller + reports it as EXIT_NO_KEY. + """ + if args.yubikey: + return source_yubikey(run_cmd) + if args.url: + return source_url(args.url, run_cmd, fetch) + if args.fingerprint: + return source_fingerprint(args.fingerprint, run_cmd, fetch) + if args.file: + return source_file(args.file) + return source_pubkey(args.pubkey) + + +def material_digest(line: str) -> str: + """SHA-256 hex digest of the key material (item 11.4). + + Comments are annotations (item 4.3), so the digest is the + key's identity across machines and sources. + """ + return hashlib.sha256(_key_material(line.strip()) + .encode("utf-8")).hexdigest() + + 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. @@ -567,20 +709,13 @@ def cmd_send_pubkey(args: argparse.Namespace, run_cmd=None, 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) + line, source = resolve_source(args, run_cmd, fetch) except SendPubkeyError as err: LOGGER.error("%s", err) return EXIT_NO_KEY print(f"public key : {line}") print(f"source : {source}") + print(f"material sha256: {material_digest(line)}") print(f"target : {args.target}") if args.dry_run: print("dry run: nothing verified, nothing sent") @@ -609,6 +744,238 @@ def cmd_send_pubkey(args: argparse.Namespace, run_cmd=None, return EXIT_OK +def store_key(line: str, target: pathlib.Path) -> bool: + """Append one public key line to this machine's authorized_keys. + + Idempotence by key material (comments ignored); existing + entries are preserved verbatim. Enforces dir 700 / file 600 + on every write (spec items 11.5-11.6). + + Args: + line: validated ssh public key line. + target: authorized_keys path to write. + + Returns: + True when appended, False when the material was present. + """ + material = _key_material(line.strip()) + existing = target.read_text(encoding="utf-8") if target.exists() else "" + rows = [_key_material(row) for row in existing.splitlines()] + if material in rows: + return False + if existing and not existing.endswith("\n"): + existing += "\n" # never glue two keys into one line + target.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + target.parent.chmod(0o700) + target.write_text(existing + line.strip() + "\n", encoding="utf-8") + target.chmod(0o600) + return True + + +def cmd_store_publickey(args: argparse.Namespace, run_cmd=None, + fetch=None) -> int: + """store_publickey subcommand (gpgtools spec section 11). + + Resolves one SSH public key and installs it into this + machine's authorized_keys - the on-site bootstrap mirror of + send_pubkey. No proof of possession (item 11.3): the private + half is intentionally elsewhere. + + Args: + args: parsed arguments (source, authorized_keys, dry_run). + run_cmd: command runner; defaults to run_command. + fetch: ``(url) -> bytes | None``; defaults to fetch_bytes. + + Returns: + Exit code (EXIT_OK stored or already present, + EXIT_NO_KEY source unresolvable). + """ + if run_cmd is None: + run_cmd = run_command + if fetch is None: + fetch = fetch_bytes + try: + line, source = resolve_source(args, run_cmd, fetch) + except SendPubkeyError as err: + LOGGER.error("%s", err) + return EXIT_NO_KEY + target = (args.authorized_keys + or pathlib.Path.home() / ".ssh" / "authorized_keys") + existing = target.read_text(encoding="utf-8") if target.exists() else "" + present = _key_material(line.strip()) in [ + _key_material(row) for row in existing.splitlines()] + print(f"public key : {line}") + print(f"source : {source}") + print(f"material sha256: {material_digest(line)}") + print(f"target : {target}") + if args.dry_run: + print("dry run: " + ("already present" if present else "creating")) + return EXIT_OK + if not store_key(line, target): + print(f"key already present in {target}; nothing changed") + return EXIT_OK + print(f"appended the public key to {target}; machines holding " + "the YubiKey can now ssh in") + return EXIT_OK + + +def build_block(alias: str, hostname: str, user: str | None, + pubkey: str, fallback: str | None) -> str: + """Build the marker-managed Host block for one alias. + + Args: + alias: ssh Host alias. + hostname: HostName value. + user: User value, or None to let ssh default it. + pubkey: primary IdentityFile (the YubiKey public key). + fallback: fallback IdentityFile, or None. + + Returns: + Full block text including begin/end markers. + """ + lines = [MANAGED_BEGIN.format(alias=alias), + f"Host {alias}", + f" HostName {hostname}"] + if user: + lines.append(f" User {user}") + lines.append(f" IdentityFile {pubkey}") + if fallback: + lines.append(f" IdentityFile {fallback}") + lines.append(" IdentitiesOnly yes") + lines.append(MANAGED_END.format(alias=alias)) + return "\n".join(lines) + "\n" + + +def merge_managed_block(existing: str, alias: str, + block: str) -> str: + """Insert or replace alias's managed block, preserving the rest. + + Args: + existing: current config text ("" when absent). + alias: the block's alias. + block: new full block (with markers, from build_block). + + Returns: + New config text: block replaced in place when the + markers exist, appended otherwise; everything outside + the markers byte-preserved. + """ + begin = MANAGED_BEGIN.format(alias=alias) + end = MANAGED_END.format(alias=alias) + lines = existing.splitlines() + if begin in lines: + start = lines.index(begin) + if end in lines[start:]: + stop = lines.index(end, start) + 1 + else: + stop = len(lines) + merged = lines[:start] + block.splitlines() + lines[stop:] + return "\n".join(merged) + "\n" + if not existing.strip(): + return block + return existing.rstrip("\n") + "\n" + block + + +def unmanaged_alias_exists(existing: str, alias: str) -> bool: + """True when a Host line names alias outside the managed block. + + Args: + existing: current config text. + alias: the alias to guard. + + Returns: + True when ssh could let that line shadow the block. + """ + begin = MANAGED_BEGIN.format(alias=alias) + end = MANAGED_END.format(alias=alias) + inside = False + for line in existing.splitlines(): + stripped = line.strip() + if stripped == begin: + inside = True + continue + if stripped == end: + inside = False + continue + if inside: + continue + if stripped.startswith("Host "): + if alias in stripped.split()[1:]: + return True + return False + + +def cmd_configure_ssh(args: argparse.Namespace) -> int: + """configure_ssh subcommand (gpgtools spec items 10.1-10.7). + + Args: + args: parsed arguments (alias, hostname, user, pubkey, + fallback, no_fallback, config, dry_run). + + Returns: + EXIT_OK, EXIT_NO_KEY, or EXIT_ALIAS_CONFLICT. + """ + home = pathlib.Path.home() + pubkey = args.pubkey or home / ".ssh" / "yubikey_auth.pub" + if not pubkey.exists(): + LOGGER.error("public key not found: %s; derive it with " + "ssh-add -L > ~/.ssh/yubikey_auth.pub " + "(gpgtools spec item 10.5)", pubkey) + return EXIT_NO_KEY + fallback = None + if not args.no_fallback: + fallback = args.fallback or home / ".ssh" / "id_ed25519" + if fallback and not fallback.exists(): + if args.fallback: + LOGGER.warning("fallback %s does not exist; " + "omitted", fallback) + fallback = None + hostname = args.hostname or args.alias + block = build_block(args.alias, hostname, args.user, + str(pubkey), str(fallback) if fallback else None) + config = args.config or home / ".ssh" / "config" + existing = config.read_text(encoding="utf-8") if config.exists() else "" + action = ("replacing" if MANAGED_BEGIN.format(alias=args.alias) + in existing else "creating") + if args.dry_run: + print(block) + print(f"dry run: {action} managed block for {args.alias} " + f"in {config}") + return EXIT_OK + if unmanaged_alias_exists(existing, args.alias): + LOGGER.error("an unmanaged 'Host %s' exists in %s; move it " + "into the managed markers or rename the alias " + "(gpgtools spec item 10.5)", args.alias, config) + return EXIT_ALIAS_CONFLICT + config.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + created = not config.exists() + config.write_text(merge_managed_block(existing, args.alias, + block), encoding="utf-8") + if created: + config.chmod(0o600) + print(f"{action} managed block for {args.alias} in {config}") + return EXIT_OK + + +def _add_source_flags(subparser: argparse.ArgumentParser) -> None: + """Add the five key-source flags (items 4.1.1-4.1.5, item 2.6).""" + sources = subparser.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") + sources.add_argument("--file", metavar="PATH", type=pathlib.Path, + help="file holding the ssh public key line " + "(e.g. a .pub from a USB stick)") + + def parse_args(argv: list[str] | None) -> argparse.Namespace: """Parse gpgtools command-line arguments.""" parser = argparse.ArgumentParser( @@ -626,24 +993,22 @@ def parse_args(argv: list[str] | None) -> argparse.Namespace: init.add_argument("--gnupg-home", type=pathlib.Path, default=None, help="GnuPG home to configure " "(default GNUPGHOME or ~/.gnupg)") + check = subparsers.add_parser( + "initialize", + help="check that gnupg is ready on this machine and " + "install what is missing (no card needed; useful " + "before store_publickey on-site)", + ) + check.add_argument("--dry-run", action="store_true", + help="print what would happen (already ready " + "or the install command), change nothing") 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") + _add_source_flags(send) send.add_argument("--no-verify", action="store_true", help="skip the proof-of-possession signature " "(explicit risk acceptance)") @@ -652,6 +1017,42 @@ def parse_args(argv: list[str] | None) -> argparse.Namespace: "nothing") send.add_argument("target", metavar="you@server", help="ssh target that receives the key") + store = subparsers.add_parser( + "store_publickey", + help="resolve an SSH public key and install it into THIS " + "machine's authorized_keys (on-site bootstrap; the " + "machine holding the YubiKey can then ssh in)", + ) + _add_source_flags(store) + store.add_argument("--authorized-keys", type=pathlib.Path, + default=None, + help="authorized_keys path (default " + "~/.ssh/authorized_keys)") + store.add_argument("--dry-run", action="store_true", + help="resolve and print the key, write nothing") + conf = subparsers.add_parser( + "configure_ssh", + help="write the per-host ssh client block (guide step 7); " + "marker-managed and idempotent", + ) + conf.add_argument("--alias", required=True, + help="ssh Host alias to configure") + conf.add_argument("--hostname", default=None, + help="HostName value (default: the alias)") + conf.add_argument("--user", default=None, + help="User value (default: ssh's own default)") + conf.add_argument("--pubkey", type=pathlib.Path, default=None, + help="primary IdentityFile (default " + "~/.ssh/yubikey_auth.pub)") + conf.add_argument("--fallback", type=pathlib.Path, default=None, + help="fallback IdentityFile (default " + "~/.ssh/id_ed25519 when it exists)") + conf.add_argument("--no-fallback", action="store_true", + help="never add a fallback IdentityFile") + conf.add_argument("--config", type=pathlib.Path, default=None, + help="ssh config path (default ~/.ssh/config)") + conf.add_argument("--dry-run", action="store_true", + help="print the block, write nothing") if autocomplete is not None: # pragma: no cover - needs argcomplete autocomplete(parser) return parser.parse_args(argv) @@ -668,6 +1069,12 @@ def main(argv: list[str] | None = None) -> int: format="%(levelname)-5s %(message)s") if args.command == "send_pubkey": return cmd_send_pubkey(args, run_command, fetch_bytes) + if args.command == "store_publickey": + return cmd_store_publickey(args, run_command, fetch_bytes) + if args.command == "configure_ssh": + return cmd_configure_ssh(args) + if args.command == "initialize": + return cmd_initialize(args, run_command) if args.command == "initialize_yubikey": if args.dry_run: print("plan: install gnupg if missing -> check card -> " @@ -678,11 +1085,17 @@ def main(argv: list[str] | None = None) -> int: return initialize_yubikey(home=args.gnupg_home or gnupg_home(), run_cmd=run_command) print("gpgtools: YubiKey GPG/SSH helpers") + print(" daedalus gpgtools initialize [--dry-run]") 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") + "--fingerprint FP | --pubkey LINE | --file PATH] [--no-verify] " + "[--dry-run] you@server") + print(" daedalus gpgtools store_publickey [--yubikey | --url URL | " + "--fingerprint FP | --pubkey LINE | --file PATH] " + "[--authorized-keys FILE] [--dry-run]") + print(" daedalus gpgtools configure_ssh --alias NAME " + "[--hostname HOST] [--user USER] [--dry-run]") return EXIT_OK diff --git a/python/src/gpgtools/spec.md b/python/src/gpgtools/spec.md index 3a58ff7..2301871 100644 --- a/python/src/gpgtools/spec.md +++ b/python/src/gpgtools/spec.md @@ -15,6 +15,9 @@ Items are cited as `gpgtools spec item N.M`. - [7. Files written](#7-files-written) - [8. Testing approach](#8-testing-approach) - [9. References](#9-references) +- [10. configure_ssh behavior](#10-configure_ssh-behavior) +- [11. store_publickey behavior](#11-store_publickey-behavior) +- [12. initialize behavior](#12-initialize-behavior) @@ -25,7 +28,10 @@ Items are cited as `gpgtools spec item N.M`. (`~/repositories/vibe-wiki/wiki/queries/yubikey-ssh-guide.md`): `initialize_yubikey` covers guide steps 1-4 (fresh machine ready for GPG), `send_pubkey` covers steps 5-6 (key to a server). - Guide step 7 (per-host `~/.ssh/config`) is out of scope. + `store_publickey` covers the on-site bootstrap case (section 11): + installing the key from the machine that access is being + granted to. Guide step 7 (per-host `~/.ssh/config`) is out of + scope. - **1.2** Hard constraint: the YubiKey's OpenPGP applet is never written - no `gpg --card-edit`, no `keytocard`, no applet reset. Only public card data is read; the card PIN is typed by its @@ -38,26 +44,43 @@ Items are cited as `gpgtools spec item N.M`. ## 2. Commands - **2.1** `daedalus gpgtools` with no subcommand prints the - overview of both subcommands and exits 0. + overview of the subcommands and exits 0. - **2.2** `daedalus gpgtools initialize_yubikey [--dry-run] [--gnupg-home DIR]` - prepares this machine (section 3). - **2.3** `daedalus gpgtools send_pubkey - (--yubikey | --url URL | --fingerprint FP | --pubkey LINE) + (--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH) [--no-verify] [--dry-run] you@server` - resolves one SSH public key, proves possession of the private half, appends it - to the target (section 4). The four source flags are mutually + to the target (section 4). The five source flags are mutually exclusive and exactly one is required; `you@server` is required. - **2.4** `--dry-run` on either subcommand prints what would happen and writes nothing; on `send_pubkey` it resolves and prints the key but never verifies and never connects. +- **2.5** `daedalus gpgtools configure_ssh --alias NAME + [--hostname HOST] [--user USER] [--pubkey FILE] + [--fallback FILE | --no-fallback] [--config PATH] [--dry-run]` + - writes the per-host ssh client block (guide step 7); + behavior in section 10. +- **2.6** `daedalus gpgtools store_publickey + (--yubikey | --url URL | --fingerprint FP | --pubkey LINE | --file PATH) + [--authorized-keys FILE] [--dry-run]` - resolves one SSH + public key and installs it into *this* machine's + authorized_keys (section 11). The source flags are the + send_pubkey set (items 4.1.1-4.1.5), mutually exclusive, + exactly one required. +- **2.7** `daedalus gpgtools initialize [--dry-run]` - checks + that gnupg is ready on this machine and installs what is + missing; the gnupg-only half of initialize_yubikey + (section 12). ## 3. initialize_yubikey behavior -- **3.1** Step 1 - gnupg: `gpg --version`. When it fails, the - package manager is detected (`shutil.which` over apt-get, dnf, - pacman) and gnupg installed via `sudo`; no known manager is - exit 3. A failed install is exit 2. +- **3.1** Step 1 - gnupg: the section 12 flow (item 12.1). When + `gpg --version` fails, the package manager is detected + (`shutil.which` over apt-get, dnf, pacman) and gnupg installed + via `sudo`; no known manager is exit 3. A failed install is + exit 2. - **3.2** Step 2 - card: `gpg --card-status` parsed for the `Application type`/`OpenPGP` markers; absent card (including gpg error text) is exit 4 with the pcscd hint @@ -101,6 +124,13 @@ Items are cited as `gpgtools spec item N.M`. All exhausted is exit 8 naming the stores. - **4.1.4** `--pubkey`: the literal line, validated by item 4.2; exit 8 when invalid. + - **4.1.5** `--file PATH`: a file holding the SSH public key + line - typically `yubikey_auth.pub` carried on a USB stick + (zero network, zero gpg). Every line is validated per item + 4.2: no valid line is exit 8; several valid lines refuse + listing them with the `--pubkey` hint (item 4.1.1 + precedent) rather than guessing; an unreadable or missing + file is exit 8. - **4.2** Key line validation: `ssh-(ed25519|rsa|dss|ecdsa-sha2-*) [comment]`, full line; anything else is rejected. - **4.3** Key material (type + base64, comment ignored) is the @@ -128,20 +158,26 @@ Items are cited as `gpgtools spec item N.M`. credentials (agent, passphrase-less key, or ControlMaster socket). First contact to a brand-new server by password is out of scope - gain access once manually, then send the key. +- **4.8** Output (identical in section 11): both resolve-and-store + subcommands print the resolved key line, its source, and the + SHA-256 hex digest of the key material (item 4.3) before + acting, so the resolved value can be compared with the machine + the key came from (or read over a phone). ## 5. Exit codes | Code | Meaning | | --- | --- | | 0 | success (initialize ready; send appended or already present) | -| 2 | package install failed (initialize) | -| 3 | gpg missing and no known package manager (initialize) | +| 2 | package install failed (initialize, initialize_yubikey) | +| 3 | gpg missing and no known package manager (initialize, initialize_yubikey) | | 4 | no OpenPGP card found (initialize) | | 5 | public-key fetch did not pair the keyring (initialize) | | 6 | keyring unpaired and the card carries no URL (initialize) | | 7 | ssh to the target failed; nothing stored (send) | -| 8 | no source resolved a usable key (send) | +| 8 | no source resolved a usable key (send, store); pubkey file missing (configure) | | 10 | proof-of-possession verification failed; nothing sent (send) | +| 11 | an unmanaged `Host ` exists in the config (configure) | ## 6. Runner contract and injectability @@ -169,6 +205,10 @@ Items are cited as `gpgtools spec item N.M`. workspace) are created under the system temp dir and removed in `finally`. The only persistent write is the target's `authorized_keys` append via ssh (item 4.6). +- **7.3** store: the local `authorized_keys` (item 11.5) is the + only persistent write; its parent gets mode 700, the file 600. + Scratch rules of item 7.2 apply when remote sources resolve + (item 4.5). ## 8. Testing approach @@ -180,10 +220,13 @@ Items are cited as `gpgtools spec item N.M`. no URL, no auth subkey, unpaired), config merge (empty, preserving, complete), manager mapping and detection, GNUPGHOME resolution, the initialize flow's success, failure, - warning, and persistence branches, the four sources including - the store chain and fingerprint mismatch, challenge - sign/verify success and refusal, send idempotence by material, - and the CLI wiring, guards, and dry runs. + warning, and persistence branches and the standalone + readiness/install/re-check branches (section 12), the five + sources including the store chain and fingerprint mismatch, + challenge sign/verify success and refusal, send idempotence by + material, store: file sources, append, preservation, + idempotence, perms, dry run, and the CLI wiring, guards, and + dry runs. - **8.3** The change order is spec item 6.12: this spec first, then failing tests, then the smallest implementation. @@ -194,4 +237,105 @@ Items are cited as `gpgtools spec item N.M`. (steps 1-13; automation notes in section 13). - **9.2** Repository rules: SPEC items 6.6 (tests), 6.9 (argcomplete opt-in after the parser), 9.8 (version bump). -- **9.3** History: `CHANGELOG.md` entries 0.5.0 and 0.6.0. +- **9.3** History: `CHANGELOG.md` entries 0.5.0, 0.6.0 + (initialize/send), 0.7.0 (configure_ssh), 0.8.0 + (--file source, store_publickey), 0.9.0 (initialize). + +## 10. configure_ssh behavior + +- **10.1** The block is written into `--config` (default + `~/.ssh/config`) between managed markers, one block per alias: + +```text +# BEGIN daedalus gpgtools: +Host + HostName + User (omitted without --user) + IdentityFile + IdentityFile (omitted per item 10.4) + IdentitiesOnly yes +# END daedalus gpgtools: +``` + +- **10.2** Defaults: `--hostname` defaults to the alias itself; + `--pubkey` defaults to `~/.ssh/yubikey_auth.pub`; + `--fallback` defaults to `~/.ssh/id_ed25519`. +- **10.3** Idempotence: a run that finds the alias's markers + replaces the whole marked block with the newly built one; + everything outside the markers is preserved byte-for-byte. + Running twice with the same arguments changes nothing. +- **10.4** The fallback `IdentityFile` is included only when its + file exists and `--no-fallback` was not given; a missing + explicit `--fallback FILE` logs a warning. +- **10.5** Guards: a `--pubkey` file that does not exist is exit + 8 with the derive hint; a `Host` line naming the same alias + anywhere outside the managed markers is exit 11 (ssh would let + the first match shadow the managed block). +- **10.6** File hygiene: `~/.ssh` is created at mode 700 when + missing; the config file is created at mode 600 when missing. +- **10.7** `--dry-run` prints the block plus + `creating`/`replacing`, and writes nothing. + +## 11. store_publickey behavior + +- **11.1** Installs one SSH public key into the *current user's* + `~/.ssh/authorized_keys` (`--authorized-keys FILE` overrides) + on this machine - the machine the key will later grant access + to. Use case: a server with ssh password authentication + disabled that no key authorizes yet; you are logged in at its + console and install the key from inside, so the machine + holding the YubiKey can ssh in afterwards. It is the mirror of + section 4: send pushes the key from where it is, store pulls + it from where the access is. +- **11.2** Sources: identical to items 4.1.1-4.1.5, one per run. + On a bare server the realistic ones are `--pubkey` (typed at + the console), `--file` (USB stick; needs no network and no + gpg), and `--fingerprint` (store chain, needs gpg and + network); `--yubikey` works when the card is plugged into + this machine. An unresolvable source is exit 8 (item 5). +- **11.3** There is no proof-of-possession step (item 4.4) and + no `--no-verify` flag: the private half is, by design, + elsewhere - this machine is the one being granted access, so + nothing here could sign the challenge. Hardening instead: line + validation (item 4.2), fingerprint-checked stores (item + 4.1.3), and the identity block (item 11.4). +- **11.4** Identity block: the resolved key line, its source, + and the SHA-256 hex digest of the key material (item 4.3) are + printed before writing (shared rule, item 4.8), so the value + can be compared with the machine the key came from. +- **11.5** Storage: the parent directory is created at mode 700 + when missing and the authorized_keys file forced to mode 600, + on every write. Existing entries are preserved verbatim - + authorized_keys is a multi-key file; there is no mismatch + guard on the rest, only the new key's absence is checked. +- **11.6** Idempotence follows item 4.3: the line is appended + only when its material is absent (comments ignored); already + present is reported and exits 0. A missing trailing newline + in an existing file is repaired, never glued into a key line. +- **11.7** `--dry-run` prints the identity block plus + `already present`/`creating` and writes nothing. +- **11.8** No ssh is run and the only persistent write is item + 11.5; remote sources keep item 4.5's throwaway-home rule + (item 7.3). Exit codes: 0 stored or already present, 8 no + source resolved a usable key. + +## 12. initialize behavior + +- **12.1** `initialize` covers the gnupg half of item 3.1 + only - no card, keyring, or agent expectations. `gpg + --version` decides readiness: present prints the version + line and exits 0. Missing runs manager detection and the + `sudo` install (item 3.1's manager map); no known manager is + exit 3, a failed install is exit 2. After a successful + install the check re-runs once - still unusable is exit 2. +- **12.2** `--dry-run` performs only the read-only + `gpg --version`, prints what would happen (`already ready` + with the version line, the install command it would run, or + the install-manually message), installs nothing, and exits 0 + in every dry-run case. +- **12.3** `initialize_yubikey` runs this flow as its step 1 + (item 3.1); a `-2`/`-3` return stops it before anything else. +- **12.4** Intended use: the on-site companion to + store_publickey (item 11) - on a machine without the + YubiKey, run `initialize` first when a gpg-dependent source + (`--fingerprint`, `--url`, `--yubikey`) is wanted. diff --git a/python/tests/test_gpgtools.py b/python/tests/test_gpgtools.py index 8e288fb..0e7fe04 100644 --- a/python/tests/test_gpgtools.py +++ b/python/tests/test_gpgtools.py @@ -5,6 +5,7 @@ Pure functions, main with argument lists, and the full initialize_yukikey flow driven by a fake runner - no hardware, no network, no card (daedalus agent rule 5.6). """ +import hashlib import pathlib import pytest @@ -13,14 +14,14 @@ from daedalus.gpgtools import gpgtools CARD_OK = """ Reader ...........: Yubico YubiKey OTP FIDO CCID 00 00 -Application ID ...: D2760001240100000006385060530000 +Application ID ...: D2760001240100000006054321090000 Application type .: OpenPGP Version ..........: 3.4 -Serial number ....: 38506053 +Serial number ....: 54321098 PIN retry counter : 3 0 3 KDF setting ......: off UIF setting ......: Sign=off Decrypt=off Auth=off -URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/A126 +URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/0123 Signature key ....: F4D1 6935 15EF CB83 Encryption key....: 3DC6 203C F1EE 3F88 Authentication key: CF8B 1604 25DE B2CA @@ -33,7 +34,7 @@ CARD_UNPAIRED = CARD_OK.replace( ) CARD_NO_URL = CARD_UNPAIRED.replace( - "URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/A126", + "URL of public key : https://keys.openpgp.org/vks/v1/by-fingerprint/0123", "URL of public key : [not set]", ) @@ -51,9 +52,9 @@ def test_parse_card_status_reads_present_card(): """A healthy card-status output yields serial, auth key, and URL.""" info = gpgtools.parse_card_status(CARD_OK) assert info.present is True - assert info.serial == "38506053" + assert info.serial == "54321098" assert info.has_auth_subkey is True - assert info.key_url == "https://keys.openpgp.org/vks/v1/by-fingerprint/A126" + assert info.key_url == "https://keys.openpgp.org/vks/v1/by-fingerprint/0123" assert info.keyring_paired is True @@ -208,7 +209,7 @@ def test_initialize_happy_path(tmp_path, happy_runner): assert oct(home.stat().st_mode)[-3:] == "700" fetched = [cmd for cmd in happy_runner.calls if cmd[:2] == ["gpg", "--fetch-keys"]] assert fetched == [["gpg", "--fetch-keys", - "https://keys.openpgp.org/vks/v1/by-fingerprint/A126"]] + "https://keys.openpgp.org/vks/v1/by-fingerprint/0123"]] killed = [cmd for cmd in happy_runner.calls if cmd[:2] == ["gpgconf", "--kill"]] assert killed == [["gpgconf", "--kill", "gpg-agent"]] @@ -313,7 +314,7 @@ def test_main_help_exits_zero(): # --- send_pubkey: validation, sources, verification, sending -FP = "A126B97CB5A18E923DE2A4FF23B8D25BC4A17EAB" +FP = "0123456789ABCDEF0123456789ABCDEF01234567" GOOD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEXAMPLEBASE64KEY daedalus-test" OTHER_KEY = "ssh-rsa AAAAB3NzaC1yc2E someone-else" CANDIDATE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICANDIDATEKEY candidate" @@ -349,7 +350,7 @@ def test_validate_pubkey_line(): def test_normalize_fingerprint(): """Fingerprints normalize: lower, spaced, 0x-prefixed all work.""" - spaced = "a126 b97c b5a1 8e92 3de2 a4ff 23b8 d25b c4a1 7eab" + spaced = "0123 4567 89ab cdef 0123 4567 89ab cdef 0123 4567" assert gpgtools.normalize_fingerprint(spaced) == FP assert gpgtools.normalize_fingerprint("0x" + FP.lower()) == FP assert gpgtools.normalize_fingerprint(FP) == FP @@ -686,3 +687,526 @@ def test_cmd_send_pubkey_blocked_by_verification(tmp_path, capsys): assert code == gpgtools.EXIT_VERIFY_FAILED assert not any(cmd and cmd[0] == "ssh" for cmd in calls) assert "no private key" in capsys.readouterr().out + + +# --- --file source (gpgtools spec item 4.1.5) and the 4.8 output + + +def test_source_file_reads_the_key_line(tmp_path): + """--file yields the key line from a carried .pub file.""" + path = tmp_path / "yubikey_auth.pub" + path.write_text(GOOD_KEY + "\n", encoding="utf-8") + line, source = gpgtools.source_file(path) + assert line == GOOD_KEY + assert str(path) in source + + +def test_source_file_missing(tmp_path): + """A missing key file is a source error naming the file.""" + with pytest.raises(gpgtools.SendPubkeyError) as err: + gpgtools.source_file(tmp_path / "nope.pub") + assert "nope.pub" in str(err.value) + + +def test_source_file_without_any_key(tmp_path): + """A file with no valid key line is refused.""" + path = tmp_path / "notes.txt" + path.write_text("just some text\n", encoding="utf-8") + with pytest.raises(gpgtools.SendPubkeyError): + gpgtools.source_file(path) + + +def test_source_file_several_keys_refuses(tmp_path): + """Several keys refuse with the list and the --pubkey hint.""" + path = tmp_path / "keys.pub" + path.write_text(GOOD_KEY + "\n" + OTHER_KEY + "\n", encoding="utf-8") + with pytest.raises(gpgtools.SendPubkeyError) as err: + gpgtools.source_file(path) + assert "--pubkey" in str(err.value) + assert GOOD_KEY in str(err.value) + + +def test_material_digest_ignores_comments(): + """The SHA-256 material digest is identity, comments are not.""" + digest = hashlib.sha256( + " ".join(GOOD_KEY.split()[:2]).encode()).hexdigest() + assert gpgtools.material_digest(GOOD_KEY) == digest + renamed = GOOD_KEY.replace("daedalus-test", "cardno:12_345_678") + assert gpgtools.material_digest(renamed) == digest + + +def test_cmd_send_pubkey_prints_identity_block(tmp_path, capsys): + """Send prints the line, source, and material digest (4.8).""" + digest = hashlib.sha256( + " ".join(GOOD_KEY.split()[:2]).encode()).hexdigest() + path = tmp_path / "yubikey_auth.pub" + path.write_text(GOOD_KEY + "\n", encoding="utf-8") + args = gpgtools.parse_args(["send_pubkey", "--file", str(path), + "--dry-run", "you@server"]) + calls = [] + runner = make_runner({}, calls) + assert gpgtools.cmd_send_pubkey(args, runner, + lambda _u: b"") == gpgtools.EXIT_OK + out = capsys.readouterr().out + assert GOOD_KEY in out + assert str(path) in out + assert digest in out + assert calls == [] # a file source needs no command at all + + +# --- store_publickey (gpgtools spec section 11) + + +def test_store_key_appends_and_enforces_perms(tmp_path): + """A fresh authorized_keys gets the line, dir 700, file 600.""" + target = tmp_path / "ssh" / "authorized_keys" + assert gpgtools.store_key(GOOD_KEY, target) is True + assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n" + assert oct(target.parent.stat().st_mode)[-3:] == "700" + assert oct(target.stat().st_mode)[-3:] == "600" + + +def test_store_key_preserves_existing_entries(tmp_path): + """Other keys in the file stay untouched (multi-key file).""" + target = tmp_path / "authorized_keys" + target.write_text(OTHER_KEY + "\n", encoding="utf-8") + assert gpgtools.store_key(GOOD_KEY, target) is True + content = target.read_text(encoding="utf-8") + assert content == OTHER_KEY + "\n" + GOOD_KEY + "\n" + + +def test_store_key_repairs_missing_newline(tmp_path): + """A file without a trailing newline never glues two keys.""" + target = tmp_path / "authorized_keys" + target.write_text(OTHER_KEY, encoding="utf-8") + assert gpgtools.store_key(GOOD_KEY, target) is True + content = target.read_text(encoding="utf-8") + assert content == OTHER_KEY + "\n" + GOOD_KEY + "\n" + + +def test_store_key_idempotent_by_material(tmp_path): + """Same material with another comment is already present.""" + target = tmp_path / "authorized_keys" + target.write_text(GOOD_KEY.replace("daedalus-test", "cardno:12_345_678") + + "\n", encoding="utf-8") + before = target.read_text(encoding="utf-8") + assert gpgtools.store_key(GOOD_KEY, target) is False + assert target.read_text(encoding="utf-8") == before + + +def test_cmd_store_publickey_full_flow(tmp_path, capsys): + """--pubkey resolves, prints the identity block, appends.""" + digest = hashlib.sha256( + " ".join(GOOD_KEY.split()[:2]).encode()).hexdigest() + target = tmp_path / "ssh" / "authorized_keys" + calls = [] + runner = make_runner({}, calls) + args = gpgtools.parse_args(["store_publickey", "--pubkey", GOOD_KEY, + "--authorized-keys", str(target)]) + assert gpgtools.cmd_store_publickey(args, runner, + None) == gpgtools.EXIT_OK + out = capsys.readouterr().out + assert GOOD_KEY in out + assert digest in out + assert str(target) in out + assert "appended" in out + assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n" + assert calls == [] # store never runs a command (spec 11.8) + + +def test_cmd_store_publickey_already_present(tmp_path, capsys): + """Present material is reported; the file is not touched.""" + target = tmp_path / "authorized_keys" + target.write_text(GOOD_KEY + "\n", encoding="utf-8") + args = gpgtools.parse_args(["store_publickey", "--pubkey", GOOD_KEY, + "--authorized-keys", str(target)]) + assert gpgtools.cmd_store_publickey( + args, make_runner({}), None) == gpgtools.EXIT_OK + assert "already present" in capsys.readouterr().out + assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n" + + +def test_cmd_store_publickey_dry_run(tmp_path, capsys): + """--dry-run prints creating and writes nothing.""" + target = tmp_path / "ssh" / "authorized_keys" + args = gpgtools.parse_args(["store_publickey", "--pubkey", GOOD_KEY, + "--authorized-keys", str(target), + "--dry-run"]) + assert gpgtools.cmd_store_publickey( + args, make_runner({}), None) == gpgtools.EXIT_OK + out = capsys.readouterr().out + assert GOOD_KEY in out + assert "creating" in out + assert not target.parent.exists() + + +def test_cmd_store_publickey_invalid_line_is_exit_8(tmp_path, capsys): + """A garbage line is refused before any write.""" + target = tmp_path / "authorized_keys" + args = gpgtools.parse_args(["store_publickey", "--pubkey", "garbage", + "--authorized-keys", str(target)]) + assert gpgtools.cmd_store_publickey( + args, make_runner({}), None) == gpgtools.EXIT_NO_KEY + assert not target.exists() + + +def test_cmd_store_publickey_fingerprint_source(tmp_path): + """A remote source resolves through the injected runner/fetch.""" + target = tmp_path / "authorized_keys" + + def fake_gpg(cmd, input_text="", env=None): + if cmd == ["gpg", "--export-ssh-key", "0x" + FP]: + return (0, GOOD_KEY + "\n") + raise AssertionError(f"unexpected {cmd}") + + args = gpgtools.parse_args(["store_publickey", "--fingerprint", FP, + "--authorized-keys", str(target)]) + assert gpgtools.cmd_store_publickey( + args, fake_gpg, lambda _u: b"") == gpgtools.EXIT_OK + assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n" + + +def test_cmd_store_publickey_file_source(tmp_path): + """A --file source stores without network or runner commands.""" + path = tmp_path / "yubikey_auth.pub" + path.write_text(GOOD_KEY + "\n", encoding="utf-8") + target = tmp_path / "authorized_keys" + args = gpgtools.parse_args(["store_publickey", "--file", str(path), + "--authorized-keys", str(target)]) + assert gpgtools.cmd_store_publickey( + args, make_runner({}), None) == gpgtools.EXIT_OK + assert target.read_text(encoding="utf-8") == GOOD_KEY + "\n" + + +def test_cmd_store_publickey_no_source_is_exit_8(tmp_path, capsys): + """A source that cannot resolve is exit 8 (spec 11.2).""" + target = tmp_path / "authorized_keys" + args = gpgtools.parse_args(["store_publickey", "--fingerprint", FP, + "--authorized-keys", str(target)]) + + def fake_gpg(cmd, input_text="", env=None): + return (1, "not found\n") + assert gpgtools.cmd_store_publickey( + args, fake_gpg, lambda _u: None) == gpgtools.EXIT_NO_KEY + assert not target.exists() + + +def test_cli_store_publickey_wires_flow(monkeypatch): + """The CLI dispatches store_publickey with runner and fetcher.""" + seen = {} + + def fake_store(args, run_cmd, fetch): + seen["args"] = args + seen["runner"] = run_cmd + return gpgtools.EXIT_OK + + monkeypatch.setattr(gpgtools, "cmd_store_publickey", fake_store) + code = gpgtools.main(["store_publickey", "--pubkey", GOOD_KEY]) + assert code == 0 + assert seen["args"].pubkey == GOOD_KEY + assert seen["runner"] is gpgtools.run_command + + +def test_cli_store_publickey_requires_source(): + """No source flag is a usage error, like send_pubkey.""" + with pytest.raises(SystemExit) as exc: + gpgtools.main(["store_publickey"]) + assert exc.value.code == 2 + + +# --- initialize: gnupg readiness and install (gpgtools spec 12) + + +def test_ensure_gnupg_already_ready(): + """A working gpg means ready: no install command is run.""" + calls = [] + runner = make_runner({("gpg", "--version"): + (0, "gpg (GnuPG) 2.4.7\n")}, calls) + assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_OK + assert not any(cmd[:1] == ["sudo"] for cmd in calls) + + +def test_ensure_gnupg_installs_when_missing(monkeypatch): + """Missing gpg: install via the detected manager, then re-check.""" + monkeypatch.setattr(gpgtools.shutil, "which", + lambda name: "/usr/bin/apt-get" + if name == "apt-get" else None) + calls = [] + state = {"ready": False} + + def runner(cmd, input_text="", env=None): + calls.append(list(cmd)) + if cmd == ["gpg", "--version"]: + if state["ready"]: + return (0, "gpg (GnuPG) 2.4.7\n") + return (1, "not found") + if cmd[:2] == ["sudo", "apt-get"]: + state["ready"] = True + return (0, "installed\n") + raise AssertionError(f"unexpected command: {cmd}") + + assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_OK + assert ["sudo", "apt-get", "install", "-y", "gnupg"] in calls + checks = [cmd for cmd in calls if cmd == ["gpg", "--version"]] + assert len(checks) == 2 # initial check + post-install re-check + + +def test_ensure_gnupg_no_known_manager(monkeypatch, caplog): + """Missing gpg with no known manager stops with exit 3.""" + monkeypatch.setattr(gpgtools.shutil, "which", lambda _name: None) + runner = make_runner({("gpg", "--version"): (1, "not found")}) + assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_NO_GPG + assert "manually" in caplog.text + + +def test_ensure_gnupg_install_fails(monkeypatch): + """A failed package install is exit 2.""" + monkeypatch.setattr(gpgtools.shutil, "which", + lambda name: "/usr/bin/dnf" if name == "dnf" else None) + runner = make_runner({ + ("gpg", "--version"): (1, "not found"), + ("sudo", "dnf"): (1, "no network\n"), + }) + assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_INSTALL_FAILED + + +def test_ensure_gnupg_still_broken_after_install(monkeypatch): + """Installed but still unusable re-checks once, then exit 2.""" + monkeypatch.setattr(gpgtools.shutil, "which", + lambda name: "/usr/bin/apt-get" + if name == "apt-get" else None) + calls = [] + + def runner(cmd, input_text="", env=None): + calls.append(list(cmd)) + if cmd == ["gpg", "--version"]: + return (1, "still broken\n") + if cmd[:2] == ["sudo", "apt-get"]: + return (0, "installed\n") + raise AssertionError(f"unexpected command: {cmd}") + + assert gpgtools.ensure_gnupg(runner) == gpgtools.EXIT_INSTALL_FAILED + assert len([cmd for cmd in calls if cmd == ["gpg", "--version"]]) == 2 + + +def test_main_initialize_dry_run_ready(monkeypatch, capsys): + """Dry run with gpg present prints ready and installs nothing.""" + calls = [] + runner = make_runner({("gpg", "--version"): + (0, "gpg (GnuPG) 2.4.7\n")}, calls) + monkeypatch.setattr(gpgtools, "run_command", runner) + assert gpgtools.main(["initialize", "--dry-run"]) == 0 + out = capsys.readouterr().out + assert "dry run" in out + assert "2.4.7" in out + assert not any(cmd[:1] == ["sudo"] for cmd in calls) + + +def test_main_initialize_dry_run_missing_prints_plan(monkeypatch, capsys): + """Dry run with gpg missing prints the install command, runs none.""" + monkeypatch.setattr(gpgtools.shutil, "which", + lambda name: "/usr/bin/apt-get" + if name == "apt-get" else None) + calls = [] + runner = make_runner({("gpg", "--version"): (1, "not found")}, calls) + monkeypatch.setattr(gpgtools, "run_command", runner) + assert gpgtools.main(["initialize", "--dry-run"]) == 0 + out = capsys.readouterr().out + assert "apt-get install -y gnupg" in out + assert not any(cmd[:1] == ["sudo"] for cmd in calls) + + +def test_main_initialize_wires_flow(monkeypatch): + """The CLI dispatches initialize to ensure_gnupg with the runner.""" + seen = {} + + def fake_ensure(run_cmd): + seen["runner"] = run_cmd + return gpgtools.EXIT_OK + + monkeypatch.setattr(gpgtools, "ensure_gnupg", fake_ensure) + assert gpgtools.main(["initialize"]) == 0 + assert seen["runner"] is gpgtools.run_command + + +# --- configure_ssh: block building, merge, guards, file writes + + +SAIKA_BLOCK = ( + "# BEGIN daedalus gpgtools: vault1\n" + "Host vault1\n" + " HostName 203.0.113.10\n" + " User admin\n" + " IdentityFile /pub/yubikey_auth.pub\n" + " IdentityFile /pub/id_ed25519\n" + " IdentitiesOnly yes\n" + "# END daedalus gpgtools: vault1\n") + + +def test_build_block_full(): + """The managed block renders exactly, markers included.""" + block = gpgtools.build_block(alias="vault1", + hostname="203.0.113.10", + user="admin", + pubkey="/pub/yubikey_auth.pub", + fallback="/pub/id_ed25519") + assert block == SAIKA_BLOCK + + +def test_build_block_minimal(): + """Without user and fallback the lines are omitted.""" + block = gpgtools.build_block(alias="host1", hostname="host1", + user=None, + pubkey="/pub/yubikey_auth.pub", + fallback=None) + assert "User " not in block + assert "id_ed25519" not in block + assert "Host host1\n" in block + assert "IdentitiesOnly yes\n" in block + + +def test_merge_into_empty_config(): + """An empty config receives the block.""" + merged = gpgtools.merge_managed_block("", "vault1", SAIKA_BLOCK) + assert merged == SAIKA_BLOCK + + +def test_merge_replaces_managed_block_only(): + """A marked block is replaced; surrounding config survives.""" + existing = ("Host other\n" + " HostName 10.0.0.1\n\n" + SAIKA_BLOCK + + "\nHost third\n HostName 10.0.0.2\n") + new_block = SAIKA_BLOCK.replace("HostName 203.0.113.10", + "HostName 198.51.100.5") + merged = gpgtools.merge_managed_block(existing, "vault1", + new_block) + assert "HostName 198.51.100.5" in merged + assert "203.0.113.10" not in merged + assert merged.startswith("Host other\n HostName 10.0.0.1\n\n") + assert merged.endswith("Host third\n HostName 10.0.0.2\n") + assert merged.count("# BEGIN daedalus gpgtools: vault1") == 1 + + +def test_unmanaged_alias_detection(): + """A Host line naming the alias outside the markers conflicts.""" + managed = SAIKA_BLOCK + assert gpgtools.unmanaged_alias_exists(managed, "vault1") is False + assert gpgtools.unmanaged_alias_exists( + SAIKA_BLOCK + "\nHost vault1\n HostName x\n", + "vault1") is True + assert gpgtools.unmanaged_alias_exists( + "Host other vault1\n HostName x\n", + "vault1") is True + + +def test_cmd_configure_ssh_creates_config(tmp_path): + """A full run creates the ssh dir and config with the block.""" + ssh_dir = tmp_path / "ssh" + pubkey = tmp_path / "yubikey_auth.pub" + pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8") + fallback = tmp_path / "id_ed25519" + fallback.write_text("secret", encoding="utf-8") + args = gpgtools.parse_args([ + "configure_ssh", "--alias", "vault1", + "--hostname", "203.0.113.10", "--user", "admin", + "--pubkey", str(pubkey), "--fallback", str(fallback), + "--config", str(ssh_dir / "config")]) + assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_OK + config = (ssh_dir / "config").read_text(encoding="utf-8") + assert config == SAIKA_BLOCK.replace( + "IdentityFile /pub/yubikey_auth.pub", + f"IdentityFile {pubkey}").replace( + "IdentityFile /pub/id_ed25519", + f"IdentityFile {fallback}") + assert oct(ssh_dir.stat().st_mode)[-3:] == "700" + assert oct((ssh_dir / "config").stat().st_mode)[-3:] == "600" + + +def test_cmd_configure_ssh_idempotent(tmp_path): + """Running twice with the same args leaves the file unchanged.""" + pubkey = tmp_path / "yubikey_auth.pub" + pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8") + config = tmp_path / "config" + argv = ["configure_ssh", "--alias", "h1", "--pubkey", str(pubkey), + "--config", str(config)] + first = gpgtools.cmd_configure_ssh(gpgtools.parse_args(argv)) + content = config.read_text(encoding="utf-8") + assert first == gpgtools.EXIT_OK + assert gpgtools.cmd_configure_ssh( + gpgtools.parse_args(argv)) == gpgtools.EXIT_OK + assert config.read_text(encoding="utf-8") == content + assert content.count("# BEGIN daedalus gpgtools: h1") == 1 + + +def test_cmd_configure_ssh_missing_pubkey(tmp_path): + """A missing pubkey file is exit 8 with the derive hint.""" + args = gpgtools.parse_args([ + "configure_ssh", "--alias", "h1", + "--pubkey", str(tmp_path / "nope.pub"), + "--config", str(tmp_path / "config")]) + assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_NO_KEY + assert not (tmp_path / "config").exists() + + +def test_cmd_configure_ssh_alias_conflict(tmp_path): + """An unmanaged Host with the same alias refuses (exit 11).""" + pubkey = tmp_path / "yubikey_auth.pub" + pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8") + config = tmp_path / "config" + config.write_text("Host h1\n HostName 10.0.0.9\n", + encoding="utf-8") + args = gpgtools.parse_args([ + "configure_ssh", "--alias", "h1", "--pubkey", str(pubkey), + "--config", str(config)]) + assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_ALIAS_CONFLICT + assert config.read_text(encoding="utf-8") == "Host h1\n HostName 10.0.0.9\n" + + +def test_cmd_configure_ssh_missing_fallback_omitted(tmp_path, caplog): + """A nonexistent default fallback is omitted without error.""" + pubkey = tmp_path / "yubikey_auth.pub" + pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8") + args = gpgtools.parse_args([ + "configure_ssh", "--alias", "h1", "--pubkey", str(pubkey), + "--fallback", str(tmp_path / "missing_key"), + "--config", str(tmp_path / "config")]) + assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_OK + content = (tmp_path / "config").read_text(encoding="utf-8") + assert "missing_key" not in content + + +def test_cmd_configure_ssh_dry_run(tmp_path, capsys): + """--dry-run prints the block and writes nothing.""" + pubkey = tmp_path / "yubikey_auth.pub" + pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8") + config = tmp_path / "config" + args = gpgtools.parse_args([ + "configure_ssh", "--alias", "h1", "--pubkey", str(pubkey), + "--config", str(config), "--dry-run"]) + assert gpgtools.cmd_configure_ssh(args) == gpgtools.EXIT_OK + out = capsys.readouterr().out + assert "Host h1" in out + assert not config.exists() + + +def test_cli_configure_ssh_wires_flow(monkeypatch): + """The CLI dispatches configure_ssh to cmd_configure_ssh.""" + seen = {} + + def fake_cmd(args): + seen["args"] = args + return gpgtools.EXIT_OK + + monkeypatch.setattr(gpgtools, "cmd_configure_ssh", fake_cmd) + code = gpgtools.main(["configure_ssh", "--alias", "h1", + "--hostname", "198.51.100.5"]) + assert code == 0 + assert seen["args"].alias == "h1" + assert seen["args"].hostname == "198.51.100.5" + + +def test_cli_configure_ssh_requires_alias(): + """--alias is required.""" + with pytest.raises(SystemExit) as exc: + gpgtools.main(["configure_ssh"]) + assert exc.value.code == 2 diff --git a/python/tests/test_hello.py b/python/tests/test_hello.py index 5bb5eeb..df0cd33 100644 --- a/python/tests/test_hello.py +++ b/python/tests/test_hello.py @@ -34,7 +34,7 @@ def test_app_version_falls_back_to_pyproject(monkeypatch): raise hello.importlib.metadata.PackageNotFoundError(_name) monkeypatch.setattr(hello.importlib.metadata, "version", not_found) - assert hello.app_version() == "0.6.0" + assert hello.app_version() == "0.9.0" def test_help_exits_zero(capsys):