From a9a1fe3c38f68fa2964a033baad517c646764057 Mon Sep 17 00:00:00 2001 From: Fran Tufro Date: Thu, 12 Nov 2026 17:38:39 -0300 Subject: [PATCH 1/3] cubil: add authenticate-over-ssh-with-the-default-key-files task --- ...ate-over-ssh-with-the-default-key-files.md | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .cubil/backlog/authenticate-over-ssh-with-the-default-key-files.md diff --git a/.cubil/backlog/authenticate-over-ssh-with-the-default-key-files.md b/.cubil/backlog/authenticate-over-ssh-with-the-default-key-files.md new file mode 100644 index 0000000..8149ea7 --- /dev/null +++ b/.cubil/backlog/authenticate-over-ssh-with-the-default-key-files.md @@ -0,0 +1,24 @@ +--- +created: 2026-11-12 +--- + +# Authenticate over SSH with the default key files + +husmo authenticates SSH remotes only through a running ssh-agent (`git2::Cred::ssh_key_from_agent` in `remote_callbacks`, `src/git_sync.rs`), then falls back to a git credential helper and `Cred::default()`. A machine with an SSH key in `~/.ssh` and no agent cannot clone, pull or push, and `husmo init` fails with "remote rejected authentication: Failed getting response". + +This blocks agent-provisioning (task `husmo-on-every-agent`). Every Hermes Agent runs in a Lima VM with its own passphrase-less key at `~/.ssh/id_ed25519`, registered on its Forgejo user, and no ssh-agent. husmo runs there as an MCP server that Hermes spawns, so there is no login shell to start an agent either. On 2026-11-12, `husmo init --repo ssh://git@git.apps.tufro.me:2222/frantufro/husmo-data.git` on Pincho passed the host key check and then failed authentication. `git clone` of the same URL works, because it reads `~/.ssh/config` and the key. + +## What to build + +1. In the credentials callback, after the ssh-agent attempt fails and the remote allows `SSH_KEY`, try `Cred::ssh_key(username, None, key_path, None)` for each of `~/.ssh/id_ed25519`, `~/.ssh/id_ecdsa` and `~/.ssh/id_rsa` that exists, in that order. Keys with a passphrase fail on the first try and the loop moves on to the next candidate. +2. Return an error that names the keys tried when none works, so a failed clone says what to do. The current message names only the libgit2 failure. +3. Test with a local SSH server or document why the existing tests cannot cover it. The agent-first path, the credential helper and `file://` remotes must keep working. +4. Note in `docs/ARCHITECTURE.md` ("Git mechanics") and the module comment of `remote_callbacks` which credentials husmo tries and in what order. + +## Related limits to document + +libgit2 does not read `~/.ssh/config`, so a `Port` or `IdentityFile` entry has no effect on husmo. A remote on a non-standard port needs an `ssh://` URL with the port, for example `ssh://git@git.apps.tufro.me:2222/frantufro/husmo-data.git`. The short form `git@host:owner/repo.git` connects to port 22. + +## Done when + +On a machine with a key file, no ssh-agent and an `ssh://` remote, `husmo init --repo ` clones and `husmo` saves push to the branch. A release ships it, and agent-provisioning's `25-tools.sh` picks it up on the next `update`, after which `husmo-on-every-agent` continues with the `ssh://` URL. From c2aaf9ba63fd03798760f9c7096d436d710bcc84 Mon Sep 17 00:00:00 2001 From: Fran Tufro Date: Thu, 12 Nov 2026 17:42:18 -0300 Subject: [PATCH 2/3] Authenticate over SSH with the default key files When no ssh-agent is available, try ~/.ssh/id_ed25519, id_ecdsa and id_rsa in order, and name the keys tried when none is accepted. Document the credential order and the ~/.ssh/config limits in ARCHITECTURE.md. --- ...ate-over-ssh-with-the-default-key-files.md | 0 docs/ARCHITECTURE.md | 15 ++ src/git_sync.rs | 157 +++++++++++++++++- 3 files changed, 164 insertions(+), 8 deletions(-) rename .cubil/{backlog => done}/authenticate-over-ssh-with-the-default-key-files.md (100%) diff --git a/.cubil/backlog/authenticate-over-ssh-with-the-default-key-files.md b/.cubil/done/authenticate-over-ssh-with-the-default-key-files.md similarity index 100% rename from .cubil/backlog/authenticate-over-ssh-with-the-default-key-files.md rename to .cubil/done/authenticate-over-ssh-with-the-default-key-files.md diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9aff3f9..d45bcdc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -115,6 +115,21 @@ No manual commit step. Single machine for now — the pull-first step is a forward-looking safety habit, not a full multi-machine conflict-resolution system. +### Remote authentication + +For SSH remotes husmo tries, in order: a key from the running ssh-agent (only +when `SSH_AUTH_SOCK` is set), then the key files `~/.ssh/id_ed25519`, +`~/.ssh/id_ecdsa` and `~/.ssh/id_rsa` that exist, without a passphrase. Keys +with a passphrase fail and the next candidate is tried. When none is +accepted the error names the key files tried. HTTPS remotes use the git +credential helper, then git2's default credential. `file://` remotes need no +credentials. + +libgit2 does not read `~/.ssh/config`, so `Port` and `IdentityFile` entries +have no effect. A remote on a non-standard port needs an `ssh://` URL that +carries the port, for example `ssh://git@host:2222/owner/repo.git`. The short +form `git@host:owner/repo.git` connects to port 22. + This is distinct from the app repo's own normal development git history — don't conflate the two. diff --git a/src/git_sync.rs b/src/git_sync.rs index 3c743c0..30a79cb 100644 --- a/src/git_sync.rs +++ b/src/git_sync.rs @@ -198,13 +198,96 @@ enum CommitOutcome { NoChanges, } +/// Private-key files husmo tries for SSH remotes, relative to `$HOME`, in +/// the order they are attempted. +const DEFAULT_SSH_KEYS: &[&str] = &[".ssh/id_ed25519", ".ssh/id_ecdsa", ".ssh/id_rsa"]; + +/// The default private-key files that exist under `home`, in attempt order. +fn default_ssh_key_paths(home: &Path) -> Vec { + DEFAULT_SSH_KEYS + .iter() + .map(|relative| home.join(relative)) + .filter(|path| path.is_file()) + .collect() +} + +/// Walks the SSH credential sources one per call. libgit2 invokes the +/// credentials callback again after every rejected credential, so each call +/// must hand out something new or the connection would retry forever. +struct SshCredentials { + /// Whether the ssh-agent attempt is still to be made. + try_agent: bool, + /// Key files not yet attempted, in attempt order. + keys: std::vec::IntoIter, + /// Every key file attempted so far, for the final error message. + tried: Vec, +} + +impl SshCredentials { + /// `agent_available` is whether an ssh-agent socket is advertised + /// (`SSH_AUTH_SOCK`). Without one libgit2 aborts the whole connection + /// on the agent attempt, so it is skipped and the key files get their + /// turn. + fn new(agent_available: bool, keys: Vec) -> Self { + Self { + try_agent: agent_available, + keys: keys.into_iter(), + tried: Vec::new(), + } + } + + fn next(&mut self, username: &str) -> Result { + if self.try_agent { + self.try_agent = false; + if let Ok(credential) = git2::Cred::ssh_key_from_agent(username) { + return Ok(credential); + } + } + for key in self.keys.by_ref() { + self.tried.push(key.clone()); + if let Ok(credential) = git2::Cred::ssh_key(username, None, &key, None) { + return Ok(credential); + } + } + Err(git2::Error::from_str(&self.exhausted_message())) + } + + fn exhausted_message(&self) -> String { + if self.tried.is_empty() { + "SSH authentication failed: no ssh-agent identity was accepted and none of \ + ~/.ssh/id_ed25519, ~/.ssh/id_ecdsa or ~/.ssh/id_rsa exists; start an \ + ssh-agent with a loaded key or create a passphrase-less key in ~/.ssh" + .to_string() + } else { + let tried: Vec = self + .tried + .iter() + .map(|path| path.display().to_string()) + .collect(); + format!( + "SSH authentication failed: the ssh-agent (if any) and these key files \ + were not accepted: {}; keys with a passphrase are not supported, so \ + load them into an ssh-agent or use a passphrase-less key", + tried.join(", ") + ) + } + } +} + /// Builds the remote callbacks used for fetch, push, and (via -/// [`crate::init`]) the initial clone: an SSH key from the running -/// ssh-agent for `git+ssh` remotes, falling back to a system credential -/// helper (covers HTTPS remotes with a stored token/password) and finally -/// to whatever default credential git2 can produce. Remotes that need no -/// authentication at all (e.g. a local `file://` path, as in the tests) -/// never invoke this. +/// [`crate::init`]) the initial clone. For `git+ssh` remotes the +/// credentials are tried in this order: a key from the running ssh-agent +/// (only when `SSH_AUTH_SOCK` is set), then the key files `~/.ssh/id_ed25519`, +/// `~/.ssh/id_ecdsa` and `~/.ssh/id_rsa` that exist, without a passphrase. +/// When none is accepted the error names the key files tried. For other +/// remotes (HTTPS with a stored token/password) it uses a system credential +/// helper and finally whatever default credential git2 can produce. Remotes +/// that need no authentication at all (e.g. a local `file://` path, as in +/// the tests) never invoke this. +/// +/// libgit2 does not read `~/.ssh/config`, so `Port` and `IdentityFile` +/// entries have no effect: a non-standard port needs an `ssh://` URL that +/// carries it. /// /// `repo` supplies the git config the credential helper is read from, when /// one is already open (the normal `pull`/`push` case). `husmo init` calls @@ -214,12 +297,20 @@ enum CommitOutcome { /// helper for a fresh clone would be configured anyway. pub(crate) fn remote_callbacks(repo: Option<&Repository>) -> git2::RemoteCallbacks<'_> { let mut callbacks = git2::RemoteCallbacks::new(); + let mut ssh: Option = None; callbacks.credentials(move |url, username_from_url, allowed_types| { if allowed_types.contains(git2::CredentialType::SSH_KEY) && let Some(username) = username_from_url - && let Ok(credential) = git2::Cred::ssh_key_from_agent(username) { - return Ok(credential); + let ssh = ssh.get_or_insert_with(|| { + let home = std::env::var_os("HOME").map(PathBuf::from); + SshCredentials::new( + std::env::var_os("SSH_AUTH_SOCK").is_some_and(|sock| !sock.is_empty()), + home.map(|home| default_ssh_key_paths(&home)) + .unwrap_or_default(), + ) + }); + return ssh.next(username); } let config = match repo { Some(repo) => repo.config(), @@ -375,6 +466,56 @@ mod tests { use crate::test_support::{empty_bare_remote, seeded_bare_remote}; + use super::{SshCredentials, default_ssh_key_paths}; + + fn home_with_keys(names: &[&str]) -> TempDir { + let home = tempfile::tempdir().expect("failed to create temp dir"); + let ssh_dir = home.path().join(".ssh"); + std::fs::create_dir_all(&ssh_dir).expect("failed to create .ssh dir"); + for name in names { + std::fs::write(ssh_dir.join(name), "key").expect("failed to write key"); + } + home + } + + #[test] + fn default_ssh_key_paths_lists_existing_keys_in_attempt_order() { + let home = home_with_keys(&["id_rsa", "id_ed25519", "id_other"]); + let paths = default_ssh_key_paths(home.path()); + assert_eq!( + paths, + vec![ + home.path().join(".ssh/id_ed25519"), + home.path().join(".ssh/id_rsa") + ] + ); + } + + #[test] + fn ssh_credentials_hand_out_each_key_once_then_name_them_in_the_error() { + let home = home_with_keys(&["id_ed25519", "id_rsa"]); + let mut ssh = SshCredentials::new(false, default_ssh_key_paths(home.path())); + for _ in 0..2 { + let credential = ssh.next("git").expect("a key file should be offered"); + assert_eq!(credential.credtype(), git2::CredentialType::SSH_KEY.bits()); + } + let message = ssh + .next("git") + .err() + .expect("keys are exhausted") + .to_string(); + assert!(message.contains("id_ed25519"), "{message}"); + assert!(message.contains("id_rsa"), "{message}"); + assert!(ssh.next("git").is_err()); + } + + #[test] + fn ssh_credentials_without_keys_explain_what_to_set_up() { + let mut ssh = SshCredentials::new(false, Vec::new()); + let message = ssh.next("git").err().expect("nothing to offer").to_string(); + assert!(message.contains("~/.ssh/id_ed25519"), "{message}"); + } + /// Clones `remote_path` into a fresh temp dir, returning the clone. fn clone_local(remote_path: &Path) -> (TempDir, std::path::PathBuf) { let local_dir = tempfile::tempdir().expect("failed to create temp dir"); From 65a8fa63b0f0e99014bb2aac2104e2c8b7045f39 Mon Sep 17 00:00:00 2001 From: Fran Tufro Date: Thu, 12 Nov 2026 17:54:39 -0300 Subject: [PATCH 3/3] Skip passphrase-protected SSH keys and always try the agent first libgit2 aborts the connection when handed an encrypted key without its passphrase, so detect OpenSSH and PEM encryption and skip those keys, naming them in the error. A failed agent attempt is an ordinary auth failure that libgit2 retries, so the SSH_AUTH_SOCK gate is dropped. Fix the ARCHITECTURE.md section order and move the task back to doing until the release ships. --- ...ate-over-ssh-with-the-default-key-files.md | 0 docs/ARCHITECTURE.md | 20 +- src/git_sync.rs | 190 +++++++++++++++--- 3 files changed, 171 insertions(+), 39 deletions(-) rename .cubil/{done => doing}/authenticate-over-ssh-with-the-default-key-files.md (100%) diff --git a/.cubil/done/authenticate-over-ssh-with-the-default-key-files.md b/.cubil/doing/authenticate-over-ssh-with-the-default-key-files.md similarity index 100% rename from .cubil/done/authenticate-over-ssh-with-the-default-key-files.md rename to .cubil/doing/authenticate-over-ssh-with-the-default-key-files.md diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d45bcdc..971b0fc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -115,24 +115,24 @@ No manual commit step. Single machine for now — the pull-first step is a forward-looking safety habit, not a full multi-machine conflict-resolution system. +This is distinct from the app repo's own normal development git history — +don't conflate the two. + ### Remote authentication -For SSH remotes husmo tries, in order: a key from the running ssh-agent (only -when `SSH_AUTH_SOCK` is set), then the key files `~/.ssh/id_ed25519`, -`~/.ssh/id_ecdsa` and `~/.ssh/id_rsa` that exist, without a passphrase. Keys -with a passphrase fail and the next candidate is tried. When none is -accepted the error names the key files tried. HTTPS remotes use the git -credential helper, then git2's default credential. `file://` remotes need no -credentials. +For SSH remotes husmo tries, in order: a key from the running ssh-agent, then +the key files `~/.ssh/id_ed25519`, `~/.ssh/id_ecdsa` and `~/.ssh/id_rsa` that +exist. Passphrase-protected key files are skipped, because libgit2 aborts the +connection when given one without its passphrase; load such a key into an +ssh-agent instead. When none is accepted the error names the key files tried +and skipped. HTTPS remotes use the git credential helper, then git2's default +credential. `file://` remotes need no credentials. libgit2 does not read `~/.ssh/config`, so `Port` and `IdentityFile` entries have no effect. A remote on a non-standard port needs an `ssh://` URL that carries the port, for example `ssh://git@host:2222/owner/repo.git`. The short form `git@host:owner/repo.git` connects to port 22. -This is distinct from the app repo's own normal development git history — -don't conflate the two. - ## MCP server - Transport: **stdio, spawned per session** by the MCP client. No diff --git a/src/git_sync.rs b/src/git_sync.rs index 30a79cb..b96d09d 100644 --- a/src/git_sync.rs +++ b/src/git_sync.rs @@ -211,6 +211,75 @@ fn default_ssh_key_paths(home: &Path) -> Vec { .collect() } +/// Whether the private key at `path` is encrypted with a passphrase. +/// +/// libgit2 aborts the whole connection with a hard error when handed an +/// encrypted key and no passphrase, so such keys must be filtered out +/// before they are offered. Recognizes both the OpenSSH format (cipher name +/// other than `none`) and legacy PEM files (`ENCRYPTED` header). A file that +/// cannot be read or parsed counts as unprotected and is left to libgit2 to +/// accept or reject. +fn is_passphrase_protected(path: &Path) -> bool { + let Ok(text) = std::fs::read_to_string(path) else { + return false; + }; + if text.contains("ENCRYPTED") { + return true; + } + let Some(body) = text + .strip_prefix("-----BEGIN OPENSSH PRIVATE KEY-----") + .map(str::trim_start) + else { + return false; + }; + // The cipher name sits in the first 15 + 4 + 16 bytes at most: the + // "openssh-key-v1\0" magic, a u32 length and the name. 64 base64 + // characters decode to 48 bytes, which covers it. + let head: Vec = body + .bytes() + .filter(|byte| !byte.is_ascii_whitespace()) + .take(64) + .collect(); + let bytes = decode_base64_prefix(&head); + let Some(rest) = bytes.strip_prefix(b"openssh-key-v1\0") else { + return false; + }; + let Some((length, rest)) = rest.split_first_chunk::<4>() else { + return false; + }; + let length = u32::from_be_bytes(*length) as usize; + match rest.get(..length) { + Some(cipher) => cipher != b"none", + None => false, + } +} + +/// Decodes standard base64 characters into bytes, stopping at the first +/// character outside the alphabet (such as `=` padding). A trailing partial +/// group yields its complete bytes. +fn decode_base64_prefix(text: &[u8]) -> Vec { + let mut out = Vec::with_capacity(text.len() * 3 / 4); + let mut accumulator: u32 = 0; + let mut bits = 0; + for &byte in text { + let value = match byte { + b'A'..=b'Z' => byte - b'A', + b'a'..=b'z' => byte - b'a' + 26, + b'0'..=b'9' => byte - b'0' + 52, + b'+' => 62, + b'/' => 63, + _ => break, + }; + accumulator = (accumulator << 6) | u32::from(value); + bits += 6; + if bits >= 8 { + bits -= 8; + out.push(u8::try_from((accumulator >> bits) & 0xff).unwrap_or(0)); + } + } + out +} + /// Walks the SSH credential sources one per call. libgit2 invokes the /// credentials callback again after every rejected credential, so each call /// must hand out something new or the connection would retry forever. @@ -221,18 +290,17 @@ struct SshCredentials { keys: std::vec::IntoIter, /// Every key file attempted so far, for the final error message. tried: Vec, + /// Key files passed over because they need a passphrase. + skipped: Vec, } impl SshCredentials { - /// `agent_available` is whether an ssh-agent socket is advertised - /// (`SSH_AUTH_SOCK`). Without one libgit2 aborts the whole connection - /// on the agent attempt, so it is skipped and the key files get their - /// turn. - fn new(agent_available: bool, keys: Vec) -> Self { + fn new(keys: Vec) -> Self { Self { - try_agent: agent_available, + try_agent: true, keys: keys.into_iter(), tried: Vec::new(), + skipped: Vec::new(), } } @@ -244,6 +312,10 @@ impl SshCredentials { } } for key in self.keys.by_ref() { + if is_passphrase_protected(&key) { + self.skipped.push(key); + continue; + } self.tried.push(key.clone()); if let Ok(credential) = git2::Cred::ssh_key(username, None, &key, None) { return Ok(credential); @@ -253,33 +325,47 @@ impl SshCredentials { } fn exhausted_message(&self) -> String { - if self.tried.is_empty() { - "SSH authentication failed: no ssh-agent identity was accepted and none of \ - ~/.ssh/id_ed25519, ~/.ssh/id_ecdsa or ~/.ssh/id_rsa exists; start an \ - ssh-agent with a loaded key or create a passphrase-less key in ~/.ssh" - .to_string() - } else { - let tried: Vec = self - .tried + let list = |paths: &[PathBuf]| { + paths .iter() .map(|path| path.display().to_string()) - .collect(); - format!( - "SSH authentication failed: the ssh-agent (if any) and these key files \ - were not accepted: {}; keys with a passphrase are not supported, so \ - load them into an ssh-agent or use a passphrase-less key", - tried.join(", ") - ) + .collect::>() + .join(", ") + }; + let mut parts = + vec!["SSH authentication failed: no ssh-agent identity was accepted".to_string()]; + if !self.tried.is_empty() { + parts.push(format!( + "these key files were not accepted: {}", + list(&self.tried) + )); + } + if !self.skipped.is_empty() { + parts.push(format!( + "these key files need a passphrase, which husmo cannot supply, so load \ + them into an ssh-agent: {}", + list(&self.skipped) + )); } + if self.tried.is_empty() && self.skipped.is_empty() { + parts.push( + "none of ~/.ssh/id_ed25519, ~/.ssh/id_ecdsa or ~/.ssh/id_rsa exists, \ + so start an ssh-agent with a loaded key or create a passphrase-less \ + key in ~/.ssh" + .to_string(), + ); + } + parts.join("; ") } } /// Builds the remote callbacks used for fetch, push, and (via /// [`crate::init`]) the initial clone. For `git+ssh` remotes the -/// credentials are tried in this order: a key from the running ssh-agent -/// (only when `SSH_AUTH_SOCK` is set), then the key files `~/.ssh/id_ed25519`, -/// `~/.ssh/id_ecdsa` and `~/.ssh/id_rsa` that exist, without a passphrase. -/// When none is accepted the error names the key files tried. For other +/// credentials are tried in this order: a key from the running ssh-agent, +/// then the key files `~/.ssh/id_ed25519`, `~/.ssh/id_ecdsa` and +/// `~/.ssh/id_rsa` that exist and need no passphrase. Passphrase-protected +/// keys are skipped. When none is accepted the error names the key files +/// tried and skipped. For other /// remotes (HTTPS with a stored token/password) it uses a system credential /// helper and finally whatever default credential git2 can produce. Remotes /// that need no authentication at all (e.g. a local `file://` path, as in @@ -305,7 +391,6 @@ pub(crate) fn remote_callbacks(repo: Option<&Repository>) -> git2::RemoteCallbac let ssh = ssh.get_or_insert_with(|| { let home = std::env::var_os("HOME").map(PathBuf::from); SshCredentials::new( - std::env::var_os("SSH_AUTH_SOCK").is_some_and(|sock| !sock.is_empty()), home.map(|home| default_ssh_key_paths(&home)) .unwrap_or_default(), ) @@ -466,7 +551,15 @@ mod tests { use crate::test_support::{empty_bare_remote, seeded_bare_remote}; - use super::{SshCredentials, default_ssh_key_paths}; + use super::{SshCredentials, default_ssh_key_paths, is_passphrase_protected}; + + /// Credentials with the agent attempt switched off: constructing an agent + /// credential always succeeds, so tests would otherwise get it first. + fn key_only(keys: Vec) -> SshCredentials { + let mut ssh = SshCredentials::new(keys); + ssh.try_agent = false; + ssh + } fn home_with_keys(names: &[&str]) -> TempDir { let home = tempfile::tempdir().expect("failed to create temp dir"); @@ -494,7 +587,7 @@ mod tests { #[test] fn ssh_credentials_hand_out_each_key_once_then_name_them_in_the_error() { let home = home_with_keys(&["id_ed25519", "id_rsa"]); - let mut ssh = SshCredentials::new(false, default_ssh_key_paths(home.path())); + let mut ssh = key_only(default_ssh_key_paths(home.path())); for _ in 0..2 { let credential = ssh.next("git").expect("a key file should be offered"); assert_eq!(credential.credtype(), git2::CredentialType::SSH_KEY.bits()); @@ -509,9 +602,48 @@ mod tests { assert!(ssh.next("git").is_err()); } + fn key_file(contents: &str) -> (TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().expect("failed to create temp dir"); + let path = dir.path().join("id_test"); + std::fs::write(&path, contents).expect("failed to write key"); + (dir, path) + } + + #[test] + fn is_passphrase_protected_recognizes_openssh_and_pem_encryption() { + let (_a, unencrypted) = key_file( + "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEYmNyeXB0AAAAAAAAAAAAAAAAAAAAAAAAAA\nA=\n-----END OPENSSH PRIVATE KEY-----\n", + ); + let (_b, encrypted) = key_file( + "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAEYmNyeXB0AAAAAAAAAAAAAAAAAA\nAAAAAAAAA=\n-----END OPENSSH PRIVATE KEY-----\n", + ); + let (_c, legacy) = key_file( + "-----BEGIN RSA PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,00\n\nAAAA\n-----END RSA PRIVATE KEY-----\n", + ); + let (_d, plain_pem) = + key_file("-----BEGIN RSA PRIVATE KEY-----\nAAAA\n-----END RSA PRIVATE KEY-----\n"); + assert!(!is_passphrase_protected(&unencrypted)); + assert!(is_passphrase_protected(&encrypted)); + assert!(is_passphrase_protected(&legacy)); + assert!(!is_passphrase_protected(&plain_pem)); + assert!(!is_passphrase_protected(Path::new("/nonexistent/key"))); + } + + #[test] + fn ssh_credentials_skip_passphrase_keys_and_say_so_in_the_error() { + let home = tempfile::tempdir().expect("failed to create temp dir"); + let ssh_dir = home.path().join(".ssh"); + std::fs::create_dir_all(&ssh_dir).expect("failed to create .ssh dir"); + std::fs::write(ssh_dir.join("id_ed25519"), "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAEYmNyeXB0AAAAAAAAAAAAAAAAAA\nAAAAAAAAA=\n-----END OPENSSH PRIVATE KEY-----\n").expect("failed to write key"); + let mut ssh = key_only(default_ssh_key_paths(home.path())); + let message = ssh.next("git").err().expect("nothing usable").to_string(); + assert!(message.contains("need a passphrase"), "{message}"); + assert!(message.contains("id_ed25519"), "{message}"); + } + #[test] fn ssh_credentials_without_keys_explain_what_to_set_up() { - let mut ssh = SshCredentials::new(false, Vec::new()); + let mut ssh = key_only(Vec::new()); let message = ssh.next("git").err().expect("nothing to offer").to_string(); assert!(message.contains("~/.ssh/id_ed25519"), "{message}"); }