diff --git a/.cubil/doing/authenticate-over-ssh-with-the-default-key-files.md b/.cubil/doing/authenticate-over-ssh-with-the-default-key-files.md new file mode 100644 index 0000000..8149ea7 --- /dev/null +++ b/.cubil/doing/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. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9aff3f9..971b0fc 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -118,6 +118,21 @@ 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, 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. + ## 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 3c743c0..b96d09d 100644 --- a/src/git_sync.rs +++ b/src/git_sync.rs @@ -198,13 +198,182 @@ 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() +} + +/// 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. +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, + /// Key files passed over because they need a passphrase. + skipped: Vec, +} + +impl SshCredentials { + fn new(keys: Vec) -> Self { + Self { + try_agent: true, + keys: keys.into_iter(), + tried: Vec::new(), + skipped: 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() { + 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); + } + } + Err(git2::Error::from_str(&self.exhausted_message())) + } + + fn exhausted_message(&self) -> String { + let list = |paths: &[PathBuf]| { + paths + .iter() + .map(|path| path.display().to_string()) + .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: 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, +/// 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 +/// 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 +383,19 @@ 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( + 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 +551,103 @@ mod tests { use crate::test_support::{empty_bare_remote, seeded_bare_remote}; + 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"); + 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 = 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()); + } + 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()); + } + + 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 = key_only(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");