From 28a2c534a0309a92379c76282ace666900f29619 Mon Sep 17 00:00:00 2001 From: Martin von Zweigbergk Date: Sat, 9 Oct 2021 09:13:06 -0700 Subject: [PATCH] git: add support for password-less SSH keys My SSH keys are password-protected, so I haven't been able to test this patch completely, but I believe it should work. We now use ssh-agent if `$SSH_AGENT_PID` is set, otherwise we check if `$HOME/.ssh/id_rsa` exists and assume it's a password-less key. That's quite hacky but I think it's good enough for now. We eventually need to move this out of the library crate just like libgit2 has done. Closes #25. --- lib/src/git.rs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/src/git.rs b/lib/src/git.rs index 7621f4b8f..e4a1de0c0 100644 --- a/lib/src/git.rs +++ b/lib/src/git.rs @@ -315,8 +315,21 @@ fn push_refs( fn create_remote_callbacks() -> RemoteCallbacks<'static> { let mut callbacks = git2::RemoteCallbacks::new(); - callbacks.credentials(|_url, username_from_url, _allowed_types| { - git2::Cred::ssh_key_from_agent(username_from_url.unwrap()) + // TODO: We should expose the callbacks to the caller instead -- the library + // crate shouldn't look in $HOME etc. + callbacks.credentials(|_url, username_from_url, allowed_types| { + if allowed_types.contains(git2::CredentialType::SSH_KEY) { + if std::env::var("SSH_AGENT_PID").is_ok() { + return git2::Cred::ssh_key_from_agent(username_from_url.unwrap()); + } + if let Ok(home_dir) = std::env::var("HOME") { + let key_path = std::path::Path::new(&home_dir).join(".ssh").join("id_rsa"); + if key_path.is_file() { + return git2::Cred::ssh_key(username_from_url.unwrap(), None, &key_path, None); + } + } + } + git2::Cred::default() }); callbacks }