From 41c8b99bd6364c21b690e422a68965ad5b3105dd Mon Sep 17 00:00:00 2001 From: nvaldez Date: Thu, 19 Nov 2026 09:49:35 +0100 Subject: [PATCH] feat: gpgtools ssh-config-summary - per-host table of gpg-enabled logins (v0.11.0) - read-only: one row per marker-managed block in ~/.ssh/config (or --config PATH): alias, hostname, user, key id (first 8 chars of the identity's SHA256 fingerprint via ssh-keygen -lf, material digest as fallback), and the fallback identity's name - no managed blocks / missing config: fact + configure_ssh hint, exit 0 always (read-only command) - spec items 2.8 + section 13 first, then tests, then code (SPEC 6.12); 10 new tests (100 in test_gpgtools.py), registry description, README section, CHANGELOG 0.11.0, version pins Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- CHANGELOG.md | 13 +++ README.md | 16 +++- daedalus/registry.py | 2 +- daedalus/tests/test_cli.py | 2 +- pyproject.toml | 2 +- python/src/gpgtools/gpgtools.py | 146 ++++++++++++++++++++++++++++++++ python/src/gpgtools/spec.md | 38 ++++++++- python/tests/test_gpgtools.py | 119 ++++++++++++++++++++++++++ python/tests/test_hello.py | 2 +- 9 files changed, 333 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 073019b..f7c7b8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,19 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and - Nothing yet. +## [0.11.0] - 2026-11-19 + +### Added in 0.11.0 + +- `gpgtools ssh-config-summary`: a read-only view of the gpg-enabled ssh + logins. One row per marker-managed block in `~/.ssh/config` (or + `--config FILE`): alias, hostname, user, the key id - first 8 chars of the + identity's SHA256 fingerprint via `ssh-keygen -lf`, with the SHA-256 + material digest as fallback when ssh-keygen is unavailable - and the + fallback identity's name. No managed blocks (or a missing config) prints + that fact with the `configure_ssh` hint. Exit code always 0. Spec item 2.8 + and section 13 written first, then tests, then code (SPEC 6.12). + ## [0.10.0] - 2026-11-19 ### Added in 0.10.0 diff --git a/README.md b/README.md index 0b3964e..9cf1123 100644 --- a/README.md +++ b/README.md @@ -156,9 +156,23 @@ daedalus gpgtools configure_ssh --alias vault1 --no-fallback # YubiKey only | `--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 +Additional exit code: `11` an unmanaged `Host` with the same alias exists in the config (move it into the managed markers or rename the alias). +`ssh-config-summary` prints what is enabled where, read-only: one row per +managed block — alias, hostname, user, the key id (first 8 chars of the +identity's SHA256 fingerprint, material-digest fallback), and the fallback +identity. Same id on two rows means the same gpg key guards both hosts. + +```bash +daedalus gpgtools ssh-config-summary +daedalus gpgtools ssh-config-summary --config FILE +``` + +| Argument | Default | Meaning | +| --- | --- | --- | +| `--config FILE` | `~/.ssh/config` | Which ssh client config to read | + ## Shell completion Bash (and other shells argcomplete supports) completes script names and diff --git a/daedalus/registry.py b/daedalus/registry.py index 93c3d9e..d901fc7 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 (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)", + 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), ssh-config-summary (per-host table of gpg-enabled logins)", categories="gpg", ), "hello": Script( diff --git a/daedalus/tests/test_cli.py b/daedalus/tests/test_cli.py index f282497..24fbb2e 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.10.0")]) +@pytest.mark.parametrize("installed, expected", [(True, "daedalus 1.2.3"), (False, "daedalus 0.11.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 02e93cb..5253040 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "daedalus" -version = "0.10.0" +version = "0.11.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 a3043ec..c69efdd 100644 --- a/python/src/gpgtools/gpgtools.py +++ b/python/src/gpgtools/gpgtools.py @@ -976,6 +976,141 @@ def _add_source_flags(subparser: argparse.ArgumentParser) -> None: "(e.g. a .pub from a USB stick)") +@dataclasses.dataclass(frozen=True) +class ManagedBlock: + """One marker-managed Host block parsed from an ssh config. + + Args: + alias: the block's ssh Host alias. + hostname: HostName value, or None when the block omits it. + user: User value, or None. + identities: the block's IdentityFiles in order (``~`` + expanded); the first is the gpg-derived key. + """ + + alias: str + hostname: str | None + user: str | None + identities: tuple[pathlib.Path, ...] + + +def parse_managed_blocks(existing: str) -> list[ManagedBlock]: + """Parse every marker-managed block of an ssh config (13.1). + + Args: + existing: config text, or "". + + Returns: + One ManagedBlock per BEGIN marker found, in file order. + """ + blocks: list[ManagedBlock] = [] + lines = existing.splitlines() + prefix = MANAGED_BEGIN.format(alias="") + index = 0 + while index < len(lines): + stripped = lines[index].strip() + if not stripped.startswith(prefix): + index += 1 + continue + alias = stripped[len(prefix):].strip() + end = MANAGED_END.format(alias=alias) + hostname = None + user = None + identities: list[pathlib.Path] = [] + index += 1 + while index < len(lines) and lines[index].strip() != end: + entry = lines[index].strip() + index += 1 + key, _sep, value = entry.partition(" ") + if key == "HostName": + hostname = value.strip() + elif key == "User": + user = value.strip() + elif key == "IdentityFile": + identities.append( + pathlib.Path(value.strip()).expanduser()) + blocks.append(ManagedBlock(alias, hostname, user, + tuple(identities))) + index += 1 + return blocks + + +def ssh_key_id(pubkey: pathlib.Path, run_cmd) -> str | None: + """Identity of a pubkey file: bare SHA256 fingerprint (13.3). + + ``ssh-keygen -lf`` decides; without it (or on failure) a + readable key line yields the material digest (item 4.8) - + both are stable per key. No match is None. + + Args: + pubkey: path to an ssh public key file. + run_cmd: command runner. + + Returns: + The full fingerprint or digest, untruncated; None when + the file cannot be identified. + """ + code, output = run_cmd(["ssh-keygen", "-lf", str(pubkey)]) + if code == 0: + for token in output.split(): + if token.startswith("SHA256:"): + return token.split(":", 1)[1] + if pubkey.is_file(): + for line in pubkey.read_text(encoding="utf-8").splitlines(): + if validate_pubkey_line(line): + return material_digest(line) + return None + + +def cmd_ssh_config_summary(args: argparse.Namespace, + run_cmd=None) -> int: + """ssh-config-summary subcommand (gpgtools spec section 13). + + Prints one row per marker-managed block in the ssh config: + alias, hostname, user, the identity's key id (first 8 chars + of its SHA256 fingerprint, with the material digest as + fallback), and the fallback identity's file name. Read-only: + nothing is written, no host is contacted. + + Args: + args: parsed arguments (config). + run_cmd: command runner; defaults to run_command. + + Returns: + EXIT_OK always (item 13.5). + """ + if run_cmd is None: + run_cmd = run_command + config = args.config or pathlib.Path.home() / ".ssh" / "config" + existing = config.read_text(encoding="utf-8") if config.exists() else "" + blocks = parse_managed_blocks(existing) + if not blocks: + print(f"no daedalus gpgtools managed blocks in {config}") + print("hint: daedalus gpgtools configure_ssh --alias NAME " + "[--hostname HOST] [--user USER]") + return EXIT_OK + rows = [("alias", "hostname", "user", "key id", "fallback")] + for block in blocks: + pubkey = block.identities[0] if block.identities else None + full_id = ssh_key_id(pubkey, run_cmd) if pubkey else None + key_id = full_id[:8] if full_id else "-" + fallback = block.identities[1].name if len( + block.identities) > 1 else "-" + rows.append((block.alias, block.hostname or block.alias, + block.user or "-", key_id, fallback)) + widths = [max(len(row[column]) for row in rows) + for column in range(len(rows[0]))] + for number, row in enumerate(rows): + line = " ".join(cell.ljust(widths[column]) + for column, cell in enumerate(row)) + print(line.rstrip()) + if number == 0: + print(" ".join("-" * width for width in widths)) + print("key id: first 8 chars of the identity's SHA256 " + "fingerprint (material digest fallback)") + return EXIT_OK + + def parse_args(argv: list[str] | None) -> argparse.Namespace: """Parse gpgtools command-line arguments.""" parser = argparse.ArgumentParser( @@ -1030,6 +1165,14 @@ def parse_args(argv: list[str] | None) -> argparse.Namespace: "~/.ssh/authorized_keys)") store.add_argument("--dry-run", action="store_true", help="resolve and print the key, write nothing") + summary = subparsers.add_parser( + "ssh-config-summary", + help="print the per-host table of gpg-enabled ssh logins " + "in the ssh config: alias, hostname, user, key id, " + "fallback (read-only)", + ) + summary.add_argument("--config", type=pathlib.Path, default=None, + help="ssh config path (default ~/.ssh/config)") conf = subparsers.add_parser( "configure_ssh", help="write the per-host ssh client block (guide step 7); " @@ -1071,6 +1214,8 @@ def main(argv: list[str] | None = None) -> int: 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 == "ssh-config-summary": + return cmd_ssh_config_summary(args, run_command) if args.command == "configure_ssh": return cmd_configure_ssh(args) if args.command == "initialize": @@ -1094,6 +1239,7 @@ def main(argv: list[str] | None = None) -> int: print(" daedalus gpgtools store_publickey [--yubikey | --url URL | " "--fingerprint FP | --pubkey LINE | --file PATH] " "[--authorized-keys FILE] [--dry-run]") + print(" daedalus gpgtools ssh-config-summary [--config PATH]") 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 2301871..245638a 100644 --- a/python/src/gpgtools/spec.md +++ b/python/src/gpgtools/spec.md @@ -18,6 +18,7 @@ Items are cited as `gpgtools spec item N.M`. - [10. configure_ssh behavior](#10-configure_ssh-behavior) - [11. store_publickey behavior](#11-store_publickey-behavior) - [12. initialize behavior](#12-initialize-behavior) +- [13. ssh-config-summary behavior](#13-ssh-config-summary-behavior) @@ -73,6 +74,9 @@ Items are cited as `gpgtools spec item N.M`. that gnupg is ready on this machine and installs what is missing; the gnupg-only half of initialize_yubikey (section 12). +- **2.8** `daedalus gpgtools ssh-config-summary + [--config PATH]` - prints the table of gpg-enabled ssh logins + found in the config (section 13); read-only. ## 3. initialize_yubikey behavior @@ -225,7 +229,9 @@ Items are cited as `gpgtools spec item N.M`. 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 + idempotence, perms, dry run, summary: block parsing (each + field), key-id resolution and both id fallbacks, the empty + and missing-config paths, 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. @@ -239,7 +245,8 @@ Items are cited as `gpgtools spec item N.M`. (argcomplete opt-in after the parser), 9.8 (version bump). - **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). + (--file source, store_publickey), 0.9.0 (initialize), 0.10.0 + (init script), 0.11.0 (ssh-config-summary). ## 10. configure_ssh behavior @@ -339,3 +346,30 @@ Host store_publickey (item 11) - on a machine without the YubiKey, run `initialize` first when a gpg-dependent source (`--fingerprint`, `--url`, `--yubikey`) is wanted. + +## 13. ssh-config-summary behavior + +- **13.1** Scope: every marker-managed block (item 10.1) in + `--config` (default `~/.ssh/config`) is one gpg-enabled + login. The command never writes and never contacts any + host; it reads only the config and the IdentityFiles the + blocks name (`~` expanded). +- **13.2** Output is one row per block with the columns + `alias`, `hostname`, `user`, `key id`, `fallback`: + hostname defaults to the alias when the block omits + HostName; user prints `-` when absent (ssh's own default); + fallback prints `-` when the block has no second + IdentityFile. Columns are padded and separated by two + spaces, like the daedalus script listing. +- **13.3** Key id: taken from the block's *first* IdentityFile. + `ssh-keygen -lf ` yields the SHA256 fingerprint; the + row shows its first 8 chars after the `SHA256:` prefix + (shorter values print in full). When ssh-keygen fails or is + missing but the file is readable and holds a valid key line + (item 4.2), the id falls back to the first 8 chars of the + material digest (item 4.8) - both are stable per key. A + missing or unreadable IdentityFile prints `-` for the id. +- **13.4** No managed blocks - a missing config file counts - + prints that fact with the `configure_ssh` hint and exits 0. +- **13.5** Exit code is always 0; the command is read-only and + has no failure modes that would leave anything half-done. diff --git a/python/tests/test_gpgtools.py b/python/tests/test_gpgtools.py index 0e7fe04..949ad0a 100644 --- a/python/tests/test_gpgtools.py +++ b/python/tests/test_gpgtools.py @@ -1029,6 +1029,125 @@ def test_main_initialize_wires_flow(monkeypatch): assert seen["runner"] is gpgtools.run_command +# --- ssh-config-summary (gpgtools spec section 13) + + +def summary_config(tmp_path): + """A config with one full managed block and one minimal one.""" + pubkey = tmp_path / "yubikey_auth.pub" + fallback = tmp_path / "id_ed25519" + full = gpgtools.build_block("vault1", "203.0.113.10", "admin", + str(pubkey), str(fallback)) + minimal = gpgtools.build_block("host1", "host1", None, + str(pubkey), None) + config = gpgtools.merge_managed_block( + gpgtools.merge_managed_block("", "vault1", full), + "host1", minimal) + return config, pubkey, fallback + + +def test_parse_managed_blocks_fields(tmp_path): + """Each block yields alias, hostname, user, identities in order.""" + config, pubkey, fallback = summary_config(tmp_path) + blocks = gpgtools.parse_managed_blocks(config) + assert [(b.alias, b.hostname, b.user) for b in blocks] == \ + [("vault1", "203.0.113.10", "admin"), ("host1", "host1", None)] + assert blocks[0].identities == (pubkey, fallback) + assert blocks[1].identities == (pubkey,) + + +def test_parse_managed_blocks_without_markers(): + """A config without managed blocks parses to an empty list.""" + assert gpgtools.parse_managed_blocks( + "Host other\n HostName 10.0.0.1\n") == [] + + +def test_ssh_key_id_from_ssh_keygen(tmp_path): + """sshd-style ssh-keygen output yields the bare fingerprint.""" + pubkey = tmp_path / "yubikey_auth.pub" + pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8") + runner = make_runner({("ssh-keygen", "-lf"): + (0, "256 SHA256:AAAA1111BBBB2222 " + "cardno:12 (ED25519)\n")}) + assert gpgtools.ssh_key_id(pubkey, runner) == "AAAA1111BBBB2222" + + +def test_ssh_key_id_falls_back_to_digest(tmp_path): + """Without ssh-keygen, a readable key yields the material digest.""" + pubkey = tmp_path / "yubikey_auth.pub" + pubkey.write_text(GOOD_KEY + "\n", encoding="utf-8") + runner = make_runner({("ssh-keygen", "-lf"): (127, "not found")}) + digest = gpgtools.material_digest(GOOD_KEY) + assert gpgtools.ssh_key_id(pubkey, runner) == digest + + +def test_ssh_key_id_missing_file(tmp_path): + """A missing identity file yields None (row prints -).""" + runner = make_runner({("ssh-keygen", "-lf"): (1, "no such file\n")}) + assert gpgtools.ssh_key_id(tmp_path / "nope.pub", runner) is None + + +def test_cmd_summary_prints_the_table(tmp_path, capsys): + """Two blocks render with header, 8-char ids, and fallbacks.""" + config, pubkey, fallback = summary_config(tmp_path) + target = tmp_path / "config" + target.write_text(config, encoding="utf-8") + runner = make_runner({("ssh-keygen", "-lf"): + (0, "256 SHA256:AAAA1111BBBB2222 " + "cardno:12 (ED25519)\n")}) + args = gpgtools.parse_args(["ssh-config-summary", + "--config", str(target)]) + assert gpgtools.cmd_ssh_config_summary( + args, runner) == gpgtools.EXIT_OK + out = capsys.readouterr().out + assert "alias" in out and "hostname" in out and "key id" in out + assert "vault1" in out and "203.0.113.10" in out and "admin" in out + assert "host1" in out + assert "AAAA1111" in out # truncated id + assert "BBBB2222" not in out # only the first 8 chars + assert fallback.name in out # vault1's fallback + assert "-" in out # host1's missing fallback/user + + +def test_cmd_summary_empty_config(tmp_path, capsys): + """No managed blocks: fact plus configure_ssh hint, exit 0.""" + target = tmp_path / "config" + target.write_text("Host other\n HostName 10.0.0.1\n", + encoding="utf-8") + args = gpgtools.parse_args(["ssh-config-summary", + "--config", str(target)]) + assert gpgtools.cmd_ssh_config_summary( + args, make_runner({})) == gpgtools.EXIT_OK + out = capsys.readouterr().out + assert "no daedalus gpgtools" in out + assert "configure_ssh" in out + + +def test_cmd_summary_missing_config(tmp_path, capsys): + """A missing config file is the same empty case, exit 0.""" + args = gpgtools.parse_args(["ssh-config-summary", + "--config", + str(tmp_path / "nope")]) + assert gpgtools.cmd_ssh_config_summary( + args, make_runner({})) == gpgtools.EXIT_OK + assert "no daedalus gpgtools" in capsys.readouterr().out + + +def test_cli_summary_wires_flow(monkeypatch): + """The CLI dispatches the summary with the runner.""" + seen = {} + + def fake_summary(args, run_cmd): + seen["args"] = args + seen["runner"] = run_cmd + return gpgtools.EXIT_OK + + monkeypatch.setattr(gpgtools, "cmd_ssh_config_summary", + fake_summary) + assert gpgtools.main(["ssh-config-summary"]) == 0 + assert seen["runner"] is gpgtools.run_command + + # --- configure_ssh: block building, merge, guards, file writes diff --git a/python/tests/test_hello.py b/python/tests/test_hello.py index ead2b7a..28aee0f 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.10.0" + assert hello.app_version() == "0.11.0" def test_help_exits_zero(capsys):