Skip to main content

agent_hub_runtime/core/
git_credentials.rs

1//! Credential handling for the git backup remote.
2//!
3//! Policy (backup redesign §3.7): tokens must never live in URLs on disk
4//! (`.git/config`, SQLite settings). Credentials embedded in a remote URL are
5//! saved in owner-only local credential files and injected into git through
6//! a noninteractive helper that reads credentials from environment variables.
7
8use 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
18/// Debug binaries are ad-hoc signed on macOS. Their code signature changes on
19/// every rebuild, so background reads can repeatedly trigger a Keychain ACL
20/// prompt. Keep legacy Keychain migration off in development unless explicitly opted in.
21/// Local credential files and gh authentication do not need this opt-in.
22pub 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
40/// Environment variable names consumed by the askpass script. The script
41/// itself contains no secrets — it just echoes these back to git.
42const 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
51/// Split userinfo credentials out of an http(s) URL.
52///
53/// Returns the extracted credential plus the sanitized URL (no userinfo).
54/// `None` when the URL is not http(s) or carries no userinfo. A token-only
55/// form (`https://TOKEN@host/...`) is kept faithful: username = token,
56/// password = empty — exactly what git derived from the embedded URL.
57pub 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
97/// Host (including port, if any) of an http(s) URL with userinfo stripped.
98/// Used as the keychain account key.
99pub 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            // One-time migration only. Subsequent processes read the local file;
142            // repeated syncs in this process use the memory cache.
143            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    // Skipping a migration must not persist a logout marker: a later signed
166    // build (or explicit opt-in) still needs to recover the old credential.
167    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
181/// Attach a credentials callback to libgit2 network operations against `url`.
182///
183/// Sources, in order: the credential this app cached locally for the
184/// host, then the user's git credential helper (osxkeychain, Git Credential
185/// Manager, libsecret) — the same place system git would have looked — then an
186/// ssh-agent key for ssh remotes.
187///
188/// The helper fallback is the one that matters for skill sources. The keychain
189/// only holds hosts this app connected itself, which in practice means the
190/// backup remote; a skill living on a private GitLab or Gitea has no entry
191/// there and would still fail with a keychain-only callback.
192///
193/// Without any callback libgit2 reports "no callback set" (#379). A desktop
194/// launch hits that whenever the system-git attempt fails first: a GUI process
195/// has a leaner PATH than a shell and cannot prompt, so it falls through to
196/// libgit2 — which is why the same skill checks fine from the CLI.
197///
198/// Each source is offered once. libgit2 re-invokes this callback after every
199/// rejection, so a source that answers unconditionally would spin forever.
200pub fn install_git2_credentials(callbacks: &mut git2::RemoteCallbacks<'_>, url: &str) {
201    // Resolve the host now, but read the keychain only from inside the callback:
202    // libgit2 invokes it solely when the remote actually demands credentials, and
203    // almost every skill source is a public repository that never will. Reading
204    // eagerly would touch the keychain on every update check for nothing — and on
205    // macOS each unsigned build that does so raises an authorization prompt.
206    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        // Phrased for the user, not for libgit2: this string reaches the UI.
243        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
251// Git invokes this helper before considering interactive prompts. Values live
252// only in the child environment; get is host-scoped, store/erase are no-ops.
253const 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
263/// Environment to inject into a git subprocess so it can authenticate against
264/// `url` without credentials on disk. Empty when not applicable: non-http(s)
265/// URL, URL still carrying embedded userinfo (git uses it directly), or no
266/// stored credential for the host.
267pub 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    // Preserve inherited config while replacing interactive credential helpers.
287    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/// Route all keyring access in this test process to keyring's in-memory mock
317/// store, so tests never touch the developer's real OS keychain.
318#[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;