agent_hub_runtime/core/
git_credentials.rs1use anyhow::{Context, Result};
9use std::sync::OnceLock;
10
11use super::central_repo;
12
13fn credential_cache() -> &'static super::credential_cache::CredentialCache {
14 static CACHE: OnceLock<super::credential_cache::CredentialCache> = OnceLock::new();
15 CACHE.get_or_init(Default::default)
16}
17
18pub fn background_access_enabled() -> bool {
23 #[cfg(debug_assertions)]
24 {
25 std::env::var("AGENT_HUB_DEV_KEYCHAIN")
26 .map(|value| {
27 matches!(
28 value.trim().to_ascii_lowercase().as_str(),
29 "1" | "true" | "on"
30 )
31 })
32 .unwrap_or(false)
33 }
34 #[cfg(not(debug_assertions))]
35 {
36 true
37 }
38}
39
40const ENV_USERNAME: &str = "AGENT_HUB_ASKPASS_USERNAME";
43const ENV_PASSWORD: &str = "AGENT_HUB_ASKPASS_PASSWORD";
44
45#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
46pub struct RemoteCredential {
47 pub username: String,
48 pub password: String,
49}
50
51pub fn split_credentials_from_url(url: &str) -> Option<(RemoteCredential, String)> {
58 let trimmed = url.trim();
59 let lower = trimmed.to_lowercase();
60 if !lower.starts_with("https://") && !lower.starts_with("http://") {
61 return None;
62 }
63 let scheme_end = trimmed.find("://")? + 3;
64 let rest = &trimmed[scheme_end..];
65 let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
66 let authority = &rest[..authority_end];
67
68 let at_pos = authority.rfind('@')?;
69 let userinfo = &authority[..at_pos];
70 let host_part = &authority[at_pos + 1..];
71
72 let (raw_user, raw_pass) = match userinfo.split_once(':') {
73 Some((u, p)) => (u, p),
74 None => (userinfo, ""),
75 };
76 let decode = |s: &str| {
77 urlencoding::decode(s)
78 .map(|c| c.into_owned())
79 .unwrap_or_else(|_| s.to_string())
80 };
81
82 let sanitized = format!(
83 "{}{}{}",
84 &trimmed[..scheme_end],
85 host_part,
86 &rest[authority_end..]
87 );
88 Some((
89 RemoteCredential {
90 username: decode(raw_user),
91 password: decode(raw_pass),
92 },
93 sanitized,
94 ))
95}
96
97pub fn https_host(url: &str) -> Option<String> {
100 let trimmed = url.trim();
101 let lower = trimmed.to_lowercase();
102 if !lower.starts_with("https://") && !lower.starts_with("http://") {
103 return None;
104 }
105 let scheme_end = trimmed.find("://")? + 3;
106 let rest = &trimmed[scheme_end..];
107 let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
108 let authority = &rest[..authority_end];
109 let host = match authority.rfind('@') {
110 Some(at) => &authority[at + 1..],
111 None => authority,
112 };
113 if host.is_empty() {
114 return None;
115 }
116 Some(host.to_ascii_lowercase())
117}
118
119fn keyring_entry(host: &str) -> Result<keyring::Entry> {
120 keyring::Entry::new(&crate::product::credential_service(), host)
121 .context("Failed to open keychain entry")
122}
123
124fn cache_key(host: &str) -> String {
125 format!(
126 "{}|{}",
127 central_repo::base_dir().display(),
128 host.to_ascii_lowercase()
129 )
130}
131
132pub fn store_credential(host: &str, cred: &RemoteCredential) -> Result<()> {
133 credential_cache().write(&cache_key(host), Some(cred.clone()), || {
134 super::credential_file::write(host, Some(cred))
135 })
136}
137
138pub fn load_credential(host: &str) -> Result<Option<RemoteCredential>> {
139 credential_cache().read(&cache_key(host), || {
140 load_persistent(host, background_access_enabled(), || {
141 let value = match keyring_entry(host)?.get_password() {
144 Ok(payload) => {
145 Some(serde_json::from_str(&payload).context("Corrupted legacy Git credential")?)
146 }
147 Err(keyring::Error::NoEntry) => None,
148 Err(error) => return Err(error).context(
149 "Cannot migrate legacy Git credential; sign in again to save a local credential",
150 ),
151 };
152 Ok(value)
153 })
154 })
155}
156
157fn load_persistent(
158 host: &str,
159 allow_legacy: bool,
160 legacy: impl FnOnce() -> Result<Option<RemoteCredential>>,
161) -> Result<Option<RemoteCredential>> {
162 if let Some(value) = super::credential_file::read(host)? {
163 return Ok(value);
164 }
165 if !allow_legacy {
168 return Ok(None);
169 }
170 let value = legacy()?;
171 super::credential_file::write(host, value.as_ref())?;
172 Ok(value)
173}
174
175pub fn delete_credential(host: &str) -> Result<()> {
176 credential_cache().write(&cache_key(host), None, || {
177 super::credential_file::write(host, None)
178 })
179}
180
181pub fn install_git2_credentials(callbacks: &mut git2::RemoteCallbacks<'_>, url: &str) {
201 let host = https_host(url);
207 let host_label = host.clone().unwrap_or_else(|| "this remote".to_string());
208 let mut tried_stored = false;
209 let mut tried_helper = false;
210 let mut tried_agent = false;
211
212 callbacks.credentials(move |url, username_from_url, allowed| {
213 if allowed.contains(git2::CredentialType::USER_PASS_PLAINTEXT) {
214 if !tried_stored {
215 tried_stored = true;
216 if let Some(cred) = host
217 .as_deref()
218 .and_then(|h| super::git_auth_source::resolve(h).ok().flatten())
219 {
220 return git2::Cred::userpass_plaintext(&cred.username, &cred.password);
221 }
222 }
223 if !tried_helper {
224 tried_helper = true;
225 if let Ok(config) = git2::Config::open_default() {
226 if let Ok(cred) = git2::Cred::credential_helper(&config, url, username_from_url)
227 {
228 return Ok(cred);
229 }
230 }
231 }
232 }
233 if allowed.contains(git2::CredentialType::SSH_KEY) && !tried_agent {
234 tried_agent = true;
235 if let Some(user) = username_from_url {
236 return git2::Cred::ssh_key_from_agent(user);
237 }
238 }
239 if allowed.contains(git2::CredentialType::DEFAULT) {
240 return git2::Cred::default();
241 }
242 Err(git2::Error::from_str(&format!(
244 "Authentication failed: no credentials available for {host_label}. \
245 Sign in to that host with git (for example `gh auth setup-git` for \
246 GitHub), then check for updates again."
247 )))
248 });
249}
250
251const CREDENTIAL_HELPER: &str = r#"!f() {
254 [ "$1" = get ] || return 0
255 h=; p=
256 while IFS= read -r line && [ -n "$line" ]; do
257 case "$line" in host=*) h=${line#host=} ;; protocol=*) p=${line#protocol=} ;; esac
258 done
259 [ "$h" = "$AGENT_HUB_CREDENTIAL_HOST" ] || return 0
260 case "$p" in http|https) printf 'username=%s\npassword=%s\n\n' "$AGENT_HUB_ASKPASS_USERNAME" "$AGENT_HUB_ASKPASS_PASSWORD" ;; esac
261}; f"#;
262
263pub fn credential_env_for_url(url: &str) -> Vec<(String, String)> {
268 let Some(host) = https_host(url) else {
269 return Vec::new();
270 };
271 if split_credentials_from_url(url).is_some() {
272 return Vec::new();
273 }
274 let cred = match super::git_auth_source::resolve(&host) {
275 Ok(Some(cred)) => cred,
276 Ok(None) => return Vec::new(),
277 Err(e) => {
278 log::warn!("git credentials: credential lookup failed for {host}: {e:#}");
279 return Vec::new();
280 }
281 };
282 credential_env(cred, &host)
283}
284
285fn credential_env(cred: RemoteCredential, host: &str) -> Vec<(String, String)> {
286 let config_count = std::env::var("GIT_CONFIG_COUNT")
288 .ok()
289 .and_then(|value| value.parse::<usize>().ok())
290 .unwrap_or(0);
291 vec![
292 ("AGENT_HUB_CREDENTIAL_HOST".to_string(), host.to_string()),
293 (ENV_USERNAME.to_string(), cred.username),
294 (ENV_PASSWORD.to_string(), cred.password),
295 ("GIT_TERMINAL_PROMPT".to_string(), "0".to_string()),
296 (
297 "GIT_CONFIG_COUNT".to_string(),
298 (config_count + 2).to_string(),
299 ),
300 (
301 format!("GIT_CONFIG_KEY_{config_count}"),
302 "credential.helper".to_string(),
303 ),
304 (format!("GIT_CONFIG_VALUE_{config_count}"), String::new()),
305 (
306 format!("GIT_CONFIG_KEY_{}", config_count + 1),
307 "credential.helper".to_string(),
308 ),
309 (
310 format!("GIT_CONFIG_VALUE_{}", config_count + 1),
311 CREDENTIAL_HELPER.to_string(),
312 ),
313 ]
314}
315
316#[cfg(test)]
319pub(crate) fn use_mock_keyring() {
320 static INIT: std::sync::Once = std::sync::Once::new();
321 INIT.call_once(|| {
322 keyring::set_default_credential_builder(keyring::mock::default_credential_builder());
323 });
324}
325
326#[cfg(test)]
327mod tests;