use anyhow::{Context, Result};
use std::sync::OnceLock;
use super::central_repo;
fn credential_cache() -> &'static super::credential_cache::CredentialCache {
static CACHE: OnceLock<super::credential_cache::CredentialCache> = OnceLock::new();
CACHE.get_or_init(Default::default)
}
pub fn background_access_enabled() -> bool {
#[cfg(debug_assertions)]
{
std::env::var("AGENT_HUB_DEV_KEYCHAIN")
.map(|value| {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"1" | "true" | "on"
)
})
.unwrap_or(false)
}
#[cfg(not(debug_assertions))]
{
true
}
}
const ENV_USERNAME: &str = "AGENT_HUB_ASKPASS_USERNAME";
const ENV_PASSWORD: &str = "AGENT_HUB_ASKPASS_PASSWORD";
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct RemoteCredential {
pub username: String,
pub password: String,
}
pub fn split_credentials_from_url(url: &str) -> Option<(RemoteCredential, String)> {
let trimmed = url.trim();
let lower = trimmed.to_lowercase();
if !lower.starts_with("https://") && !lower.starts_with("http://") {
return None;
}
let scheme_end = trimmed.find("://")? + 3;
let rest = &trimmed[scheme_end..];
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let authority = &rest[..authority_end];
let at_pos = authority.rfind('@')?;
let userinfo = &authority[..at_pos];
let host_part = &authority[at_pos + 1..];
let (raw_user, raw_pass) = match userinfo.split_once(':') {
Some((u, p)) => (u, p),
None => (userinfo, ""),
};
let decode = |s: &str| {
urlencoding::decode(s)
.map(|c| c.into_owned())
.unwrap_or_else(|_| s.to_string())
};
let sanitized = format!(
"{}{}{}",
&trimmed[..scheme_end],
host_part,
&rest[authority_end..]
);
Some((
RemoteCredential {
username: decode(raw_user),
password: decode(raw_pass),
},
sanitized,
))
}
pub fn https_host(url: &str) -> Option<String> {
let trimmed = url.trim();
let lower = trimmed.to_lowercase();
if !lower.starts_with("https://") && !lower.starts_with("http://") {
return None;
}
let scheme_end = trimmed.find("://")? + 3;
let rest = &trimmed[scheme_end..];
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
let authority = &rest[..authority_end];
let host = match authority.rfind('@') {
Some(at) => &authority[at + 1..],
None => authority,
};
if host.is_empty() {
return None;
}
Some(host.to_ascii_lowercase())
}
fn keyring_entry(host: &str) -> Result<keyring::Entry> {
keyring::Entry::new(&crate::product::credential_service(), host)
.context("Failed to open keychain entry")
}
fn cache_key(host: &str) -> String {
format!(
"{}|{}",
central_repo::base_dir().display(),
host.to_ascii_lowercase()
)
}
pub fn store_credential(host: &str, cred: &RemoteCredential) -> Result<()> {
credential_cache().write(&cache_key(host), Some(cred.clone()), || {
super::credential_file::write(host, Some(cred))
})
}
pub fn load_credential(host: &str) -> Result<Option<RemoteCredential>> {
credential_cache().read(&cache_key(host), || {
load_persistent(host, background_access_enabled(), || {
let value = match keyring_entry(host)?.get_password() {
Ok(payload) => {
Some(serde_json::from_str(&payload).context("Corrupted legacy Git credential")?)
}
Err(keyring::Error::NoEntry) => None,
Err(error) => return Err(error).context(
"Cannot migrate legacy Git credential; sign in again to save a local credential",
),
};
Ok(value)
})
})
}
fn load_persistent(
host: &str,
allow_legacy: bool,
legacy: impl FnOnce() -> Result<Option<RemoteCredential>>,
) -> Result<Option<RemoteCredential>> {
if let Some(value) = super::credential_file::read(host)? {
return Ok(value);
}
if !allow_legacy {
return Ok(None);
}
let value = legacy()?;
super::credential_file::write(host, value.as_ref())?;
Ok(value)
}
pub fn delete_credential(host: &str) -> Result<()> {
credential_cache().write(&cache_key(host), None, || {
super::credential_file::write(host, None)
})
}
pub fn install_git2_credentials(callbacks: &mut git2::RemoteCallbacks<'_>, url: &str) {
let host = https_host(url);
let host_label = host.clone().unwrap_or_else(|| "this remote".to_string());
let mut tried_stored = false;
let mut tried_helper = false;
let mut tried_agent = false;
callbacks.credentials(move |url, username_from_url, allowed| {
if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
if !tried_stored {
tried_stored = true;
if let Some(cred) = host
.as_deref()
.and_then(|h| super::git_auth_source::resolve(h).ok().flatten())
{
return git2::Cred::userpass_plaintext(&cred.username, &cred.password);
}
}
if !tried_helper {
tried_helper = true;
if let Ok(config) = git2::Config::open_default() {
if let Ok(cred) = git2::Cred::credential_helper(&config, url, username_from_url)
{
return Ok(cred);
}
}
}
}
if allowed.contains(git2::CredentialType::SSH_KEY) && !tried_agent {
tried_agent = true;
if let Some(user) = username_from_url {
return git2::Cred::ssh_key_from_agent(user);
}
}
if allowed.contains(git2::CredentialType::DEFAULT) {
return git2::Cred::default();
}
Err(git2::Error::from_str(&format!(
"Authentication failed: no credentials available for {host_label}. \
Sign in to that host with git (for example `gh auth setup-git` for \
GitHub), then check for updates again."
)))
});
}
const CREDENTIAL_HELPER: &str = r#"!f() {
[ "$1" = get ] || return 0
h=; p=
while IFS= read -r line && [ -n "$line" ]; do
case "$line" in host=*) h=${line#host=} ;; protocol=*) p=${line#protocol=} ;; esac
done
[ "$h" = "$AGENT_HUB_CREDENTIAL_HOST" ] || return 0
case "$p" in http|https) printf 'username=%s\npassword=%s\n\n' "$AGENT_HUB_ASKPASS_USERNAME" "$AGENT_HUB_ASKPASS_PASSWORD" ;; esac
}; f"#;
pub fn credential_env_for_url(url: &str) -> Vec<(String, String)> {
let Some(host) = https_host(url) else {
return Vec::new();
};
if split_credentials_from_url(url).is_some() {
return Vec::new();
}
let cred = match super::git_auth_source::resolve(&host) {
Ok(Some(cred)) => cred,
Ok(None) => return Vec::new(),
Err(e) => {
log::warn!("git credentials: credential lookup failed for {host}: {e:#}");
return Vec::new();
}
};
credential_env(cred, &host)
}
fn credential_env(cred: RemoteCredential, host: &str) -> Vec<(String, String)> {
let config_count = std::env::var("GIT_CONFIG_COUNT")
.ok()
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(0);
vec![
("AGENT_HUB_CREDENTIAL_HOST".to_string(), host.to_string()),
(ENV_USERNAME.to_string(), cred.username),
(ENV_PASSWORD.to_string(), cred.password),
("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),
(
"GIT_CONFIG_COUNT".to_string(),
(config_count + 2).to_string(),
),
(
format!("GIT_CONFIG_KEY_{config_count}"),
"credential.helper".to_string(),
),
(format!("GIT_CONFIG_VALUE_{config_count}"), String::new()),
(
format!("GIT_CONFIG_KEY_{}", config_count + 1),
"credential.helper".to_string(),
),
(
format!("GIT_CONFIG_VALUE_{}", config_count + 1),
CREDENTIAL_HELPER.to_string(),
),
]
}
#[cfg(test)]
pub(crate) fn use_mock_keyring() {
static INIT: std::sync::Once = std::sync::Once::new();
INIT.call_once(|| {
keyring::set_default_credential_builder(keyring::mock::default_credential_builder());
});
}
#[cfg(test)]
mod tests;