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.
This commit is contained in:
Martin von Zweigbergk 2021-10-09 09:13:06 -07:00
parent fc883d1d02
commit 28a2c534a0

View file

@ -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
}