Skip to main content

grit_lib/
credentials.rs

1//! Credential layer — Git-compatible credential filling/approval/rejection for
2//! library embedders.
3//!
4//! It exposes:
5//!
6//! - [`Credential`] — a structured credential with the standard Git fields
7//!   ([`protocol`](Credential::protocol), [`host`](Credential::host),
8//!   [`path`](Credential::path), [`username`](Credential::username),
9//!   [`password`](Credential::password), [`url`](Credential::url)) plus
10//!   parsing/serialization in Git's `key=value\n…\n\n` credential wire format
11//!   ([`Credential::parse`] / [`Credential::serialize`]).
12//! - [`CredentialProvider`] — the pluggable seam an embedder implements (or
13//!   wraps) to supply credentials.
14//! - [`HelperCredentialProvider`] — the Git-compatible default that runs the
15//!   configured `credential.helper` / `credential.<url>.helper` programs
16//!   (shell `!cmd`, the built-in `store`/`cache` helpers, and external
17//!   `git-credential-*` binaries), then falls back to an askpass program.
18//! - [`helper_config_value`] — formats a program path and arguments as a
19//!   `credential.helper` value that both Git and grit run directly.
20//!
21//! ## Askpass, never a terminal
22//!
23//! When the configured helpers cannot supply a usable username/password,
24//! [`HelperCredentialProvider`] asks the askpass program set with
25//! [`HelperCredentialProvider::with_askpass`] for the missing fields, as Git
26//! does. [`askpass_program`] resolves that program from `GIT_ASKPASS`,
27//! `core.askPass` and `SSH_ASKPASS`; this is how CI systems inject tokens
28//! non-interactively. `credential.interactive=false` (or `never`) disables
29//! the fallback.
30//!
31//! The provider **never** prompts on a TTY. Without an askpass program, or
32//! when it is disabled, [`fill`](CredentialProvider::fill) returns the typed
33//! [`RemoteError::CredentialsUnavailable`](crate::remote::RemoteError::CredentialsUnavailable) (displayed as [`NON_INTERACTIVE_MESSAGE`],
34//! listing the helpers that were asked) rather than blocking on `/dev/tty`.
35//! Callers that want a person to supply a username and password store it up
36//! front with [`CredentialProvider::approve`], as `grit auth <url> --username
37//! <user> --token <token>` does.
38
39use std::collections::HashSet;
40use std::ffi::OsString;
41use std::path::{Path, PathBuf};
42use std::sync::{Arc, OnceLock};
43
44use crate::command_runner::{
45    system_command_runner, CommandEnvironment, CommandRunner, CommandSpec, CommandStdin,
46    CommandStdio, ShellInvocation,
47};
48use crate::config::{parse_bool, parse_path, ConfigSet};
49use crate::environment::Environment;
50use crate::error::{Error, Result};
51use crate::remote::RemoteError;
52
53fn credential_err(message: impl Into<String>) -> Error {
54    Error::Remote(RemoteError::Credential {
55        detail: message.into(),
56    })
57}
58
59/// How [`RemoteError::CredentialsUnavailable`](crate::remote::RemoteError::CredentialsUnavailable) displays: credentials are required but
60/// no configured helper could supply a complete username/password and no
61/// askpass program is available to ask for them.
62pub const NON_INTERACTIVE_MESSAGE: &str = "credentials required but unavailable (non-interactive)";
63
64/// The askpass program Git would run to ask for a missing username or
65/// password.
66///
67/// The first of these that is set wins: the `GIT_ASKPASS` environment
68/// variable, the `core.askPass` config value (with `~/` expanded), then the
69/// `SSH_ASKPASS` environment variable. As in Git, a source that is set to an
70/// empty value stops the search and disables askpass.
71///
72/// # Parameters
73///
74/// * `env` — the environment to read `GIT_ASKPASS` / `SSH_ASKPASS` (and `HOME`
75///   for `~/`) from; pass [`Environment::empty`] to consult config only.
76/// * `config` — merged config holding `core.askPass`.
77///
78/// # Returns
79///
80/// The program to pass to [`HelperCredentialProvider::with_askpass`], or
81/// `None` when askpass is not configured.
82#[must_use]
83#[cfg_attr(not(feature = "http-ureq"), allow(dead_code))]
84pub(crate) fn askpass_program(env: &Environment, config: &ConfigSet) -> Option<PathBuf> {
85    let program = env
86        .var_os("GIT_ASKPASS")
87        .or_else(|| {
88            config
89                .value("core.askPass")
90                .map(|value| parse_path(env, &value).into())
91        })
92        .or_else(|| env.var_os("SSH_ASKPASS"))?;
93    (!program.is_empty()).then(|| PathBuf::from(program))
94}
95
96/// A structured Git credential.
97///
98/// Mirrors the fields Git's credential protocol exchanges. Round-trips through
99/// the `key=value\n…\n\n` wire format via [`Credential::parse`] and
100/// [`Credential::serialize`]. Any keys outside the named fields below
101/// (`capability[]`, `authtype`, `password_expiry_utc`, …) are preserved in
102/// [`extra`](Credential::extra) so they survive a parse/serialize round-trip
103/// and are forwarded to helpers unchanged.
104#[derive(Clone, Debug, Default, PartialEq, Eq)]
105pub struct Credential {
106    /// `protocol` field (e.g. `https`, `http`, `ssh`).
107    pub protocol: Option<String>,
108    /// `host` field, optionally including a `:port` suffix.
109    pub host: Option<String>,
110    /// `path` field (repository path on the host).
111    pub path: Option<String>,
112    /// `username` field.
113    pub username: Option<String>,
114    /// `password` field (the secret).
115    pub password: Option<String>,
116    /// `url` field — a full URL Git can decompose into the fields above.
117    ///
118    /// [`HelperCredentialProvider`] uses it to match `credential.<url>.*`
119    /// config (see [`target_url`](Credential::target_url)) and to fill a
120    /// missing protocol/host, but never writes it to a helper: helpers such as
121    /// `git-credential-store` would otherwise key the lookup on its path.
122    pub url: Option<String>,
123    /// Any additional `key=value` pairs, in wire order. Multi-valued keys such
124    /// as `capability[]` may appear more than once.
125    pub extra: Vec<(String, String)>,
126}
127
128impl Credential {
129    /// Parse a credential from Git's `key=value\n…` wire format.
130    ///
131    /// Parsing stops at the first blank line (Git's record terminator) or at
132    /// EOF. Trailing `\r` is stripped from each line so the parser accepts both
133    /// LF and CRLF input. Lines without an `=` are ignored.
134    pub fn parse(input: &str) -> Self {
135        let mut cred = Credential::default();
136        for line in input.lines() {
137            let line = line.trim_end_matches('\r');
138            if line.is_empty() {
139                break;
140            }
141            let Some((key, value)) = line.split_once('=') else {
142                continue;
143            };
144            cred.set(key, value);
145        }
146        cred
147    }
148
149    /// The credential Git requests for the repository at `url`.
150    ///
151    /// `protocol` and `host` (with any `:port`) come from `url`, and
152    /// [`url`](Credential::url) keeps `url` itself so `credential.<url>.*`
153    /// config still matches on the full repository path. For `http` and
154    /// `https` the `path` is only included when `credential.useHttpPath`
155    /// applies to `url`, so one host-level entry (as written by
156    /// `git-credential-store` or a keychain helper) serves every repository on
157    /// the host. Other protocols always carry the path. The path is
158    /// percent-decoded and has surrounding slashes removed, as in Git.
159    ///
160    /// A `user[:password]@` in the URL becomes the percent-decoded
161    /// [`username`](Credential::username) and
162    /// [`password`](Credential::password), so a URL with both is already
163    /// complete and a username-only URL is only asked for its password. The
164    /// stored [`url`](Credential::url) has the userinfo removed, so the secret
165    /// never reaches config matching or messages built from it.
166    ///
167    /// Pass the repository URL (`https://host/owner/repo.git`), not a
168    /// smart-HTTP request URL with `/info/refs` and a query appended.
169    ///
170    /// # Returns
171    ///
172    /// `None` when `url` does not parse or has no host.
173    #[must_use]
174    pub fn from_url(url: &str, config: &ConfigSet) -> Option<Self> {
175        let parsed = url::Url::parse(url).ok()?;
176        let host = parsed.host_str().filter(|host| !host.is_empty())?;
177        let host = match parsed.port() {
178            Some(port) => format!("{host}:{port}"),
179            None => host.to_owned(),
180        };
181        let protocol = parsed.scheme();
182        let url = url_without_userinfo(url);
183        let is_http = matches!(protocol, "http" | "https");
184        let path = (!is_http || use_http_path(config, Some(&url)))
185            .then(|| percent_decode_lossy(parsed.path().trim_matches('/')))
186            .filter(|path| !path.is_empty());
187        let username = Some(parsed.username())
188            .filter(|user| !user.is_empty())
189            .map(percent_decode_lossy);
190        Some(Credential {
191            protocol: Some(protocol.to_owned()),
192            host: Some(host),
193            path,
194            password: parsed.password().map(percent_decode_lossy),
195            username,
196            url: Some(url),
197            ..Default::default()
198        })
199    }
200
201    /// Parse from raw bytes (lossy UTF-8); convenience for helper stdout.
202    pub fn parse_bytes(bytes: &[u8]) -> Self {
203        Self::parse(&String::from_utf8_lossy(bytes))
204    }
205
206    /// Serialize to Git's `key=value\n` wire format (no trailing blank line).
207    ///
208    /// Fields are emitted in Git's canonical order
209    /// (protocol, host, path, username, password, url) followed by any
210    /// [`extra`](Credential::extra) entries in their stored order.
211    pub fn serialize(&self) -> String {
212        let mut out = String::new();
213        for (key, value) in self.iter_pairs() {
214            out.push_str(&key);
215            out.push('=');
216            out.push_str(&value);
217            out.push('\n');
218        }
219        out
220    }
221
222    /// Set a field by its Git key name. Unknown keys land in
223    /// [`extra`](Credential::extra). Multi-valued keys (those ending in `[]`)
224    /// always append; named keys overwrite.
225    fn set(&mut self, key: &str, value: &str) {
226        match key {
227            "protocol" => self.protocol = Some(value.to_string()),
228            "host" => self.host = Some(value.to_string()),
229            "path" => self.path = Some(value.to_string()),
230            "username" => self.username = Some(value.to_string()),
231            "password" => self.password = Some(value.to_string()),
232            "url" => self.url = Some(value.to_string()),
233            _ => {
234                if key.ends_with("[]") {
235                    self.extra.push((key.to_string(), value.to_string()));
236                } else if let Some(slot) = self
237                    .extra
238                    .iter_mut()
239                    .find(|(k, _)| k == key)
240                    .map(|(_, v)| v)
241                {
242                    *slot = value.to_string();
243                } else {
244                    self.extra.push((key.to_string(), value.to_string()));
245                }
246            }
247        }
248    }
249
250    /// Look up an `extra` key (first match).
251    fn extra_get(&self, key: &str) -> Option<&str> {
252        self.extra
253            .iter()
254            .find(|(k, _)| k == key)
255            .map(|(_, v)| v.as_str())
256    }
257
258    /// Iterate the credential's key/value pairs in Git's canonical wire order.
259    fn iter_pairs(&self) -> Vec<(String, String)> {
260        let mut pairs = Vec::new();
261        if let Some(v) = &self.protocol {
262            pairs.push(("protocol".to_string(), v.clone()));
263        }
264        if let Some(v) = &self.host {
265            pairs.push(("host".to_string(), v.clone()));
266        }
267        if let Some(v) = &self.path {
268            pairs.push(("path".to_string(), v.clone()));
269        }
270        if let Some(v) = &self.username {
271            pairs.push(("username".to_string(), v.clone()));
272        }
273        if let Some(v) = &self.password {
274            pairs.push(("password".to_string(), v.clone()));
275        }
276        if let Some(v) = &self.url {
277            pairs.push(("url".to_string(), v.clone()));
278        }
279        for (k, v) in &self.extra {
280            pairs.push((k.clone(), v.clone()));
281        }
282        pairs
283    }
284
285    /// True when the credential carries a usable username **and** password.
286    pub fn is_complete(&self) -> bool {
287        self.username.as_deref().is_some_and(|s| !s.is_empty())
288            && self.password.as_deref().is_some_and(|s| !s.is_empty())
289    }
290
291    /// The URL this credential authenticates against, for matching
292    /// `credential.<url>.helper` config entries. Prefers an explicit
293    /// [`url`](Credential::url); otherwise reconstructs it from
294    /// protocol/host/path (matching Git's `credential_apply_config`).
295    pub fn target_url(&self) -> Option<String> {
296        if let Some(u) = self.url.as_deref().filter(|u| !u.trim().is_empty()) {
297            return Some(u.to_string());
298        }
299        let protocol = self.protocol.as_deref()?;
300        let host = self.host.as_deref()?;
301        let mut url = format!("{protocol}://");
302        if let Some(username) = self.username.as_deref().filter(|u| !u.is_empty()) {
303            url.push_str(username);
304            url.push('@');
305        }
306        url.push_str(host);
307        if let Some(path) = self.path.as_deref().filter(|p| !p.is_empty()) {
308            if !path.starts_with('/') {
309                url.push('/');
310            }
311            url.push_str(path);
312        }
313        Some(url)
314    }
315
316    /// The askpass prompt for `field` (`Username` or `Password`), in the
317    /// `<field> for '<protocol>://[<user>@]<host>[/<path>]': ` form askpass
318    /// scripts match on. With `sanitize` (Git's `credential.sanitizePrompt`,
319    /// which may be URL-scoped and is on by default) control and URL-unsafe characters in the user, host and
320    /// path are percent-encoded.
321    fn prompt(&self, field: &str, sanitize: bool) -> String {
322        let Some(protocol) = self.protocol.as_deref() else {
323            return format!("{field}: ");
324        };
325        let part = |value: &str, escape: fn(u8) -> bool| {
326            if sanitize {
327                percent_encode_where(value, escape)
328            } else {
329                value.to_owned()
330            }
331        };
332        let mut target = format!("{protocol}://");
333        if let Some(user) = self.username.as_deref().filter(|u| !u.is_empty()) {
334            target.push_str(&part(user, |b| {
335                b == b'/' || URL_UNSAFE_PROMPT_BYTES.contains(&b)
336            }));
337            target.push('@');
338        }
339        if let Some(host) = self.host.as_deref() {
340            target.push_str(&part(host, |b| {
341                !b.is_ascii_alphanumeric() && !b"-.:[]".contains(&b)
342            }));
343        }
344        if let Some(path) = self.path.as_deref() {
345            target.push('/');
346            target.push_str(&part(path, |b| URL_UNSAFE_PROMPT_BYTES.contains(&b)));
347        }
348        format!("{field} for '{target}': ")
349    }
350
351    /// Merge a helper's `get` response into this credential: fill any missing
352    /// username/password (and other recognized fields) without clobbering
353    /// values we already hold. `quit` and `capability[]` are tracked in
354    /// `extra` for the caller to inspect.
355    fn merge_response(&mut self, response: &Credential) {
356        if self.username.is_none() {
357            self.username = response.username.clone();
358        }
359        if self.password.is_none() {
360            self.password = response.password.clone();
361        }
362        if self.protocol.is_none() {
363            self.protocol = response.protocol.clone();
364        }
365        if self.host.is_none() {
366            self.host = response.host.clone();
367        }
368        if self.path.is_none() {
369            self.path = response.path.clone();
370        }
371        for (k, v) in &response.extra {
372            // Preserve quit signalling for callers; other extras are advisory.
373            if k == "quit" {
374                self.set(k, v);
375            }
376        }
377    }
378
379    /// Did a helper signal `quit=1`/`quit=true` (stop querying further helpers)?
380    fn wants_quit(&self) -> bool {
381        matches!(self.extra_get("quit"), Some("1") | Some("true"))
382    }
383}
384
385/// The pluggable credential seam an embedder implements (or wraps).
386///
387/// All three methods take a (partial) [`Credential`] describing the target and
388/// return a result; transports call [`fill`](CredentialProvider::fill) before a
389/// request and [`approve`](CredentialProvider::approve) /
390/// [`reject`](CredentialProvider::reject) after, mirroring Git's
391/// `credential_fill` / `credential_approve` / `credential_reject`.
392pub trait CredentialProvider {
393    /// Fill in missing fields (typically username/password) for `input`,
394    /// returning a more-complete [`Credential`]. Implementations that cannot
395    /// supply a usable credential should return a typed [`Error`] rather than
396    /// block on interactive input.
397    fn fill(&self, input: &Credential) -> Result<Credential>;
398
399    /// Mark `cred` as known-good (helpers `store` it).
400    fn approve(&self, cred: &Credential) -> Result<()>;
401
402    /// Mark `cred` as known-bad (helpers `erase` it).
403    fn reject(&self, cred: &Credential) -> Result<()>;
404}
405
406/// Git-compatible [`CredentialProvider`] that runs the configured
407/// `credential.helper` programs.
408///
409/// Built from a [`ConfigSet`]; it resolves the helper list per the target URL
410/// (so `credential.<url>.helper` entries are honored) and invokes each helper
411/// with `get` (for [`fill`](CredentialProvider::fill)), `store` (for
412/// [`approve`](CredentialProvider::approve)), or `erase` (for
413/// [`reject`](CredentialProvider::reject)) exactly as Git does.
414///
415/// If no helper yields a complete credential, [`fill`](CredentialProvider::fill)
416/// asks the [askpass program](HelperCredentialProvider::with_askpass) for the
417/// missing username and password. It never prompts on a terminal: without an
418/// askpass program it returns [`RemoteError::CredentialsUnavailable`](crate::remote::RemoteError::CredentialsUnavailable) with the
419/// helpers it asked.
420pub struct HelperCredentialProvider {
421    config: ConfigSet,
422    command_runner: Arc<dyn CommandRunner>,
423    probed_git_exec_path: OnceLock<Vec<PathBuf>>,
424    askpass: Option<PathBuf>,
425}
426
427impl HelperCredentialProvider {
428    /// Build a provider from a loaded [`ConfigSet`], with no askpass program.
429    pub fn new(config: ConfigSet) -> Self {
430        Self {
431            config,
432            command_runner: system_command_runner(),
433            probed_git_exec_path: OnceLock::new(),
434            askpass: None,
435        }
436    }
437
438    /// Override the subprocess runner (tests and embedders).
439    #[must_use]
440    pub fn with_command_runner(mut self, runner: Arc<dyn CommandRunner>) -> Self {
441        self.command_runner = runner;
442        self
443    }
444
445    /// Ask `program` for a username and password the helpers could not
446    /// supply, usually the result of [`askpass_program`].
447    ///
448    /// `program` runs once per missing field with the prompt (for example
449    /// `Username for 'https://example.com': `) as its only argument, and its
450    /// stdout up to the first line break is the answer. Credentials obtained
451    /// this way are stored with the helpers when the transport
452    /// [approves](CredentialProvider::approve) them. `None` disables the
453    /// fallback. `credential.interactive=false` or `never` also disables it.
454    #[must_use]
455    pub fn with_askpass(mut self, program: Option<PathBuf>) -> Self {
456        self.askpass = program;
457        self
458    }
459
460    /// The `credential.helper` programs this provider runs for `cred`, in the
461    /// order [`fill`](CredentialProvider::fill),
462    /// [`approve`](CredentialProvider::approve) and
463    /// [`reject`](CredentialProvider::reject) invoke them.
464    ///
465    /// Includes `credential.<url>.helper` entries whose URL pattern matches
466    /// [`Credential::target_url`]; an empty value resets the list, as in Git.
467    /// An empty result means storing `cred` would be a no-op.
468    #[must_use]
469    pub fn helpers_for(&self, cred: &Credential) -> Vec<String> {
470        self.helpers(cred.target_url().as_deref())
471    }
472
473    /// The ordered helper list applicable to `target_url`.
474    fn helpers(&self, target_url: Option<&str>) -> Vec<String> {
475        credential_helpers(&self.config, target_url)
476    }
477
478    /// The fields a helper receives for `cred`: an explicit
479    /// [`url`](Credential::url) fills a missing protocol/host/path the way
480    /// [`Credential::from_url`] does and is then dropped, because Git never
481    /// writes `url` to helpers.
482    fn helper_request(&self, cred: &Credential) -> Credential {
483        let mut request = cred.clone();
484        let Some(url) = request.url.take() else {
485            return request;
486        };
487        if request.protocol.is_none() && request.host.is_none() {
488            if let Some(from_url) = Credential::from_url(&url, &self.config) {
489                request.protocol = from_url.protocol;
490                request.host = from_url.host;
491                request.path = request.path.or(from_url.path);
492            }
493        }
494        request
495    }
496
497    /// False when `credential.interactive` is `false` or `never`.
498    fn prompts_allowed(&self) -> bool {
499        self.config
500            .value("credential.interactive")
501            .is_none_or(|value| value != "never" && parse_bool(&value).unwrap_or(true))
502    }
503
504    fn exec_path_candidates(&self) -> Vec<PathBuf> {
505        credential_helper_exec_path_candidates(
506            self.command_runner.as_ref(),
507            &self.probed_git_exec_path,
508        )
509    }
510
511    /// Whether the helper program for the bare helper name `name` (so
512    /// `git-credential-<name>`) is installed in Git's exec-path or on `PATH`.
513    #[must_use]
514    pub fn helper_installed(&self, name: &str) -> bool {
515        let program = format!("git-credential-{name}");
516        let on_path = crate::environment::Environment::empty()
517            .var_os("PATH")
518            .map(|path| std::env::split_paths(&path).collect::<Vec<_>>())
519            .unwrap_or_default();
520        self.exec_path_candidates()
521            .iter()
522            .chain(on_path.iter())
523            .any(|dir| credential_helper_executable_at(&dir.join(&program)).is_some())
524    }
525
526    /// The helper to configure when `credential.helper` is unset: the first of
527    /// [`SUGGESTED_HELPERS`] that is installed.
528    ///
529    /// That is the platform's secure store when it is available (the macOS
530    /// keychain, libsecret on Linux), otherwise `store`, which keeps
531    /// credentials in a plaintext file. `None` when none is installed.
532    #[must_use]
533    pub fn suggested_helper(&self) -> Option<&'static str> {
534        SUGGESTED_HELPERS
535            .iter()
536            .copied()
537            .find(|name| self.helper_installed(name))
538    }
539}
540
541/// Helper names [`HelperCredentialProvider::suggested_helper`] tries, best
542/// first: the platform's secure store, then the plaintext `store`.
543#[cfg(target_os = "macos")]
544pub const SUGGESTED_HELPERS: &[&str] = &["osxkeychain", "store"];
545/// Helper names [`HelperCredentialProvider::suggested_helper`] tries, best
546/// first: the platform's secure store, then the plaintext `store`.
547#[cfg(all(unix, not(target_os = "macos")))]
548pub const SUGGESTED_HELPERS: &[&str] = &["libsecret", "store"];
549/// Helper names [`HelperCredentialProvider::suggested_helper`] tries, best
550/// first: the platform's secure store, then the plaintext `store`.
551#[cfg(not(unix))]
552pub const SUGGESTED_HELPERS: &[&str] = &["manager", "store"];
553
554impl CredentialProvider for HelperCredentialProvider {
555    fn fill(&self, input: &Credential) -> Result<Credential> {
556        let mut filled = input.clone();
557        if filled.is_complete() {
558            return Ok(filled);
559        }
560        let target_url = filled.target_url();
561        let helper_list = self.helpers(target_url.as_deref());
562        for helper in &helper_list {
563            let response = invoke_helper(
564                self.command_runner.as_ref(),
565                helper,
566                "get",
567                &self.helper_request(&filled),
568                &self.exec_path_candidates(),
569            )?;
570            if response.wants_quit() {
571                return Err(credential_err(format!(
572                    "credential helper '{helper}' told us to quit"
573                )));
574            }
575            filled.merge_response(&response);
576            if filled.is_complete() {
577                return Ok(filled);
578            }
579        }
580        let Some(askpass) = self.askpass.as_deref().filter(|_| self.prompts_allowed()) else {
581            return Err(RemoteError::CredentialsUnavailable {
582                helpers: helper_list,
583            }
584            .into());
585        };
586        let sanitize =
587            credential_config_value(&self.config, target_url.as_deref(), "sanitizePrompt")
588                .is_none_or(|value| parse_bool(&value).unwrap_or(true));
589        if filled.username.is_none() {
590            let prompt = filled.prompt("Username", sanitize);
591            filled.username = Some(run_askpass(self.command_runner.as_ref(), askpass, &prompt)?);
592        }
593        if filled.password.is_none() {
594            let prompt = filled.prompt("Password", sanitize);
595            filled.password = Some(run_askpass(self.command_runner.as_ref(), askpass, &prompt)?);
596        }
597        Ok(filled)
598    }
599
600    fn approve(&self, cred: &Credential) -> Result<()> {
601        let target_url = cred.target_url();
602        let request = self.helper_request(cred);
603        for helper in self.helpers(target_url.as_deref()) {
604            invoke_helper(
605                self.command_runner.as_ref(),
606                &helper,
607                "store",
608                &request,
609                &self.exec_path_candidates(),
610            )?;
611        }
612        Ok(())
613    }
614
615    fn reject(&self, cred: &Credential) -> Result<()> {
616        let target_url = cred.target_url();
617        let request = self.helper_request(cred);
618        for helper in self.helpers(target_url.as_deref()) {
619            invoke_helper(
620                self.command_runner.as_ref(),
621                &helper,
622                "erase",
623                &request,
624                &self.exec_path_candidates(),
625            )?;
626        }
627        Ok(())
628    }
629}
630
631/// Build the effective `credential.helper` list in Git order.
632///
633/// Git walks every `credential.helper` and `credential.<URL>.helper` config
634/// entry in load order. URL-scoped entries only apply when the subsection
635/// pattern matches `target_url` (per Git's URL-match rules). For every
636/// applicable entry, a non-empty value is appended to the helper list and an
637/// empty value resets it (Git's `string_list_clear` semantics in
638/// `credential_apply_config_cb`).
639///
640/// `target_url` is the URL we're authenticating against (e.g.
641/// `https://github.com/owner/repo.git`). When `None`, only unscoped
642/// `credential.helper` entries contribute.
643fn credential_helpers(config: &ConfigSet, target_url: Option<&str>) -> Vec<String> {
644    let mut out = Vec::new();
645    for entry in config.entries() {
646        let key = &entry.key;
647        if key.contains('\n') || key.to_ascii_lowercase().contains("%0a") {
648            continue;
649        }
650        let Some(first_dot) = key.find('.') else {
651            continue;
652        };
653        let Some(last_dot) = key.rfind('.') else {
654            continue;
655        };
656        let section = &key[..first_dot];
657        let variable = &key[last_dot + 1..];
658        if !section.eq_ignore_ascii_case("credential") || !variable.eq_ignore_ascii_case("helper") {
659            continue;
660        }
661        if first_dot != last_dot {
662            let subsection = &key[first_dot + 1..last_dot];
663            if percent_decode_lossy(subsection).contains('\n') {
664                continue;
665            }
666            let Some(target) = target_url else {
667                continue;
668            };
669            if !credential_url_matches(subsection, target) {
670                continue;
671            }
672        }
673        let value = entry.value.as_deref().unwrap_or("");
674        if value.trim().is_empty() {
675            out.clear();
676        } else {
677            out.push(value.to_string());
678        }
679    }
680    out
681}
682
683fn credential_url_matches(pattern: &str, target: &str) -> bool {
684    let pattern = percent_decode_lossy(pattern);
685    if pattern.contains('\n') {
686        return false;
687    }
688    let pattern = pattern.trim_end_matches('/');
689    let pattern_no_user = url_without_userinfo(pattern);
690    let pattern_after_user = pattern.rsplit_once('@').map(|(_, host)| host);
691    let target = target.trim_end_matches('/');
692    let target_no_user = url_without_userinfo(target);
693    let target_no_scheme = strip_url_scheme(target);
694    let target_no_scheme_no_user = strip_url_scheme(&target_no_user);
695    let target_path = target_path_component(target);
696
697    let matches = |pattern: &str| {
698        if pattern.starts_with('/') {
699            return credential_prefix_matches(pattern, target_path);
700        }
701        if pattern.ends_with("://") {
702            return target.starts_with(pattern) || target_no_user.starts_with(pattern);
703        }
704        if pattern.contains('*') {
705            return credential_wildcard_matches(pattern, target)
706                || credential_wildcard_matches(pattern, &target_no_user)
707                || credential_wildcard_matches(pattern, target_no_scheme)
708                || credential_wildcard_matches(pattern, target_no_scheme_no_user);
709        }
710        credential_prefix_matches(pattern, target)
711            || credential_prefix_matches(pattern, &target_no_user)
712            || credential_prefix_matches(pattern, target_no_scheme)
713            || credential_prefix_matches(pattern, target_no_scheme_no_user)
714    };
715    matches(pattern)
716        || (pattern_no_user != pattern && matches(&pattern_no_user))
717        || pattern_after_user.is_some_and(matches)
718}
719
720fn credential_prefix_matches(pattern: &str, candidate: &str) -> bool {
721    candidate
722        .strip_prefix(pattern)
723        .is_some_and(|rest| rest.is_empty() || rest.starts_with('/') || pattern.ends_with("://"))
724}
725
726fn credential_wildcard_matches(pattern: &str, candidate: &str) -> bool {
727    let Some((prefix, suffix)) = pattern.split_once('*') else {
728        return false;
729    };
730    let Some(rest) = candidate.strip_prefix(prefix) else {
731        return false;
732    };
733    rest.find(suffix).is_some_and(|idx| {
734        let after = &rest[idx + suffix.len()..];
735        after.is_empty() || after.starts_with('/')
736    })
737}
738
739fn strip_url_scheme(url: &str) -> &str {
740    url.split_once("://").map_or(url, |(_, rest)| rest)
741}
742
743/// Return `url` with any `user:pass@` userinfo removed.
744///
745/// Handles `scheme://user:pass@host/...` and scp-style `user:pass@host:path`
746/// (no scheme). Userinfo is stripped only from the URL authority (the part
747/// before the first `/`, `?`, or `#`); `@` in paths, queries, and fragments is
748/// preserved. The result is safe to show in errors and logs.
749pub(crate) fn url_without_userinfo(url: &str) -> String {
750    let Some((scheme, rest)) = url.split_once("://") else {
751        let (authority, suffix) = split_authority_suffix(url);
752        let authority = strip_userinfo_from_authority(authority);
753        return format!("{authority}{suffix}");
754    };
755    let (authority, suffix) = split_authority_suffix(rest);
756    let authority = strip_userinfo_from_authority(authority);
757    format!("{scheme}://{authority}{suffix}")
758}
759
760fn split_authority_suffix(url: &str) -> (&str, &str) {
761    let authority_end = url
762        .char_indices()
763        .find(|(_, ch)| matches!(ch, '/' | '?' | '#'))
764        .map(|(idx, _)| idx)
765        .unwrap_or(url.len());
766    url.split_at(authority_end)
767}
768
769fn strip_userinfo_from_authority(authority: &str) -> &str {
770    authority
771        .rsplit_once('@')
772        .map_or(authority, |(_, host_port)| host_port)
773}
774
775/// Redact credentials from URL-like `http://` / `https://` substrings in `message`.
776#[cfg_attr(not(feature = "http-ureq"), allow(dead_code))]
777pub(crate) fn redact_embedded_url_credentials(message: &str) -> String {
778    let mut out = String::with_capacity(message.len());
779    let mut rest = message;
780    while let Some(scheme_sep) = rest.find("://") {
781        let before = &rest[..scheme_sep];
782        let scheme_start = before
783            .char_indices()
784            .rfind(|(_, c)| !c.is_ascii_alphanumeric() && *c != '-' && *c != '+' && *c != '.')
785            .map(|(i, c)| i + c.len_utf8())
786            .unwrap_or(0);
787        out.push_str(&rest[..scheme_start]);
788        let url_part = &rest[scheme_start..];
789        let url_end = url_part
790            .find(|c: char| c.is_whitespace() || matches!(c, '"' | '\'' | ')' | ']' | ','))
791            .unwrap_or(url_part.len());
792        let url = &url_part[..url_end];
793        out.push_str(&url_without_userinfo(url));
794        rest = &url_part[url_end..];
795    }
796    out.push_str(rest);
797    out
798}
799
800fn target_path_component(url: &str) -> &str {
801    let rest = strip_url_scheme(url);
802    let idx = rest
803        .char_indices()
804        .find_map(|(idx, ch)| matches!(ch, '/' | '?' | '#').then_some(idx))
805        .unwrap_or(rest.len());
806    &rest[idx..]
807}
808
809fn percent_decode_lossy(input: &str) -> String {
810    let mut out = Vec::with_capacity(input.len());
811    let bytes = input.as_bytes();
812    let mut idx = 0;
813    while idx < bytes.len() {
814        if bytes[idx] == b'%' && idx + 2 < bytes.len() {
815            if let (Some(hi), Some(lo)) = (hex_value(bytes[idx + 1]), hex_value(bytes[idx + 2])) {
816                out.push((hi << 4) | lo);
817                idx += 3;
818                continue;
819            }
820        }
821        out.push(bytes[idx]);
822        idx += 1;
823    }
824    String::from_utf8_lossy(&out).into_owned()
825}
826
827/// Bytes a sanitized askpass prompt percent-encodes in the user and path.
828const URL_UNSAFE_PROMPT_BYTES: &[u8] = b" <>\"%{}|\\^`:?#[]@!$&'()*+,;=";
829
830/// Percent-encode control and non-ASCII bytes of `value`, plus every byte for
831/// which `escape` returns true.
832fn percent_encode_where(value: &str, escape: fn(u8) -> bool) -> String {
833    use std::fmt::Write as _;
834    let mut out = String::with_capacity(value.len());
835    for byte in value.bytes() {
836        if byte <= 0x1f || byte >= 0x7f || escape(byte) {
837            let _ = write!(out, "%{byte:02X}");
838        } else {
839            out.push(char::from(byte));
840        }
841    }
842    out
843}
844
845fn hex_value(byte: u8) -> Option<u8> {
846    match byte {
847        b'0'..=b'9' => Some(byte - b'0'),
848        b'a'..=b'f' => Some(byte - b'a' + 10),
849        b'A'..=b'F' => Some(byte - b'A' + 10),
850        _ => None,
851    }
852}
853
854/// Extra `bin` directories to search for credential helpers given Git's `--exec-path`.
855///
856/// Git for Windows uses `{root}/mingw64/libexec/git-core` for exec-path while Git
857/// Credential Manager lives in `{root}/mingw64/bin`, not `{root}/mingw64/libexec/bin`.
858fn credential_helper_bin_dirs_from_exec_path(exec_path: &Path) -> Vec<PathBuf> {
859    let mut bins = Vec::new();
860    let Some(parent) = exec_path.parent() else {
861        return bins;
862    };
863    bins.push(parent.join("bin"));
864    if exec_path.file_name().is_some_and(|name| name == "git-core")
865        && parent.file_name().is_some_and(|name| name == "libexec")
866    {
867        if let Some(toolchain_root) = parent.parent() {
868            bins.push(toolchain_root.join("bin"));
869        }
870    }
871    bins
872}
873
874fn push_exec_path_candidate(out: &mut Vec<PathBuf>, seen: &mut HashSet<PathBuf>, dir: PathBuf) {
875    if !dir.is_dir() || !seen.insert(dir.clone()) {
876        return;
877    }
878    out.push(dir.clone());
879    for bin in credential_helper_bin_dirs_from_exec_path(&dir) {
880        if bin.is_dir() && seen.insert(bin.clone()) {
881            out.push(bin);
882        }
883    }
884}
885
886/// Directories to search for `git-credential-*` the way Git does
887/// (exec-path before `PATH`). Git installs helpers under e.g.
888/// `/usr/libexec/git-core`, which is not on `PATH`.
889fn credential_helper_exec_path_candidates(
890    runner: &dyn CommandRunner,
891    probed_git_exec_path: &OnceLock<Vec<PathBuf>>,
892) -> Vec<PathBuf> {
893    let mut v = Vec::new();
894    let mut seen = HashSet::new();
895    if let Some(ep) = crate::environment::Environment::empty().var("GIT_EXEC_PATH") {
896        push_exec_path_candidate(&mut v, &mut seen, PathBuf::from(ep.trim()));
897    }
898    for dir in probed_git_exec_path_dirs(runner, probed_git_exec_path) {
899        push_exec_path_candidate(&mut v, &mut seen, dir);
900    }
901    for candidate in [
902        "/usr/libexec/git-core",
903        "/Library/Developer/CommandLineTools/usr/libexec/git-core",
904        "/opt/homebrew/opt/git/libexec/git-core",
905        "/opt/homebrew/libexec/git-core",
906        "/usr/lib/git-core",
907        "/usr/local/libexec/git-core",
908    ] {
909        push_exec_path_candidate(&mut v, &mut seen, PathBuf::from(candidate));
910    }
911    v
912}
913
914fn probed_git_exec_path_dirs(
915    runner: &dyn CommandRunner,
916    probed_git_exec_path: &OnceLock<Vec<PathBuf>>,
917) -> Vec<PathBuf> {
918    probed_git_exec_path
919        .get_or_init(|| probe_git_exec_path(runner))
920        .clone()
921}
922
923fn probe_git_exec_path(runner: &dyn CommandRunner) -> Vec<PathBuf> {
924    let spec = CommandSpec {
925        program: PathBuf::from("git"),
926        args: vec![OsString::from("--exec-path")],
927        shell: None,
928        cwd: None,
929        env: CommandEnvironment::inherit_process_only(),
930        stdin: CommandStdin::Null,
931        stdout: CommandStdio::Pipe,
932        stderr: CommandStdio::Null,
933    };
934    let Ok(child) = runner.spawn(&spec) else {
935        return Vec::new();
936    };
937    let Ok(output) = child.wait_with_output() else {
938        return Vec::new();
939    };
940    if !output.status.success {
941        return Vec::new();
942    }
943    let dir = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
944    if dir.is_dir() {
945        vec![dir]
946    } else {
947        Vec::new()
948    }
949}
950
951fn credential_helper_executable_at(path: &Path) -> Option<PathBuf> {
952    if path.is_file() {
953        return Some(path.to_path_buf());
954    }
955    #[cfg(windows)]
956    {
957        let with_exe = path.with_extension("exe");
958        if with_exe.is_file() {
959            return Some(with_exe);
960        }
961    }
962    None
963}
964
965/// Resolve a helper program name to an executable path. A bare
966/// `git-credential-<name>` is looked up across Git's exec-path candidates
967/// before falling back to `PATH`.
968fn resolve_credential_helper_executable(
969    helper_program: &str,
970    exec_path_candidates: &[PathBuf],
971) -> PathBuf {
972    if helper_program.contains('/') {
973        return PathBuf::from(helper_program);
974    }
975    if let Some(suffix) = helper_program.strip_prefix("git-credential-") {
976        let exe_name = format!("git-credential-{suffix}");
977        for ep in exec_path_candidates {
978            let candidate = ep.join(&exe_name);
979            if let Some(resolved) = credential_helper_executable_at(&candidate) {
980                return resolved;
981            }
982        }
983    }
984    PathBuf::from(helper_program)
985}
986
987/// Invoke an external credential helper program.
988///
989/// The helper may be:
990/// - shell form: `!command ...` (executed by `sh -c`)
991/// - absolute/relative path containing `/`
992/// - bare helper name (expanded to `git-credential-<name>`)
993/// - already-expanded binary (`git-credential-...`)
994///
995/// Bare helper names such as `store` and `cache` expand to `git-credential-*`
996/// and are resolved via Git's exec-path (and `PATH`) like other helpers.
997///
998/// The helper is invoked with one action argument (`get`, `store`, `erase`)
999/// after any arguments from the configured helper string. Credential fields are
1000/// written to stdin as `key=value` lines followed by a blank line; stdout is
1001/// parsed back into a [`Credential`].
1002/// The fields sent to a helper for `creds`.
1003///
1004/// Like Git, a credential that already has its protocol and host goes to
1005/// helpers without `url`: the URL is only used to pick helpers. Helpers parse a
1006/// `url` into protocol, host *and path*, so sending the request URL (say
1007/// `…/repo.git/info/refs?service=…`) would make every host-wide stored
1008/// credential miss.
1009fn helper_request(creds: &Credential) -> std::borrow::Cow<'_, Credential> {
1010    if creds.url.is_none() || creds.protocol.is_none() || creds.host.is_none() {
1011        return std::borrow::Cow::Borrowed(creds);
1012    }
1013    let mut request = creds.clone();
1014    request.url = None;
1015    std::borrow::Cow::Owned(request)
1016}
1017
1018fn invoke_helper(
1019    runner: &dyn CommandRunner,
1020    helper: &str,
1021    action: &str,
1022    creds: &Credential,
1023    exec_path_candidates: &[PathBuf],
1024) -> Result<Credential> {
1025    let helper_words = shell_words::split(helper)
1026        .map_err(|e| credential_err(format!("invalid credential.helper '{helper}': {e}")))?;
1027    let (first_word, extra_args) = match helper_words.split_first() {
1028        Some((first, rest)) => (first.as_str(), rest),
1029        None => ("", &[][..]),
1030    };
1031
1032    let mut stdin_body = helper_request(creds).serialize();
1033    stdin_body.push('\n');
1034    let stdin_bytes = stdin_body.into_bytes();
1035
1036    let spec = if let Some(shell_cmd) = helper.strip_prefix('!') {
1037        CommandSpec {
1038            program: "sh".into(),
1039            args: Vec::new(),
1040            shell: Some(ShellInvocation::DashC {
1041                script: format!("{shell_cmd} {action}"),
1042                argv0: None,
1043                args: Vec::new(),
1044            }),
1045            cwd: None,
1046            env: CommandEnvironment::inherit_process_only(),
1047            stdin: CommandStdin::Pipe(stdin_bytes),
1048            stdout: CommandStdio::Pipe,
1049            stderr: CommandStdio::Inherit,
1050        }
1051    } else {
1052        let helper_program =
1053            if first_word.contains('/') || first_word.starts_with("git-credential-") {
1054                first_word.to_string()
1055            } else {
1056                format!("git-credential-{first_word}")
1057            };
1058        let resolved = resolve_credential_helper_executable(&helper_program, exec_path_candidates);
1059        let mut args: Vec<OsString> = extra_args
1060            .iter()
1061            .map(|a| OsString::from(a.as_str()))
1062            .collect();
1063        args.push(OsString::from(action));
1064        CommandSpec {
1065            program: resolved,
1066            args,
1067            shell: None,
1068            cwd: None,
1069            env: CommandEnvironment::inherit_process_only(),
1070            stdin: CommandStdin::Pipe(stdin_bytes),
1071            stdout: CommandStdio::Pipe,
1072            stderr: CommandStdio::Inherit,
1073        }
1074    };
1075
1076    let output = runner
1077        .spawn(&spec)
1078        .map_err(|e| credential_err(format!("failed to run credential helper '{helper}': {e}")))?
1079        .wait_with_output()
1080        .map_err(|e| credential_err(format!("credential helper '{helper}' failed: {e}")))?;
1081    if !output.status.success {
1082        return Err(credential_err(format!(
1083            "credential helper '{helper}' exited with status {}",
1084            output.status.code.unwrap_or(-1)
1085        )));
1086    }
1087
1088    Ok(Credential::parse_bytes(&output.stdout))
1089}
1090
1091/// Why [`helper_config_value`] cannot express a helper command as a
1092/// `credential.helper` value.
1093#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1094#[non_exhaustive]
1095pub enum HelperValueError {
1096    /// The program path is relative. Git expands a value that does not start
1097    /// with an absolute path to `git credential-<value>`.
1098    #[error("credential helper program `{}` is not an absolute path", path.display())]
1099    RelativeProgram {
1100        /// The program path that was passed.
1101        path: PathBuf,
1102    },
1103    /// The program path is not valid Unicode, so it cannot be stored in config.
1104    #[error("credential helper program `{}` is not valid Unicode", path.display())]
1105    NonUnicodeProgram {
1106        /// The program path that was passed.
1107        path: PathBuf,
1108    },
1109    /// A word contains a line feed, which an escaped config value cannot carry
1110    /// through shell word splitting.
1111    #[error("credential helper word {word:?} contains a line break")]
1112    LineBreak {
1113        /// The program path or argument containing the line feed.
1114        word: String,
1115    },
1116}
1117
1118/// Format `program` and `args` as a `credential.helper` value that Git and grit
1119/// both run directly, without the value being taken as a helper name.
1120///
1121/// Git treats a helper value as a command only when it starts with `!` (run
1122/// through `sh -c`) or with an absolute path; anything else becomes
1123/// `git credential-<value>`. A value that wraps the path in quotes therefore
1124/// fails, and a leading `!` needs a POSIX shell, which grit's own helper
1125/// invocation avoids. This keeps the absolute path first and backslash-escapes
1126/// every shell metacharacter instead, so Git's shell and grit's word splitting
1127/// both recover exactly `[program, args...]`.
1128///
1129/// On Windows, `\` separators in `program` are written as `/`, which Git and
1130/// Windows both accept, so the value starts with a drive prefix like `C:/`.
1131///
1132/// # Parameters
1133///
1134/// - `program`: absolute path of the helper executable.
1135/// - `args`: arguments placed before the action (`get`, `store`, `erase`) that
1136///   Git and grit append.
1137///
1138/// # Returns
1139///
1140/// The value to store under `credential.helper`.
1141///
1142/// # Errors
1143///
1144/// - [`HelperValueError::RelativeProgram`] when `program` is not absolute.
1145/// - [`HelperValueError::NonUnicodeProgram`] when `program` is not valid Unicode.
1146/// - [`HelperValueError::LineBreak`] when `program` or an argument contains `\n`.
1147///
1148/// # Examples
1149///
1150/// ```
1151/// # #[cfg(unix)] {
1152/// use std::path::Path;
1153/// use grit_lib::remote::credentials::helper_config_value;
1154///
1155/// let value = helper_config_value(Path::new("/opt/my tools/grit"), &["manager"])?;
1156/// assert_eq!(value, r"/opt/my\ tools/grit manager");
1157/// # }
1158/// # Ok::<(), grit_lib::remote::credentials::HelperValueError>(())
1159/// ```
1160pub fn helper_config_value(
1161    program: &Path,
1162    args: &[&str],
1163) -> std::result::Result<String, HelperValueError> {
1164    if !program.is_absolute() {
1165        return Err(HelperValueError::RelativeProgram {
1166            path: program.to_path_buf(),
1167        });
1168    }
1169    let program_str = program
1170        .to_str()
1171        .ok_or_else(|| HelperValueError::NonUnicodeProgram {
1172            path: program.to_path_buf(),
1173        })?;
1174    let program_str: std::borrow::Cow<'_, str> = if cfg!(windows) {
1175        program_str.replace('\\', "/").into()
1176    } else {
1177        program_str.into()
1178    };
1179
1180    let mut value = String::with_capacity(program_str.len() + 16);
1181    for (i, word) in std::iter::once(program_str.as_ref())
1182        .chain(args.iter().copied())
1183        .enumerate()
1184    {
1185        if word.contains('\n') {
1186            return Err(HelperValueError::LineBreak {
1187                word: word.to_owned(),
1188            });
1189        }
1190        if i > 0 {
1191            value.push(' ');
1192        }
1193        if word.is_empty() {
1194            value.push_str("''");
1195            continue;
1196        }
1197        for ch in word.chars() {
1198            let plain = !ch.is_ascii()
1199                || ch.is_ascii_alphanumeric()
1200                || matches!(ch, '/' | '.' | '_' | '-' | ':' | '+' | ',' | '@' | '%');
1201            if !plain {
1202                value.push('\\');
1203            }
1204            value.push(ch);
1205        }
1206    }
1207    Ok(value)
1208}
1209
1210/// Run the askpass `program` with `prompt` as its argument and return its
1211/// answer: stdout up to the first `\r` or `\n`.
1212fn run_askpass(runner: &dyn CommandRunner, program: &Path, prompt: &str) -> Result<String> {
1213    let spec = CommandSpec {
1214        program: program.to_path_buf(),
1215        args: vec![OsString::from(prompt)],
1216        shell: None,
1217        cwd: None,
1218        env: CommandEnvironment::inherit_process_only(),
1219        stdin: CommandStdin::Null,
1220        stdout: CommandStdio::Pipe,
1221        stderr: CommandStdio::Inherit,
1222    };
1223    let output = runner
1224        .spawn(&spec)
1225        .and_then(|child| child.wait_with_output())
1226        .map_err(|e| {
1227            credential_err(format!(
1228                "could not run askpass program '{}': {e}",
1229                program.display()
1230            ))
1231        })?;
1232    if !output.status.success {
1233        return Err(credential_err(format!(
1234            "askpass program '{}' exited with status {}",
1235            program.display(),
1236            output.status.code.unwrap_or(-1)
1237        )));
1238    }
1239    let answer = String::from_utf8_lossy(&output.stdout);
1240    Ok(answer
1241        .split(['\r', '\n'])
1242        .next()
1243        .unwrap_or_default()
1244        .to_owned())
1245}
1246
1247/// Whether `credential.useHttpPath` (optionally URL-scoped) is enabled.
1248///
1249/// Exposed so embedders can decide whether to include the `path` field when
1250/// constructing a [`Credential`] for an HTTP(S) target, matching Git.
1251pub fn use_http_path(config: &ConfigSet, target_url: Option<&str>) -> bool {
1252    credential_config_value(config, target_url, "useHttpPath")
1253        .as_deref()
1254        .map(|value| parse_bool(value).unwrap_or(false))
1255        .unwrap_or(false)
1256}
1257
1258fn credential_config_value(
1259    config: &ConfigSet,
1260    target_url: Option<&str>,
1261    variable_name: &str,
1262) -> Option<String> {
1263    let mut out = None;
1264    for entry in config.entries() {
1265        let key = &entry.key;
1266        if key.contains('\n') || key.to_ascii_lowercase().contains("%0a") {
1267            continue;
1268        }
1269        let Some(first_dot) = key.find('.') else {
1270            continue;
1271        };
1272        let Some(last_dot) = key.rfind('.') else {
1273            continue;
1274        };
1275        let section = &key[..first_dot];
1276        let variable = &key[last_dot + 1..];
1277        if !section.eq_ignore_ascii_case("credential")
1278            || !variable.eq_ignore_ascii_case(variable_name)
1279        {
1280            continue;
1281        }
1282        if first_dot != last_dot {
1283            let subsection = &key[first_dot + 1..last_dot];
1284            if percent_decode_lossy(subsection).contains('\n') {
1285                continue;
1286            }
1287            let Some(target) = target_url else {
1288                continue;
1289            };
1290            if !credential_url_matches(subsection, target) {
1291                continue;
1292            }
1293        }
1294        out = entry.value.clone();
1295    }
1296    out
1297}
1298
1299/// Windows Credential Manager backing store for the built-in `manager`
1300/// credential helper (`gs manager`).
1301///
1302/// Git for Windows bundles Git Credential Manager (the `manager` helper), but it
1303/// is only present when Git for Windows is installed. These functions let `gs`
1304/// store and retrieve secrets directly from the Windows Credential Manager
1305/// without that dependency. They are only compiled on Windows; the `gs manager`
1306/// command errors elsewhere.
1307///
1308/// Secrets are stored as `CRED_TYPE_GENERIC` entries keyed by a target name of
1309/// the form `git:<protocol>://<host>`, matching Git's own `wincred` helper so
1310/// the entries are recognizable in the Credential Manager UI.
1311#[cfg(windows)]
1312pub mod windows_store {
1313    use std::ffi::OsStr;
1314    use std::os::windows::ffi::OsStrExt;
1315
1316    use windows_sys::Win32::Foundation::{GetLastError, ERROR_NOT_FOUND};
1317    use windows_sys::Win32::Security::Credentials::{
1318        CredDeleteW, CredFree, CredReadW, CredWriteW, CREDENTIALW, CRED_PERSIST_LOCAL_MACHINE,
1319        CRED_TYPE_GENERIC,
1320    };
1321
1322    use super::{credential_err, Credential};
1323    use crate::error::Result;
1324
1325    /// The Credential Manager target name a credential is stored under.
1326    fn target_name(cred: &Credential) -> Result<String> {
1327        let protocol = cred
1328            .protocol
1329            .as_deref()
1330            .filter(|p| !p.is_empty())
1331            .ok_or_else(|| credential_err("credential is missing its protocol".to_owned()))?;
1332        let host = cred
1333            .host
1334            .as_deref()
1335            .filter(|h| !h.is_empty())
1336            .ok_or_else(|| credential_err("credential is missing its host".to_owned()))?;
1337        Ok(format!("git:{protocol}://{host}"))
1338    }
1339
1340    /// Encode a string as a NUL-terminated UTF-16 buffer for the wide Win32 API.
1341    fn wide(s: &str) -> Vec<u16> {
1342        OsStr::new(s)
1343            .encode_wide()
1344            .chain(std::iter::once(0))
1345            .collect()
1346    }
1347
1348    /// Read a NUL-terminated wide string from a (possibly null) pointer.
1349    ///
1350    /// # Safety
1351    /// `ptr` must be null or point to a NUL-terminated UTF-16 string owned by a
1352    /// live `CREDENTIALW` returned by `CredReadW`.
1353    unsafe fn wstr_to_string(ptr: *const u16) -> String {
1354        if ptr.is_null() {
1355            return String::new();
1356        }
1357        let mut len = 0usize;
1358        while *ptr.add(len) != 0 {
1359            len += 1;
1360        }
1361        String::from_utf16_lossy(std::slice::from_raw_parts(ptr, len))
1362    }
1363
1364    /// Look up the stored username/password for `cred`'s host, if any.
1365    pub fn get(cred: &Credential) -> Result<Option<Credential>> {
1366        let target = wide(&target_name(cred)?);
1367        let mut pcred: *mut CREDENTIALW = std::ptr::null_mut();
1368        // SAFETY: `target` is a valid NUL-terminated wide string and `pcred` is a
1369        // valid out-pointer; on success Windows allocates the credential for us.
1370        let ok = unsafe { CredReadW(target.as_ptr(), CRED_TYPE_GENERIC, 0, &mut pcred) };
1371        if ok == 0 {
1372            // SAFETY: `GetLastError` is always safe to call after a failed Win32 call.
1373            let err = unsafe { GetLastError() };
1374            if err == ERROR_NOT_FOUND {
1375                return Ok(None);
1376            }
1377            return Err(credential_err(format!(
1378                "reading from the Windows Credential Manager failed (error {err})"
1379            )));
1380        }
1381
1382        // SAFETY: `CredReadW` succeeded, so `pcred` points to a live credential we own
1383        // until `CredFree`. We copy out the fields before freeing it.
1384        let (username, password) = unsafe {
1385            let c = &*pcred;
1386            let username = wstr_to_string(c.UserName);
1387            let password = if c.CredentialBlob.is_null() || c.CredentialBlobSize == 0 {
1388                String::new()
1389            } else {
1390                let bytes =
1391                    std::slice::from_raw_parts(c.CredentialBlob, c.CredentialBlobSize as usize);
1392                String::from_utf8_lossy(bytes).into_owned()
1393            };
1394            (username, password)
1395        };
1396        // SAFETY: `pcred` came from `CredReadW` and has not been freed yet.
1397        unsafe { CredFree(pcred as *const core::ffi::c_void) };
1398
1399        let mut out = Credential::default();
1400        if !username.is_empty() {
1401            out.username = Some(username);
1402        }
1403        if !password.is_empty() {
1404            out.password = Some(password);
1405        }
1406        Ok(Some(out))
1407    }
1408
1409    /// Store `cred`'s password (and username) for its host. A credential with no
1410    /// password is a no-op.
1411    pub fn store(cred: &Credential) -> Result<()> {
1412        let password = match cred.password.as_deref() {
1413            Some(p) if !p.is_empty() => p,
1414            _ => return Ok(()),
1415        };
1416        let mut target = wide(&target_name(cred)?);
1417        let mut username = wide(cred.username.as_deref().unwrap_or(""));
1418        let blob = password.as_bytes();
1419
1420        // SAFETY: zeroing is valid for this plain-old-data struct; we populate the
1421        // fields the API reads below.
1422        let mut credential: CREDENTIALW = unsafe { std::mem::zeroed() };
1423        credential.Type = CRED_TYPE_GENERIC;
1424        credential.TargetName = target.as_mut_ptr();
1425        credential.CredentialBlobSize = blob.len() as u32;
1426        credential.CredentialBlob = blob.as_ptr() as *mut u8;
1427        credential.Persist = CRED_PERSIST_LOCAL_MACHINE;
1428        credential.UserName = username.as_mut_ptr();
1429
1430        // SAFETY: every pointer field references a buffer that outlives the call.
1431        let ok = unsafe { CredWriteW(&credential as *const CREDENTIALW, 0) };
1432        if ok == 0 {
1433            // SAFETY: always safe after a failed Win32 call.
1434            let err = unsafe { GetLastError() };
1435            return Err(credential_err(format!(
1436                "writing to the Windows Credential Manager failed (error {err})"
1437            )));
1438        }
1439        Ok(())
1440    }
1441
1442    /// Delete the stored credential for `cred`'s host. Succeeds if none exists.
1443    pub fn erase(cred: &Credential) -> Result<()> {
1444        let target = wide(&target_name(cred)?);
1445        // SAFETY: `target` is a valid NUL-terminated wide string.
1446        let ok = unsafe { CredDeleteW(target.as_ptr(), CRED_TYPE_GENERIC, 0) };
1447        if ok == 0 {
1448            // SAFETY: always safe after a failed Win32 call.
1449            let err = unsafe { GetLastError() };
1450            if err != ERROR_NOT_FOUND {
1451                return Err(credential_err(format!(
1452                    "deleting from the Windows Credential Manager failed (error {err})"
1453                )));
1454            }
1455        }
1456        Ok(())
1457    }
1458}
1459
1460#[cfg(test)]
1461mod tests {
1462    use super::*;
1463    use crate::command_runner::{RecordedResponse, RecordingRunner};
1464
1465    #[test]
1466    fn helpers_get_decomposed_fields_without_the_request_url() {
1467        let request = Credential {
1468            protocol: Some("http".into()),
1469            host: Some("127.0.0.1:8080".into()),
1470            url: Some("http://127.0.0.1:8080/app.git/info/refs?service=git-upload-pack".into()),
1471            ..Default::default()
1472        };
1473        assert_eq!(
1474            helper_request(&request).serialize(),
1475            "protocol=http\nhost=127.0.0.1:8080\n"
1476        );
1477
1478        // A bare `url` is all a helper could go on, so it stays.
1479        let url_only = Credential {
1480            url: Some("https://example.com/".into()),
1481            ..Default::default()
1482        };
1483        assert_eq!(
1484            helper_request(&url_only).serialize(),
1485            "url=https://example.com/\n"
1486        );
1487    }
1488
1489    #[cfg(unix)]
1490    #[test]
1491    fn helper_config_value_escapes_metacharacters_and_splits_back() {
1492        let cases: &[(&str, &[&str], &str)] = &[
1493            ("/usr/bin/grit", &["manager"], "/usr/bin/grit manager"),
1494            (
1495                "/home/a b/bin/grit",
1496                &["manager"],
1497                r"/home/a\ b/bin/grit manager",
1498            ),
1499            ("/opt/R&D/grit", &[], r"/opt/R\&D/grit"),
1500            (
1501                r#"/tmp/it's "quoted"/grit"#,
1502                &["manager"],
1503                r#"/tmp/it\'s\ \"quoted\"/grit manager"#,
1504            ),
1505            ("/tmp/#1;$x/grit", &["a b"], r"/tmp/\#1\;\$x/grit a\ b"),
1506            ("/tmp/back\\slash/grit", &[""], r"/tmp/back\\slash/grit ''"),
1507            ("/tmp/caf\u{e9}/grit", &[], "/tmp/caf\u{e9}/grit"),
1508        ];
1509        for (program, args, expected) in cases {
1510            let value = helper_config_value(Path::new(program), args).expect("formats");
1511            assert_eq!(&value, expected, "{program} {args:?}");
1512            assert!(
1513                value.starts_with('/'),
1514                "Git only runs a value as a command when it starts with an absolute path: {value}"
1515            );
1516            let mut words = vec![(*program).to_owned()];
1517            words.extend(args.iter().map(|a| (*a).to_owned()));
1518            assert_eq!(shell_words::split(&value).expect("splits"), words);
1519        }
1520    }
1521
1522    #[cfg(windows)]
1523    #[test]
1524    fn helper_config_value_writes_forward_slashes_after_the_drive() {
1525        let value = helper_config_value(Path::new(r"C:\Users\Jane Doe\bin\grit.exe"), &["manager"])
1526            .expect("formats");
1527        assert_eq!(value, r"C:/Users/Jane\ Doe/bin/grit.exe manager");
1528        assert_eq!(
1529            shell_words::split(&value).expect("splits"),
1530            ["C:/Users/Jane Doe/bin/grit.exe", "manager"]
1531        );
1532    }
1533
1534    #[test]
1535    fn helper_config_value_rejects_what_it_cannot_express() {
1536        assert_eq!(
1537            helper_config_value(Path::new("bin/grit"), &["manager"]),
1538            Err(HelperValueError::RelativeProgram {
1539                path: PathBuf::from("bin/grit")
1540            })
1541        );
1542        let absolute = std::env::temp_dir().join("grit");
1543        assert_eq!(
1544            helper_config_value(&absolute, &["a\nb"]),
1545            Err(HelperValueError::LineBreak {
1546                word: "a\nb".into()
1547            })
1548        );
1549    }
1550
1551    #[cfg(unix)]
1552    #[test]
1553    fn helper_config_value_non_unicode_program_is_rejected() {
1554        use std::os::unix::ffi::OsStrExt;
1555        let path = PathBuf::from(std::ffi::OsStr::from_bytes(b"/tmp/\xff/grit"));
1556        assert_eq!(
1557            helper_config_value(&path, &[]),
1558            Err(HelperValueError::NonUnicodeProgram { path })
1559        );
1560    }
1561
1562    #[cfg(unix)]
1563    #[test]
1564    fn formatted_helper_value_runs_the_program_directly() {
1565        let value =
1566            helper_config_value(Path::new("/opt/my tools/grit"), &["manager"]).expect("formats");
1567        let runner = RecordingRunner::default();
1568        runner.push_response(RecordedResponse::Output {
1569            stdout: b"username=u\npassword=p\n".to_vec(),
1570            code: 0,
1571        });
1572        let filled = invoke_helper(
1573            &runner,
1574            &value,
1575            "get",
1576            &Credential {
1577                protocol: Some("https".into()),
1578                host: Some("example.com".into()),
1579                ..Default::default()
1580            },
1581            &[],
1582        )
1583        .expect("helper runs");
1584        assert_eq!(filled.password.as_deref(), Some("p"));
1585        let specs = runner.specs();
1586        assert_eq!(specs.len(), 1);
1587        assert!(
1588            specs[0].shell.is_none(),
1589            "no shell between grit and the helper"
1590        );
1591        assert_eq!(specs[0].program, PathBuf::from("/opt/my tools/grit"));
1592        assert_eq!(specs[0].args, [OsString::from("manager"), "get".into()]);
1593    }
1594
1595    #[cfg(unix)]
1596    #[test]
1597    fn helper_that_exits_without_reading_stdin_still_answers() {
1598        // A request larger than any pipe buffer guarantees the write hits a closed pipe once
1599        // the helper has exited without reading it.
1600        let creds = Credential {
1601            protocol: Some("https".into()),
1602            host: Some("example.com".into()),
1603            password: Some("x".repeat(1 << 20)),
1604            ..Default::default()
1605        };
1606        let response = invoke_helper(
1607            system_command_runner().as_ref(),
1608            "!echo quit=1; exit 0; :",
1609            "get",
1610            &creds,
1611            &[],
1612        )
1613        .expect("helper");
1614        assert!(response.wants_quit());
1615    }
1616
1617    #[test]
1618    fn url_without_userinfo_strips_https_credentials() {
1619        let raw = "https://x-access-token:SECRETTOKEN@github.com/octocat/repo.git/info/refs?service=git-upload-pack";
1620        let redacted = url_without_userinfo(raw);
1621        assert_eq!(
1622            redacted,
1623            "https://github.com/octocat/repo.git/info/refs?service=git-upload-pack"
1624        );
1625        assert!(!redacted.contains("SECRETTOKEN"));
1626        assert!(!redacted.contains("x-access-token"));
1627    }
1628
1629    #[test]
1630    fn url_without_userinfo_preserves_at_in_path_query_and_fragment() {
1631        let path_at = "https://example.com/org/repo@v1.git/info/refs?service=git-upload-pack";
1632        assert_eq!(
1633            url_without_userinfo(path_at),
1634            "https://example.com/org/repo@v1.git/info/refs?service=git-upload-pack"
1635        );
1636
1637        let query_at = "https://example.com/repo.git/info/refs?notify=user@example.net";
1638        assert_eq!(
1639            url_without_userinfo(query_at),
1640            "https://example.com/repo.git/info/refs?notify=user@example.net"
1641        );
1642
1643        let fragment_at = "https://example.com/repo.git#section@anchor";
1644        assert_eq!(
1645            url_without_userinfo(fragment_at),
1646            "https://example.com/repo.git#section@anchor"
1647        );
1648    }
1649
1650    #[test]
1651    fn url_without_userinfo_strips_credentials_but_keeps_path_at() {
1652        let raw =
1653            "https://token:SECRET@127.0.0.1:8080/org/repo@v1.git/info/refs?service=git-upload-pack";
1654        let redacted = url_without_userinfo(raw);
1655        assert_eq!(
1656            redacted,
1657            "https://127.0.0.1:8080/org/repo@v1.git/info/refs?service=git-upload-pack"
1658        );
1659        assert!(!redacted.contains("SECRET"));
1660        assert!(!redacted.contains("token"));
1661    }
1662
1663    #[cfg_attr(
1664        not(feature = "full-tests"),
1665        ignore = "starts system git or is heavy; run with --features full-tests"
1666    )]
1667    #[test]
1668    fn redact_embedded_url_credentials_in_message() {
1669        let msg = "GET failed: https://user:pass@example.com/repo.git (timeout)";
1670        let out = redact_embedded_url_credentials(msg);
1671        assert!(out.contains("https://example.com/repo.git"));
1672        assert!(!out.contains("user:pass"));
1673    }
1674
1675    #[test]
1676    fn parse_round_trips_named_fields() {
1677        let input =
1678            "protocol=https\nhost=example.com\nusername=alice\npassword=secret\n\nignored=x\n";
1679        let cred = Credential::parse(input);
1680        assert_eq!(cred.protocol.as_deref(), Some("https"));
1681        assert_eq!(cred.host.as_deref(), Some("example.com"));
1682        assert_eq!(cred.username.as_deref(), Some("alice"));
1683        assert_eq!(cred.password.as_deref(), Some("secret"));
1684        // Parsing stops at the blank line.
1685        assert!(cred.extra.is_empty());
1686    }
1687
1688    #[test]
1689    fn serialize_uses_canonical_order() {
1690        let cred = Credential {
1691            protocol: Some("https".into()),
1692            host: Some("h".into()),
1693            username: Some("u".into()),
1694            password: Some("p".into()),
1695            ..Default::default()
1696        };
1697        assert_eq!(
1698            cred.serialize(),
1699            "protocol=https\nhost=h\nusername=u\npassword=p\n"
1700        );
1701    }
1702
1703    #[test]
1704    fn target_url_reconstructed_from_fields() {
1705        let cred = Credential {
1706            protocol: Some("https".into()),
1707            host: Some("github.com".into()),
1708            path: Some("o/r.git".into()),
1709            ..Default::default()
1710        };
1711        assert_eq!(
1712            cred.target_url().as_deref(),
1713            Some("https://github.com/o/r.git")
1714        );
1715    }
1716
1717    #[test]
1718    fn from_url_omits_http_path_unless_use_http_path_applies() {
1719        let plain = ConfigSet::new();
1720        let cred = Credential::from_url("http://127.0.0.1:9418/hw.git", &plain).expect("cred");
1721        assert_eq!(cred.protocol.as_deref(), Some("http"));
1722        assert_eq!(cred.host.as_deref(), Some("127.0.0.1:9418"));
1723        assert_eq!(cred.path, None);
1724        assert_eq!(cred.url.as_deref(), Some("http://127.0.0.1:9418/hw.git"));
1725
1726        let mut scoped = ConfigSet::new();
1727        scoped
1728            .add_command_override("credential.https://example.com/team.useHttpPath", "true")
1729            .unwrap();
1730        let in_scope =
1731            Credential::from_url("https://example.com/team/a%20b.git/", &scoped).expect("cred");
1732        assert_eq!(in_scope.path.as_deref(), Some("team/a b.git"));
1733        let out_of_scope =
1734            Credential::from_url("https://example.com/other/repo.git", &scoped).expect("cred");
1735        assert_eq!(out_of_scope.path, None);
1736    }
1737
1738    #[test]
1739    fn from_url_keeps_path_for_non_http_protocols_and_rejects_hostless_urls() {
1740        let cfg = ConfigSet::new();
1741        let cred = Credential::from_url("ftp://files.example/pub/repo.git", &cfg).expect("cred");
1742        assert_eq!(cred.path.as_deref(), Some("pub/repo.git"));
1743        assert_eq!(Credential::from_url("not a url", &cfg), None);
1744        assert_eq!(Credential::from_url("file:///tmp/repo.git", &cfg), None);
1745    }
1746
1747    #[test]
1748    fn helper_request_drops_url_and_fills_missing_fields_from_it() {
1749        let provider = HelperCredentialProvider::new(ConfigSet::new());
1750        let decomposed =
1751            Credential::from_url("http://127.0.0.1:9418/hw.git", &ConfigSet::new()).expect("cred");
1752        assert_eq!(
1753            provider.helper_request(&decomposed).serialize(),
1754            "protocol=http\nhost=127.0.0.1:9418\n"
1755        );
1756
1757        let url_only = Credential {
1758            url: Some("https://example.com/o/r.git".into()),
1759            username: Some("alice".into()),
1760            ..Default::default()
1761        };
1762        assert_eq!(
1763            provider.helper_request(&url_only).serialize(),
1764            "protocol=https\nhost=example.com\nusername=alice\n"
1765        );
1766    }
1767
1768    #[cfg(unix)]
1769    #[test]
1770    fn helpers_never_receive_the_url_key() {
1771        let tmp = tempfile::tempdir().expect("tempdir");
1772        let log = tmp.path().join("helper.log");
1773        let mut cfg = ConfigSet::new();
1774        cfg.add_command_override(
1775            "credential.http://127.0.0.1:9418/hw.git.helper",
1776            &format!(
1777                "!cat >>'{}'; echo username=u; echo password=p; :",
1778                log.display()
1779            ),
1780        )
1781        .unwrap();
1782        let provider = HelperCredentialProvider::new(cfg.clone());
1783        let input = Credential::from_url("http://127.0.0.1:9418/hw.git", &cfg).expect("cred");
1784
1785        let filled = provider
1786            .fill(&input)
1787            .expect("path-scoped helper still matches");
1788        assert_eq!(filled.username.as_deref(), Some("u"));
1789        provider.approve(&filled).expect("store");
1790
1791        assert_eq!(
1792            std::fs::read_to_string(&log).expect("helper log"),
1793            "protocol=http\nhost=127.0.0.1:9418\n\n\
1794             protocol=http\nhost=127.0.0.1:9418\nusername=u\npassword=p\n\n"
1795        );
1796    }
1797
1798    fn env_with(vars: &[(&str, &str)]) -> Environment {
1799        Environment::from_vars(
1800            vars.iter()
1801                .map(|(k, v)| (OsString::from(k), OsString::from(v))),
1802            PathBuf::from("/"),
1803        )
1804    }
1805
1806    fn config_with(entries: &[(&str, &str)]) -> ConfigSet {
1807        let mut cfg = ConfigSet::new();
1808        for (key, value) in entries {
1809            cfg.add_command_override(key, value).unwrap();
1810        }
1811        cfg
1812    }
1813
1814    #[test]
1815    fn askpass_program_prefers_git_askpass_then_core_askpass_then_ssh_askpass() {
1816        let cfg = config_with(&[("core.askPass", "/cfg/askpass")]);
1817        let all = env_with(&[("GIT_ASKPASS", "/env/git"), ("SSH_ASKPASS", "/env/ssh")]);
1818        assert_eq!(askpass_program(&all, &cfg), Some(PathBuf::from("/env/git")));
1819        let ssh_only = env_with(&[("SSH_ASKPASS", "/env/ssh")]);
1820        assert_eq!(
1821            askpass_program(&ssh_only, &cfg),
1822            Some(PathBuf::from("/cfg/askpass"))
1823        );
1824        assert_eq!(
1825            askpass_program(&ssh_only, &ConfigSet::new()),
1826            Some(PathBuf::from("/env/ssh"))
1827        );
1828        assert_eq!(
1829            askpass_program(&Environment::empty(), &ConfigSet::new()),
1830            None
1831        );
1832    }
1833
1834    #[test]
1835    fn askpass_program_empty_value_disables_askpass_and_core_askpass_expands_home() {
1836        let cfg = config_with(&[("core.askPass", "~/bin/askpass")]);
1837        let empty_git = env_with(&[("GIT_ASKPASS", ""), ("SSH_ASKPASS", "/env/ssh")]);
1838        assert_eq!(askpass_program(&empty_git, &cfg), None);
1839        let home = env_with(&[("HOME", "/home/ci")]);
1840        assert_eq!(
1841            askpass_program(&home, &cfg),
1842            Some(PathBuf::from("/home/ci/bin/askpass"))
1843        );
1844        let empty_cfg = config_with(&[("core.askPass", "")]);
1845        assert_eq!(
1846            askpass_program(&env_with(&[("SSH_ASKPASS", "/env/ssh")]), &empty_cfg),
1847            None
1848        );
1849    }
1850
1851    fn askpass_provider(
1852        cfg: ConfigSet,
1853        responses: Vec<RecordedResponse>,
1854    ) -> (HelperCredentialProvider, Arc<RecordingRunner>) {
1855        let runner = Arc::new(RecordingRunner::default());
1856        for response in responses {
1857            runner.push_response(response);
1858        }
1859        let provider = HelperCredentialProvider::new(cfg)
1860            .with_command_runner(runner.clone())
1861            .with_askpass(Some(PathBuf::from("/ci/askpass")));
1862        (provider, runner)
1863    }
1864
1865    fn answer(text: &str) -> RecordedResponse {
1866        RecordedResponse::Output {
1867            stdout: text.as_bytes().to_vec(),
1868            code: 0,
1869        }
1870    }
1871
1872    fn askpass_prompts(runner: &RecordingRunner) -> Vec<String> {
1873        runner
1874            .specs()
1875            .iter()
1876            .map(|spec| {
1877                assert_eq!(spec.program, PathBuf::from("/ci/askpass"));
1878                assert!(spec.shell.is_none(), "askpass runs without a shell");
1879                assert!(matches!(spec.stdin, CommandStdin::Null));
1880                assert_eq!(spec.args.len(), 1, "the prompt is the only argument");
1881                spec.args[0].to_string_lossy().into_owned()
1882            })
1883            .collect()
1884    }
1885
1886    #[test]
1887    fn fill_asks_askpass_for_username_then_password_and_keeps_the_first_line() {
1888        let (provider, runner) = askpass_provider(
1889            ConfigSet::new(),
1890            vec![answer("ci\nignored\n"), answer("s3cret\r\n")],
1891        );
1892        let input =
1893            Credential::from_url("http://127.0.0.1:9431/hello.git", &ConfigSet::new()).unwrap();
1894        let filled = provider.fill(&input).expect("askpass fills");
1895        assert_eq!(filled.username.as_deref(), Some("ci"));
1896        assert_eq!(filled.password.as_deref(), Some("s3cret"));
1897        assert_eq!(
1898            askpass_prompts(&runner),
1899            [
1900                "Username for 'http://127.0.0.1:9431': ",
1901                "Password for 'http://ci@127.0.0.1:9431': ",
1902            ]
1903        );
1904    }
1905
1906    #[test]
1907    fn fill_asks_only_for_the_password_when_the_url_names_the_user() {
1908        let cfg = config_with(&[("credential.useHttpPath", "true")]);
1909        let (provider, runner) = askpass_provider(cfg.clone(), vec![answer("tok")]);
1910        let input = Credential::from_url("https://ci@example.com/o/r.git", &cfg).unwrap();
1911        let filled = provider.fill(&input).expect("askpass fills");
1912        assert_eq!(filled.username.as_deref(), Some("ci"));
1913        assert_eq!(filled.password.as_deref(), Some("tok"));
1914        assert_eq!(
1915            askpass_prompts(&runner),
1916            ["Password for 'https://ci@example.com/o/r.git': "]
1917        );
1918    }
1919
1920    #[test]
1921    fn askpass_prompt_is_sanitized_unless_disabled() {
1922        let cred = Credential {
1923            protocol: Some("https".into()),
1924            host: Some("example.com".into()),
1925            username: Some("a b/c\x1b".into()),
1926            path: Some("o/r e.git".into()),
1927            ..Default::default()
1928        };
1929        assert_eq!(
1930            cred.prompt("Password", true),
1931            "Password for 'https://a%20b%2Fc%1B@example.com/o/r%20e.git': "
1932        );
1933        assert_eq!(
1934            cred.prompt("Password", false),
1935            "Password for 'https://a b/c\x1b@example.com/o/r e.git': "
1936        );
1937        assert_eq!(Credential::default().prompt("Username", true), "Username: ");
1938
1939        let (provider, runner) = askpass_provider(
1940            config_with(&[("credential.sanitizePrompt", "false")]),
1941            vec![answer("p")],
1942        );
1943        let input = Credential {
1944            username: Some("a b".into()),
1945            ..cred
1946        };
1947        provider.fill(&input).expect("askpass fills");
1948        assert_eq!(
1949            askpass_prompts(&runner),
1950            ["Password for 'https://a b@example.com/o/r e.git': "]
1951        );
1952    }
1953
1954    #[test]
1955    fn url_scoped_sanitize_prompt_applies_only_to_matching_urls() {
1956        let cfg = config_with(&[("credential.https://example.com.sanitizePrompt", "false")]);
1957        for (url, expected) in [
1958            (
1959                "https://a%20b@example.com/r.git",
1960                "Password for 'https://a b@example.com': ",
1961            ),
1962            (
1963                "https://a%20b@other.example/r.git",
1964                "Password for 'https://a%20b@other.example': ",
1965            ),
1966        ] {
1967            let (provider, runner) = askpass_provider(cfg.clone(), vec![answer("p")]);
1968            let input = Credential::from_url(url, &cfg).unwrap();
1969            provider.fill(&input).expect("askpass fills");
1970            assert_eq!(askpass_prompts(&runner), [expected], "{url}");
1971        }
1972    }
1973
1974    #[test]
1975    fn empty_askpass_answers_are_kept_like_git() {
1976        let (provider, runner) = askpass_provider(ConfigSet::new(), vec![answer("\n"), answer("")]);
1977        let input = Credential::from_url("https://example.com/r.git", &ConfigSet::new()).unwrap();
1978        let filled = provider
1979            .fill(&input)
1980            .expect("empty answers are still answers");
1981        assert_eq!(filled.username.as_deref(), Some(""));
1982        assert_eq!(filled.password.as_deref(), Some(""));
1983        assert_eq!(runner.specs().len(), 2, "each field is asked once");
1984    }
1985
1986    #[test]
1987    fn failing_askpass_is_an_error_naming_the_program() {
1988        let (provider, _runner) =
1989            askpass_provider(ConfigSet::new(), vec![RecordedResponse::Exit(3)]);
1990        let input = Credential::from_url("https://example.com/r.git", &ConfigSet::new()).unwrap();
1991        let err = provider.fill(&input).expect_err("askpass failed");
1992        let message = err.to_string();
1993        assert!(message.contains("/ci/askpass"), "{message}");
1994        assert!(message.contains("status 3"), "{message}");
1995    }
1996
1997    #[test]
1998    fn no_askpass_or_credential_interactive_never_keeps_fill_non_interactive() {
1999        let input = Credential::from_url("https://example.com/r.git", &ConfigSet::new()).unwrap();
2000        let err = HelperCredentialProvider::new(ConfigSet::new())
2001            .fill(&input)
2002            .expect_err("nothing can answer");
2003        assert_eq!(err.to_string(), NON_INTERACTIVE_MESSAGE);
2004
2005        for value in ["never", "false"] {
2006            let (provider, runner) = askpass_provider(
2007                config_with(&[("credential.interactive", value)]),
2008                vec![answer("unused")],
2009            );
2010            let err = provider.fill(&input).expect_err("askpass disabled");
2011            assert_eq!(err.to_string(), NON_INTERACTIVE_MESSAGE);
2012            assert!(
2013                runner.specs().is_empty(),
2014                "askpass must not run for {value}"
2015            );
2016        }
2017    }
2018
2019    #[test]
2020    fn unavailable_credentials_name_the_helpers_that_were_asked() {
2021        let input = Credential::from_url("https://example.com/r.git", &ConfigSet::new()).unwrap();
2022        let err = HelperCredentialProvider::new(ConfigSet::new())
2023            .fill(&input)
2024            .expect_err("no helper");
2025        assert!(
2026            matches!(
2027                &err,
2028                Error::Remote(RemoteError::CredentialsUnavailable { helpers }) if helpers.is_empty()
2029            ),
2030            "{err:?}"
2031        );
2032
2033        let runner = Arc::new(RecordingRunner::default());
2034        runner.push_response(answer(""));
2035        let err = HelperCredentialProvider::new(config_with(&[("credential.helper", "!empty")]))
2036            .with_command_runner(runner.clone())
2037            .fill(&input)
2038            .expect_err("the helper has nothing");
2039        assert_eq!(err.to_string(), NON_INTERACTIVE_MESSAGE);
2040        assert!(
2041            runner
2042                .specs()
2043                .iter()
2044                .any(|spec| format!("{spec:?}").contains("empty")),
2045            "the helper was asked"
2046        );
2047        let failure = crate::error::AuthFailure::from_fill_error(err);
2048        assert_eq!(
2049            failure,
2050            crate::error::AuthFailure::CredentialsUnavailable {
2051                detail: NON_INTERACTIVE_MESSAGE.to_owned(),
2052                helpers: vec!["!empty".to_owned()],
2053            }
2054        );
2055
2056        let other = crate::error::AuthFailure::from_fill_error(credential_err("helper crashed"));
2057        assert!(matches!(
2058            other,
2059            crate::error::AuthFailure::CredentialsUnavailable { detail, helpers }
2060                if detail == "helper crashed" && helpers.is_empty()
2061        ));
2062    }
2063
2064    #[test]
2065    fn from_url_takes_decoded_userinfo_and_keeps_it_out_of_the_url() {
2066        let cfg = ConfigSet::new();
2067        let cred =
2068            Credential::from_url("https://ci%40corp:p%3Ass@example.com/r.git", &cfg).unwrap();
2069        assert_eq!(cred.username.as_deref(), Some("ci@corp"));
2070        assert_eq!(cred.password.as_deref(), Some("p:ss"));
2071        assert_eq!(cred.url.as_deref(), Some("https://example.com/r.git"));
2072        assert!(cred.is_complete());
2073
2074        let user_only = Credential::from_url("https://ci@example.com/r.git", &cfg).unwrap();
2075        assert_eq!(user_only.username.as_deref(), Some("ci"));
2076        assert_eq!(user_only.password, None);
2077    }
2078
2079    #[cfg(unix)]
2080    #[test]
2081    fn helpers_answer_before_askpass_runs() {
2082        let tmp = tempfile::tempdir().expect("tempdir");
2083        let askpass = tmp.path().join("askpass");
2084        let log = tmp.path().join("askpass.log");
2085        std::fs::write(
2086            &askpass,
2087            format!(
2088                "#!/bin/sh\necho \"$1\" >>'{}'\necho from-askpass\n",
2089                log.display()
2090            ),
2091        )
2092        .unwrap();
2093        let mut perms = std::fs::metadata(&askpass).unwrap().permissions();
2094        std::os::unix::fs::PermissionsExt::set_mode(&mut perms, 0o755);
2095        std::fs::set_permissions(&askpass, perms).unwrap();
2096
2097        let cfg = config_with(&[("credential.helper", "!echo username=helper-user; :")]);
2098        let provider = HelperCredentialProvider::new(cfg.clone()).with_askpass(Some(askpass));
2099        let input = Credential::from_url("https://example.com/r.git", &cfg).unwrap();
2100        let filled = provider.fill(&input).expect("helper plus askpass");
2101        assert_eq!(filled.username.as_deref(), Some("helper-user"));
2102        assert_eq!(filled.password.as_deref(), Some("from-askpass"));
2103        assert_eq!(
2104            std::fs::read_to_string(&log).unwrap(),
2105            "Password for 'https://helper-user@example.com': \n"
2106        );
2107
2108        let complete =
2109            config_with(&[("credential.helper", "!echo username=u; echo password=p; :")]);
2110        let provider = HelperCredentialProvider::new(complete.clone())
2111            .with_askpass(Some(tmp.path().join("askpass")));
2112        provider.fill(&input).expect("helper answers");
2113        assert_eq!(
2114            std::fs::read_to_string(&log).unwrap().lines().count(),
2115            1,
2116            "askpass must not run when a helper completes the credential"
2117        );
2118    }
2119
2120    #[test]
2121    fn git_for_windows_exec_path_adds_mingw64_bin_not_libexec_bin() {
2122        // Forward slashes so the path parses on Unix CI as well as on Windows.
2123        let exec_path = PathBuf::from("C:/Program Files/Git/mingw64/libexec/git-core");
2124        let bins = credential_helper_bin_dirs_from_exec_path(&exec_path);
2125        let mingw_bin = PathBuf::from("C:/Program Files/Git/mingw64/bin");
2126        assert!(
2127            bins.contains(&mingw_bin),
2128            "GCM lives in mingw64/bin, got {bins:?}"
2129        );
2130        let libexec_bin = PathBuf::from("C:/Program Files/Git/mingw64/libexec/bin");
2131        assert!(
2132            bins.contains(&libexec_bin),
2133            "libexec/bin is still listed for other layouts: {bins:?}"
2134        );
2135    }
2136
2137    #[test]
2138    fn resolve_manager_finds_helper_in_git_for_windows_layout() {
2139        use std::collections::HashSet;
2140        use std::fs;
2141
2142        let tmp = tempfile::tempdir().expect("tempdir");
2143        let git_core = tmp.path().join("mingw64/libexec/git-core");
2144        let mingw_bin = tmp.path().join("mingw64/bin");
2145        fs::create_dir_all(&git_core).expect("git-core dir");
2146        fs::create_dir_all(&mingw_bin).expect("mingw bin dir");
2147        fs::write(mingw_bin.join("git-credential-manager"), b"").expect("fake gcm");
2148
2149        let mut candidates = Vec::new();
2150        let mut seen = HashSet::new();
2151        push_exec_path_candidate(&mut candidates, &mut seen, git_core);
2152
2153        let resolved = candidates.iter().find_map(|ep| {
2154            let candidate = ep.join("git-credential-manager");
2155            credential_helper_executable_at(&candidate)
2156        });
2157        assert_eq!(
2158            resolved,
2159            Some(mingw_bin.join("git-credential-manager")),
2160            "manager helper must resolve via mingw64/bin, searched {candidates:?}"
2161        );
2162    }
2163
2164    #[test]
2165    fn installed_helpers_are_found_in_the_exec_path() {
2166        let dir = tempfile::tempdir().unwrap();
2167        let program = dir.path().join("git-credential-osxkeychain");
2168        std::fs::write(&program, "#!/bin/sh\n").unwrap();
2169        let provider = HelperCredentialProvider::new(ConfigSet::default());
2170        provider
2171            .probed_git_exec_path
2172            .set(vec![dir.path().to_path_buf()])
2173            .unwrap();
2174        assert!(provider.helper_installed("osxkeychain"));
2175        assert!(!provider.helper_installed("no-such-helper-anywhere"));
2176        let suggested = provider.suggested_helper();
2177        assert!(
2178            suggested.is_none_or(|name| SUGGESTED_HELPERS.contains(&name)),
2179            "{suggested:?}"
2180        );
2181        #[cfg(target_os = "macos")]
2182        assert_eq!(suggested, Some("osxkeychain"));
2183    }
2184}