Skip to main content

gitpoulpi_core/
failure.rs

1//! What went wrong, in enough detail to paste to someone (or an AI) who can
2//! explain it: the operation, the git command line that ran, its exit code
3//! and the tail of its stderr, or libgit2's class/code/message.
4//!
5//! Everything in an [`ErrorDetail`] has been through [`redact`], so it is
6//! safe to show, log and copy: URLs with credentials, `Authorization`
7//! headers, well-known token shapes and `password=`-style pairs never reach
8//! it. [`FailureKind`] is the best-effort reading of git's English messages
9//! that the frontends turn into a friendly sentence and a suggested action.
10//! It is only ever a hint: an unknown or localised message stays
11//! [`FailureKind::Other`] and the raw text is still there.
12
13use serde::{Deserialize, Serialize};
14
15/// How many trailing stderr lines an [`ErrorDetail`] keeps.
16pub const STDERR_TAIL_LINES: usize = 30;
17
18/// libgit2's own account of a failure.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Git2Detail {
21    /// `git_error_t` class, e.g. `Net`, `Ssh`, `Http`.
22    pub class: String,
23    /// `git_error_code`, e.g. `Auth`, `NotFound`.
24    pub code: String,
25    pub message: String,
26}
27
28/// The facts of one failed backend operation.
29#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30pub struct ErrorDetail {
31    /// What the user asked for (`Push`, `Pull`, ...), or git's subcommand
32    /// until the daemon names the operation.
33    pub operation: String,
34    /// The git command line that ran, redacted. GitPoulpi's pinned `-c`
35    /// output-shape overrides are left out: they are on every command.
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub command: Option<String>,
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub exit_code: Option<i32>,
40    /// The last [`STDERR_TAIL_LINES`] lines of stderr, redacted.
41    #[serde(default, skip_serializing_if = "String::is_empty")]
42    pub stderr: String,
43    #[serde(default, skip_serializing_if = "Option::is_none")]
44    pub git2: Option<Git2Detail>,
45}
46
47impl ErrorDetail {
48    /// A failed `git <args>`: `args` are the command's own arguments.
49    pub fn from_git(args: &[&str], exit_code: Option<i32>, stderr: &str) -> Self {
50        let command = redact(&format!("git {}", args.join(" ")));
51        ErrorDetail {
52            operation: args.first().copied().unwrap_or("git").to_string(),
53            command: Some(command),
54            exit_code,
55            stderr: tail_lines(&redact(stderr), STDERR_TAIL_LINES),
56            git2: None,
57        }
58    }
59
60    /// A libgit2 failure.
61    pub fn from_git2(
62        operation: &str,
63        class: impl Into<String>,
64        code: impl Into<String>,
65        message: &str,
66    ) -> Self {
67        ErrorDetail {
68            operation: operation.to_string(),
69            command: None,
70            exit_code: None,
71            stderr: String::new(),
72            git2: Some(Git2Detail {
73                class: class.into(),
74                code: code.into(),
75                message: redact(message),
76            }),
77        }
78    }
79
80    /// The same detail under the user-level operation's name.
81    pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
82        self.operation = operation.into();
83        self
84    }
85
86    /// The best-effort reading of what failed.
87    pub fn kind(&self) -> FailureKind {
88        let mut text = self.stderr.clone();
89        if let Some(g) = &self.git2 {
90            text.push('\n');
91            text.push_str(&g.message);
92            if g.code == "Auth" || g.class == "Ssh" && g.message.contains("auth") {
93                return FailureKind::AuthFailed;
94            }
95        }
96        FailureKind::classify(&text)
97    }
98
99    /// The facts as plain text lines, for a report.
100    pub fn lines(&self) -> Vec<String> {
101        let mut out = vec![format!("operation: {}", self.operation)];
102        if let Some(c) = &self.command {
103            out.push(format!("command: {c}"));
104        }
105        if let Some(code) = self.exit_code {
106            out.push(format!("exit code: {code}"));
107        }
108        if let Some(g) = &self.git2 {
109            out.push(format!(
110                "libgit2: class={} code={} message={}",
111                g.class, g.code, g.message
112            ));
113        }
114        if !self.stderr.trim().is_empty() {
115            out.push("stderr:".to_string());
116            out.extend(self.stderr.lines().map(|l| format!("  {l}")));
117        }
118        out
119    }
120}
121
122/// What kind of failure git's message describes. The frontends map each to
123/// a sentence and, where one exists, an action.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
125#[serde(rename_all = "snake_case")]
126pub enum FailureKind {
127    /// The remote has commits this branch lacks: pull first.
128    NonFastForward,
129    /// Credentials missing, wrong or refused.
130    AuthFailed,
131    /// The configured credential helper itself could not run (a missing
132    /// script, a helper not on `PATH`, a helper that quit): git then sent no
133    /// credentials and the remote's refusal that follows is a consequence,
134    /// not the cause. [`FailureKind::credential_helper_line`] has the line.
135    CredentialHelperFailed,
136    /// A merge, rebase or pull stopped on conflicts.
137    MergeConflict,
138    /// Local changes would be overwritten: commit, stash or discard.
139    WouldOverwrite,
140    /// ssh does not know the remote's host key and could not ask: connect
141    /// once in a terminal to verify and add it.
142    HostKeyUnverified,
143    /// The remote could not be reached.
144    NetworkUnreachable,
145    /// Another git process holds `index.lock` (or another lock file).
146    LockExists,
147    /// An abort refused because files have local changes it would overwrite
148    /// (`ConflictRefusal::LocalChanges`). Never read from text: the typed
149    /// error sets it.
150    LocalChangesBlockAbort,
151    Other,
152}
153
154impl FailureKind {
155    /// Classifies git's English stderr. Order matters: the specific
156    /// "would be overwritten" and lock messages come before the broad ones.
157    pub fn classify(stderr: &str) -> FailureKind {
158        let s = stderr.to_lowercase();
159        let has = |needles: &[&str]| needles.iter().any(|n| s.contains(n));
160        if has(&[
161            "would be overwritten by",
162            "please commit your changes or stash them",
163        ]) {
164            FailureKind::WouldOverwrite
165        } else if has(&[
166            ".lock': file exists",
167            ".lock\": file exists",
168            "another git process seems to be running",
169        ]) {
170            FailureKind::LockExists
171        } else if has(&[
172            "host key verification failed",
173            "no matching host key type found",
174            "remote host identification has changed",
175        ]) {
176            FailureKind::HostKeyUnverified
177        } else if credential_helper_line(stderr).is_some_and(|(_, certain)| {
178            certain
179                || has(&[
180                    "authentication failed",
181                    "could not read username",
182                    "could not read password",
183                    "terminal prompts disabled",
184                    "invalid username or",
185                    "the requested url returned error: 401",
186                    "the requested url returned error: 403",
187                ])
188        }) {
189            FailureKind::CredentialHelperFailed
190        } else if has(&[
191            "authentication failed",
192            "could not read username",
193            "could not read password",
194            "permission denied (publickey",
195            "permission denied (password",
196            "invalid username or password",
197            "terminal prompts disabled",
198            "the requested url returned error: 401",
199            "the requested url returned error: 403",
200            "http basic: access denied",
201            "support for password authentication was removed",
202        ]) {
203            FailureKind::AuthFailed
204        } else if has(&[
205            "could not resolve host",
206            "connection refused",
207            "connection timed out",
208            "operation timed out",
209            "network is unreachable",
210            "failed to connect to",
211            "could not connect to server",
212            "temporary failure in name resolution",
213            "connection reset",
214            "unable to access",
215        ]) {
216            FailureKind::NetworkUnreachable
217        } else if has(&[
218            "conflict (",
219            "automatic merge failed",
220            "fix conflicts and",
221            "merge conflict in",
222        ]) {
223            FailureKind::MergeConflict
224        } else if has(&[
225            "non-fast-forward",
226            "fetch first",
227            "updates were rejected because",
228            "not possible to fast-forward",
229            "divergent branches",
230            "diverging branches",
231        ]) {
232            FailureKind::NonFastForward
233        } else {
234            FailureKind::Other
235        }
236    }
237}
238
239impl FailureKind {
240    /// The stderr line that shows a credential helper failing to run, for a
241    /// [`FailureKind::CredentialHelperFailed`] reading (`None` otherwise).
242    pub fn credential_helper_line(stderr: &str) -> Option<String> {
243        credential_helper_line(stderr).map(|(line, _)| line.trim().to_string())
244    }
245}
246
247/// The first stderr line that reads as a credential helper that could not
248/// run, with whether the line names the helper itself (`certain`) or is a
249/// bare shell failure (`sh: /c/Users/x/token.sh: No such file or directory`)
250/// that only counts next to an authentication failure.
251///
252/// The realistic shapes: a `credential.helper = !script` or an absolute path
253/// run through `sh` (`sh: ...: No such file or directory`, `... not found`,
254/// `Permission denied`, `/bin/sh: 1: x: not found`), `helper = foo` with no
255/// `git-credential-foo` on `PATH` (`git: 'credential-foo' is not a git
256/// command`), a helper that exited asking git to stop (`fatal: credential
257/// helper '...' told us to quit`), and cmd.exe's "is not recognized".
258fn credential_helper_line(stderr: &str) -> Option<(&str, bool)> {
259    for line in stderr.lines() {
260        // A message made of the command and its first stderr line:
261        // `backend error: git fetch ... failed: sh: x: No such file`.
262        let line = line
263            .find(" failed: ")
264            .map_or(line, |i| &line[i + " failed: ".len()..]);
265        let lower = line.trim().to_lowercase();
266        let l = lower.strip_prefix("error: ").unwrap_or(&lower);
267        let l = l.strip_prefix("fatal: ").unwrap_or(l);
268        let shell_failure = [
269            "no such file or directory",
270            "not found",
271            "permission denied",
272            "cannot execute",
273            "exec format error",
274            "bad interpreter",
275        ]
276        .iter()
277        .any(|n| l.contains(n));
278        let names_helper = l.contains("credential");
279        // bash as `sh` names the script and the line instead:
280        // `/x/helper get: line 1: /x/helper: No such file or directory`.
281        let shell_prefix = [
282            "sh: ",
283            "/bin/sh: ",
284            "bash: ",
285            "/bin/bash: ",
286            "dash: ",
287            "/bin/dash: ",
288        ]
289        .iter()
290        .any(|p| l.starts_with(p))
291            || l.contains(": line ");
292        if (l.contains("is not a git command") && l.contains("credential-"))
293            || (l.contains("credential helper") && l.contains("told us to quit"))
294            || (names_helper && shell_failure && (shell_prefix || l.contains("cannot run")))
295            || (names_helper && l.contains("is not recognized as an internal or external command"))
296        {
297            return Some((line, true));
298        }
299        if shell_prefix && shell_failure {
300            return Some((line, false));
301        }
302    }
303    None
304}
305
306/// The last `n` lines of `text`, trimmed of surrounding blank lines.
307pub fn tail_lines(text: &str, n: usize) -> String {
308    let lines: Vec<&str> = text.trim().lines().collect();
309    let skip = lines.len().saturating_sub(n);
310    let mut out = lines[skip..].join("\n");
311    if skip > 0 {
312        out.insert_str(0, &format!("[{skip} earlier lines omitted]\n"));
313    }
314    out
315}
316
317const MASK: &str = "***";
318
319/// Keys whose value is a secret when written `key=value` or `key: value`.
320const SECRET_KEYS: &[&str] = &[
321    "password",
322    "passwd",
323    "pwd",
324    "token",
325    "secret",
326    "api_key",
327    "apikey",
328    "api-key",
329    "access_token",
330    "private_token",
331    "private-token",
332    "client_secret",
333    "authorization",
334    "proxy-authorization",
335    "x-api-key",
336];
337
338/// `text` with credentials masked: userinfo in URLs, `Authorization`
339/// style headers, `Bearer`/`Basic` values, token-shaped words and
340/// `password=...` pairs. Idempotent, line structure preserved.
341pub fn redact(text: &str) -> String {
342    let masked = text
343        .split_inclusive('\n')
344        .map(redact_line)
345        .collect::<String>();
346    mask_registered(masked)
347}
348
349/// Secrets this process knows exactly (a token it resolved for a grant),
350/// masked wherever they appear whatever they look like: a token with no
351/// known prefix is invisible to the shape rules above.
352fn registered_secrets() -> &'static std::sync::Mutex<Vec<String>> {
353    static SECRETS: std::sync::OnceLock<std::sync::Mutex<Vec<String>>> = std::sync::OnceLock::new();
354    SECRETS.get_or_init(Default::default)
355}
356
357/// Shorter values would mask ordinary words.
358const MIN_REGISTERED_SECRET: usize = 6;
359
360/// Remembers `secret` for the life of the process: [`redact`] masks every
361/// occurrence of it from now on. A value shorter than six characters is
362/// ignored (it would mask ordinary text); registering twice is harmless.
363pub fn redact_register_secret(secret: &str) {
364    let secret = secret.trim();
365    if secret.len() < MIN_REGISTERED_SECRET {
366        return;
367    }
368    let mut all = registered_secrets()
369        .lock()
370        .unwrap_or_else(|e| e.into_inner());
371    if !all.iter().any(|s| s == secret) {
372        all.push(secret.to_string());
373    }
374}
375
376fn mask_registered(text: String) -> String {
377    let all = registered_secrets()
378        .lock()
379        .unwrap_or_else(|e| e.into_inner());
380    all.iter().fold(text, |text, secret| {
381        if text.contains(secret.as_str()) {
382            text.replace(secret.as_str(), "***")
383        } else {
384            text
385        }
386    })
387}
388
389fn redact_line(line: &str) -> String {
390    let line = redact_urls(line);
391    let line = redact_pairs(&line);
392    let line = redact_bearer(&line);
393    redact_prefixed_tokens(&line)
394}
395
396fn is_word_char(c: char) -> bool {
397    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '~' | '+' | '/' | '=')
398}
399
400/// `scheme://user:secret@host` becomes `scheme://***@host`.
401fn redact_urls(line: &str) -> String {
402    let mut out = String::with_capacity(line.len());
403    let mut rest = line;
404    while let Some(pos) = rest.find("://") {
405        let (head, tail) = rest.split_at(pos + 3);
406        out.push_str(head);
407        let end = tail
408            .find(|c: char| c.is_whitespace() || matches!(c, '/' | '"' | '\'' | '<' | '>'))
409            .unwrap_or(tail.len());
410        let authority = &tail[..end];
411        match authority.rfind('@') {
412            Some(at) if at > 0 => {
413                out.push_str(MASK);
414                out.push_str(&authority[at..]);
415            }
416            _ => out.push_str(authority),
417        }
418        rest = &tail[end..];
419    }
420    out.push_str(rest);
421    out
422}
423
424/// `key=value` / `key: value` for the secret keys (case-insensitive).
425fn redact_pairs(line: &str) -> String {
426    let lower = line.to_lowercase();
427    let mut out = String::with_capacity(line.len());
428    let mut i = 0;
429    let bytes = line.as_bytes();
430    while i < line.len() {
431        let mut matched = None;
432        // Only at a key boundary: start of line or after a non-word char.
433        let boundary = i == 0
434            || !line[..i]
435                .chars()
436                .next_back()
437                .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_');
438        if boundary && line.is_char_boundary(i) {
439            for key in SECRET_KEYS {
440                if lower[i..].starts_with(key) {
441                    let after = i + key.len();
442                    let mut j = after;
443                    while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'"') {
444                        j += 1;
445                    }
446                    if j < bytes.len() && (bytes[j] == b'=' || bytes[j] == b':') && j > after - 1 {
447                        // key, optional spaces, separator, optional spaces
448                        let mut k = j + 1;
449                        while k < bytes.len() && bytes[k] == b' ' {
450                            k += 1;
451                        }
452                        // A header value runs to the end of the line; a
453                        // pair's value to whitespace, `&` or a quote.
454                        let header = *key == "authorization" || *key == "proxy-authorization";
455                        let mut end = k;
456                        while end < line.len() {
457                            let c = line[end..].chars().next().unwrap();
458                            let stop = if header {
459                                c == '\n' || c == '\r' || c == '"' || c == '\''
460                            } else {
461                                c.is_whitespace() || matches!(c, '&' | '"' | '\'' | ',' | ';')
462                            };
463                            if stop {
464                                break;
465                            }
466                            end += c.len_utf8();
467                        }
468                        if end > k {
469                            matched = Some((after, j + 1, k, end));
470                        }
471                    }
472                    break;
473                }
474            }
475        }
476        match matched {
477            Some((after, sep_end, value_start, end)) => {
478                out.push_str(&line[i..after]);
479                out.push_str(&line[after..sep_end]);
480                out.push_str(&line[sep_end..value_start]);
481                out.push_str(MASK);
482                i = end;
483            }
484            None => {
485                let c = line[i..].chars().next().unwrap();
486                out.push(c);
487                i += c.len_utf8();
488            }
489        }
490    }
491    out
492}
493
494/// `Bearer abc` and `Basic abc` (any case).
495fn redact_bearer(line: &str) -> String {
496    let lower = line.to_lowercase();
497    let mut out = String::with_capacity(line.len());
498    let mut i = 0;
499    while i < line.len() {
500        let rest = &lower[i..];
501        let scheme = ["bearer ", "basic ", "token "]
502            .into_iter()
503            .find(|s| rest.starts_with(s));
504        let boundary = i == 0
505            || !line[..i]
506                .chars()
507                .next_back()
508                .is_some_and(|c| c.is_ascii_alphanumeric());
509        if let (Some(s), true) = (scheme, boundary) {
510            let value_start = i + s.len();
511            let value: String = line[value_start..]
512                .chars()
513                .take_while(|c| is_word_char(*c))
514                .collect();
515            // "basic " / "token " are ordinary words: only mask a value that
516            // looks like a credential (long enough, no plain-word look).
517            let credential = value.len() >= 12 || (s.starts_with("bearer") && value.len() >= 6);
518            if credential && !value.contains(MASK) {
519                out.push_str(&line[i..value_start]);
520                out.push_str(MASK);
521                i = value_start + value.len();
522                continue;
523            }
524        }
525        let c = line[i..].chars().next().unwrap();
526        out.push(c);
527        i += c.len_utf8();
528    }
529    out
530}
531
532/// Words that start with a known token prefix.
533fn redact_prefixed_tokens(line: &str) -> String {
534    let mut out = String::with_capacity(line.len());
535    let mut word = String::new();
536    let flush = |word: &mut String, out: &mut String| {
537        if !word.is_empty() {
538            // The prefixes are the history scanner's table (`rewrite::secrets`),
539            // so the log and the scanner mask the same shapes.
540            let is_token = crate::domain::rewrite::secrets::token_prefixes()
541                .any(|p| word.starts_with(p) && word.len() >= p.len() + 8);
542            if is_token {
543                out.push_str(MASK);
544            } else {
545                out.push_str(word);
546            }
547            word.clear();
548        }
549    };
550    for c in line.chars() {
551        if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
552            word.push(c);
553        } else {
554            flush(&mut word, &mut out);
555            out.push(c);
556        }
557    }
558    flush(&mut word, &mut out);
559    out
560}
561
562#[cfg(test)]
563mod tests {
564    use super::*;
565
566    #[test]
567    fn credentials_in_urls_are_masked() {
568        assert_eq!(
569            redact("fatal: unable to access 'https://user:hunter2@example.com/r.git/': x"),
570            "fatal: unable to access 'https://***@example.com/r.git/': x"
571        );
572        assert_eq!(
573            redact("remote https://ghp_abcdefghijklmnop@github.com/o/r"),
574            "remote https://***@github.com/o/r"
575        );
576        // No userinfo: untouched.
577        assert_eq!(
578            redact("https://github.com/o/r.git"),
579            "https://github.com/o/r.git"
580        );
581    }
582
583    #[test]
584    fn auth_headers_and_secret_pairs_are_masked() {
585        let out = redact("-c http.extraheader=Authorization: Basic dXNlcjpwYXNz\nnext line");
586        assert!(!out.contains("dXNlcjpwYXNz"), "{out}");
587        assert!(out.ends_with("next line"), "{out}");
588        let out = redact("curl -H 'Authorization: Bearer abcdef123456' x");
589        assert!(!out.contains("abcdef123456"), "{out}");
590        let out = redact("url?access_token=abc123xyz&per_page=5");
591        assert!(
592            !out.contains("abc123xyz") && out.contains("per_page=5"),
593            "{out}"
594        );
595        let out = redact("password = s3cret value");
596        assert!(!out.contains("s3cret"), "{out}");
597        let out = redact("PRIVATE-TOKEN: glpat-xxxxxxxxxxxxxxxxxxxx");
598        assert!(!out.contains("glpat-xxxx"), "{out}");
599    }
600
601    #[test]
602    fn token_shaped_words_are_masked_but_prose_is_not() {
603        let out = redact("pushed with ghp_0123456789abcdefghij to origin");
604        assert_eq!(out, "pushed with *** to origin");
605        let out = redact("key sk-ant-api03-ABCDEFGHIJKLMN end");
606        assert!(!out.contains("ABCDEFGH"), "{out}");
607        // Ordinary text survives, including words that merely contain keys.
608        let plain = "error: failed to push some refs to 'origin' (tokenizer, basic setup)";
609        assert_eq!(redact(plain), plain);
610    }
611
612    #[test]
613    fn a_registered_secret_is_masked_even_without_a_known_prefix() {
614        let secret = "zq81-plain-secret-value-4417";
615        let line = format!("remote: denied for {secret} at host\n");
616        assert!(redact(&line).contains(secret), "not registered yet");
617        redact_register_secret(secret);
618        redact_register_secret(secret);
619        redact_register_secret("abc");
620        assert_eq!(redact(&line), "remote: denied for *** at host\n");
621        // Too short to be a secret: ordinary text stays readable.
622        assert_eq!(redact("abc def"), "abc def");
623    }
624
625    #[test]
626    fn redaction_is_idempotent() {
627        let once = redact("https://u:p@h/x Authorization: Bearer abcdefghijkl token=zzz");
628        assert_eq!(redact(&once), once);
629    }
630
631    #[test]
632    fn a_detail_never_holds_the_secret_it_was_built_from() {
633        let d = ErrorDetail::from_git(
634            &["push", "https://me:topsecret@host/r.git"],
635            Some(128),
636            "fatal: Authentication failed for 'https://me:topsecret@host/r.git/'\n",
637        );
638        let all = format!("{:?}", d);
639        assert!(!all.contains("topsecret"), "{all}");
640        assert_eq!(d.kind(), FailureKind::AuthFailed);
641    }
642
643    #[test]
644    fn stderr_is_cut_to_its_tail() {
645        let long: String = (0..100).map(|i| format!("line {i}\n")).collect();
646        let d = ErrorDetail::from_git(&["fetch"], Some(1), &long);
647        assert!(d.stderr.contains("line 99"));
648        assert!(!d.stderr.contains("line 10\n"));
649        assert!(d.stderr.starts_with("[70 earlier lines omitted]"));
650    }
651
652    #[test]
653    fn git_messages_map_to_a_friendly_kind() {
654        use FailureKind as K;
655        let cases = [
656            (
657                " ! [rejected]        main -> main (non-fast-forward)\nerror: failed to push some refs",
658                K::NonFastForward,
659            ),
660            ("hint: Updates were rejected because the tip of your current branch is behind", K::NonFastForward),
661            ("fatal: Not possible to fast-forward, aborting.", K::NonFastForward),
662            ("remote: Invalid username or password.\nfatal: Authentication failed for 'https://h/r'", K::AuthFailed),
663            ("git@h: Permission denied (publickey).\nfatal: Could not read from remote repository.", K::AuthFailed),
664            ("fatal: could not read Username for 'https://h': terminal prompts disabled", K::AuthFailed),
665            ("CONFLICT (content): Merge conflict in a.txt\nAutomatic merge failed; fix conflicts", K::MergeConflict),
666            ("error: Your local changes to the following files would be overwritten by merge:\n\ta.txt", K::WouldOverwrite),
667            ("fatal: Unable to create '/r/.git/index.lock': File exists.", K::LockExists),
668            ("fatal: unable to access 'https://h/r/': Could not resolve host: h", K::NetworkUnreachable),
669            ("Host key verification failed.\nfatal: Could not read from remote repository.", K::HostKeyUnverified),
670            ("ssh: connect to host h port 22: Network is unreachable", K::NetworkUnreachable),
671            ("something unexpected", K::Other),
672            (HELPER_STDERR, K::CredentialHelperFailed),
673        ];
674        for (stderr, kind) in cases {
675            assert_eq!(FailureKind::classify(stderr), kind, "{stderr}");
676        }
677    }
678
679    #[test]
680    fn libgit2_auth_failures_are_recognized() {
681        let d = ErrorDetail::from_git2("fetch", "Http", "Auth", "authentication required");
682        assert_eq!(d.kind(), FailureKind::AuthFailed);
683    }
684
685    const HELPER_STDERR: &str = "sh: /c/Users/X/.config/my-tool/token.sh: No such file or directory\nremote: Invalid username or token. Password authentication is not supported for Git operations.\nfatal: Authentication failed for 'https://github.com/Poulpi-Lab/GitPoulpi.git/'";
686
687    #[test]
688    fn a_credential_helper_that_cannot_run_is_not_read_as_a_refusal() {
689        use FailureKind as K;
690        let line = K::credential_helper_line(HELPER_STDERR).unwrap();
691        assert_eq!(
692            line,
693            "sh: /c/Users/X/.config/my-tool/token.sh: No such file or directory"
694        );
695        for stderr in [
696            "git: 'credential-foo' is not a git command. See 'git --help'.\nfatal: Authentication failed for 'https://h/r'",
697            "/bin/sh: 1: /home/me/helper.sh: not found\nfatal: could not read Username for 'https://h': terminal prompts disabled",
698            "sh: /usr/bin/git-credential-manager: Permission denied\nfatal: Authentication failed for 'https://h/r'",
699            "fatal: credential helper '/x/y' told us to quit",
700            "'git-credential-foo' is not recognized as an internal or external command,\nfatal: Authentication failed for 'https://h/r'",
701            "error: cannot run git-credential-foo: No such file or directory\nfatal: Authentication failed for 'https://h/r'",
702            "/x/credential-script get: line 1: /x/credential-script: No such file or directory\nfatal: could not read Username for 'http://h': No such device or address",
703        ] {
704            assert_eq!(K::classify(stderr), K::CredentialHelperFailed, "{stderr}");
705            assert!(K::credential_helper_line(stderr).is_some(), "{stderr}");
706        }
707        // A plain refusal, and a bare shell failure without an auth failure
708        // (not provably the helper), keep their readings.
709        let refusal = "fatal: Authentication failed for 'https://h/r'";
710        assert_eq!(K::classify(refusal), K::AuthFailed);
711        let flat = format!("backend error: git fetch --all failed: {HELPER_STDERR}");
712        assert_eq!(K::classify(&flat), K::CredentialHelperFailed);
713        assert_eq!(
714            K::credential_helper_line(&flat).as_deref(),
715            Some("sh: /c/Users/X/.config/my-tool/token.sh: No such file or directory")
716        );
717        assert_eq!(K::credential_helper_line(refusal), None);
718        assert_eq!(
719            K::classify("sh: ./hook.sh: not found"),
720            K::Other,
721            "a bare shell failure is not a helper failure on its own"
722        );
723        assert_eq!(
724            K::classify("ssh: connect to host h port 22: Network is unreachable"),
725            K::NetworkUnreachable
726        );
727    }
728}