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 phrases (lowercase) with which git or libgit2 says that local changes
307/// are in the way of an operation. The daemon's auto-stash reads them to tell
308/// "blocked by local changes" from any other failure; the backend contract
309/// suite checks that both backends' refusals contain one of them.
310pub const LOCAL_CHANGES_NEEDLES: [&str; 8] = [
311    "would be overwritten",
312    "local changes",
313    "prevent checkout",
314    "prevents checkout",
315    "uncommitted changes",
316    "working tree is not clean",
317    "unstaged changes",
318    "cannot pull with rebase",
319];
320
321/// Whether an error message says local changes are in the way (see
322/// [`LOCAL_CHANGES_NEEDLES`]).
323pub fn is_local_changes_message(message: &str) -> bool {
324    let message = message.to_lowercase();
325    LOCAL_CHANGES_NEEDLES.iter().any(|n| message.contains(n))
326}
327
328/// The last `n` lines of `text`, trimmed of surrounding blank lines.
329pub fn tail_lines(text: &str, n: usize) -> String {
330    let lines: Vec<&str> = text.trim().lines().collect();
331    let skip = lines.len().saturating_sub(n);
332    let mut out = lines[skip..].join("\n");
333    if skip > 0 {
334        out.insert_str(0, &format!("[{skip} earlier lines omitted]\n"));
335    }
336    out
337}
338
339const MASK: &str = "***";
340
341/// Keys whose value is a secret when written `key=value` or `key: value`.
342const SECRET_KEYS: &[&str] = &[
343    "password",
344    "passwd",
345    "pwd",
346    "token",
347    "secret",
348    "api_key",
349    "apikey",
350    "api-key",
351    "access_token",
352    "private_token",
353    "private-token",
354    "client_secret",
355    "authorization",
356    "proxy-authorization",
357    "x-api-key",
358];
359
360/// `text` with credentials masked: userinfo in URLs, `Authorization`
361/// style headers, `Bearer`/`Basic` values, token-shaped words and
362/// `password=...` pairs. Idempotent, line structure preserved.
363pub fn redact(text: &str) -> String {
364    let masked = text
365        .split_inclusive('\n')
366        .map(redact_line)
367        .collect::<String>();
368    mask_registered(masked)
369}
370
371/// Secrets this process knows exactly (a token it resolved for a grant),
372/// masked wherever they appear whatever they look like: a token with no
373/// known prefix is invisible to the shape rules above.
374fn registered_secrets() -> &'static std::sync::Mutex<Vec<String>> {
375    static SECRETS: std::sync::OnceLock<std::sync::Mutex<Vec<String>>> = std::sync::OnceLock::new();
376    SECRETS.get_or_init(Default::default)
377}
378
379/// Shorter values would mask ordinary words.
380const MIN_REGISTERED_SECRET: usize = 6;
381
382/// Remembers `secret` for the life of the process: [`redact`] masks every
383/// occurrence of it from now on. A value shorter than six characters is
384/// ignored (it would mask ordinary text); registering twice is harmless.
385pub fn redact_register_secret(secret: &str) {
386    let secret = secret.trim();
387    if secret.len() < MIN_REGISTERED_SECRET {
388        return;
389    }
390    let mut all = registered_secrets()
391        .lock()
392        .unwrap_or_else(|e| e.into_inner());
393    if !all.iter().any(|s| s == secret) {
394        all.push(secret.to_string());
395    }
396}
397
398fn mask_registered(text: String) -> String {
399    let all = registered_secrets()
400        .lock()
401        .unwrap_or_else(|e| e.into_inner());
402    all.iter().fold(text, |text, secret| {
403        if text.contains(secret.as_str()) {
404            text.replace(secret.as_str(), "***")
405        } else {
406            text
407        }
408    })
409}
410
411fn redact_line(line: &str) -> String {
412    let line = redact_urls(line);
413    let line = redact_pairs(&line);
414    let line = redact_bearer(&line);
415    redact_prefixed_tokens(&line)
416}
417
418fn is_word_char(c: char) -> bool {
419    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '~' | '+' | '/' | '=')
420}
421
422/// `scheme://user:secret@host` becomes `scheme://***@host`.
423fn redact_urls(line: &str) -> String {
424    let mut out = String::with_capacity(line.len());
425    let mut rest = line;
426    while let Some(pos) = rest.find("://") {
427        let (head, tail) = rest.split_at(pos + 3);
428        out.push_str(head);
429        let end = tail
430            .find(|c: char| c.is_whitespace() || matches!(c, '/' | '"' | '\'' | '<' | '>'))
431            .unwrap_or(tail.len());
432        let authority = &tail[..end];
433        match authority.rfind('@') {
434            Some(at) if at > 0 => {
435                out.push_str(MASK);
436                out.push_str(&authority[at..]);
437            }
438            _ => out.push_str(authority),
439        }
440        rest = &tail[end..];
441    }
442    out.push_str(rest);
443    out
444}
445
446/// `key=value` / `key: value` for the secret keys (case-insensitive).
447fn redact_pairs(line: &str) -> String {
448    let lower = line.to_lowercase();
449    let mut out = String::with_capacity(line.len());
450    let mut i = 0;
451    let bytes = line.as_bytes();
452    while i < line.len() {
453        let mut matched = None;
454        // Only at a key boundary: start of line or after a non-word char.
455        let boundary = i == 0
456            || !line[..i]
457                .chars()
458                .next_back()
459                .is_some_and(|c| c.is_ascii_alphanumeric() || c == '_');
460        if boundary && line.is_char_boundary(i) {
461            for key in SECRET_KEYS {
462                if lower[i..].starts_with(key) {
463                    let after = i + key.len();
464                    let mut j = after;
465                    while j < bytes.len() && (bytes[j] == b' ' || bytes[j] == b'"') {
466                        j += 1;
467                    }
468                    if j < bytes.len() && (bytes[j] == b'=' || bytes[j] == b':') && j > after - 1 {
469                        // key, optional spaces, separator, optional spaces
470                        let mut k = j + 1;
471                        while k < bytes.len() && bytes[k] == b' ' {
472                            k += 1;
473                        }
474                        // A header value runs to the end of the line; a
475                        // pair's value to whitespace, `&` or a quote.
476                        let header = *key == "authorization" || *key == "proxy-authorization";
477                        let mut end = k;
478                        while end < line.len() {
479                            let c = line[end..].chars().next().unwrap();
480                            let stop = if header {
481                                c == '\n' || c == '\r' || c == '"' || c == '\''
482                            } else {
483                                c.is_whitespace() || matches!(c, '&' | '"' | '\'' | ',' | ';')
484                            };
485                            if stop {
486                                break;
487                            }
488                            end += c.len_utf8();
489                        }
490                        if end > k {
491                            matched = Some((after, j + 1, k, end));
492                        }
493                    }
494                    break;
495                }
496            }
497        }
498        match matched {
499            Some((after, sep_end, value_start, end)) => {
500                out.push_str(&line[i..after]);
501                out.push_str(&line[after..sep_end]);
502                out.push_str(&line[sep_end..value_start]);
503                out.push_str(MASK);
504                i = end;
505            }
506            None => {
507                let c = line[i..].chars().next().unwrap();
508                out.push(c);
509                i += c.len_utf8();
510            }
511        }
512    }
513    out
514}
515
516/// `Bearer abc` and `Basic abc` (any case).
517fn redact_bearer(line: &str) -> String {
518    let lower = line.to_lowercase();
519    let mut out = String::with_capacity(line.len());
520    let mut i = 0;
521    while i < line.len() {
522        let rest = &lower[i..];
523        let scheme = ["bearer ", "basic ", "token "]
524            .into_iter()
525            .find(|s| rest.starts_with(s));
526        let boundary = i == 0
527            || !line[..i]
528                .chars()
529                .next_back()
530                .is_some_and(|c| c.is_ascii_alphanumeric());
531        if let (Some(s), true) = (scheme, boundary) {
532            let value_start = i + s.len();
533            let value: String = line[value_start..]
534                .chars()
535                .take_while(|c| is_word_char(*c))
536                .collect();
537            // "basic " / "token " are ordinary words: only mask a value that
538            // looks like a credential (long enough, no plain-word look).
539            let credential = value.len() >= 12 || (s.starts_with("bearer") && value.len() >= 6);
540            if credential && !value.contains(MASK) {
541                out.push_str(&line[i..value_start]);
542                out.push_str(MASK);
543                i = value_start + value.len();
544                continue;
545            }
546        }
547        let c = line[i..].chars().next().unwrap();
548        out.push(c);
549        i += c.len_utf8();
550    }
551    out
552}
553
554/// Words that start with a known token prefix.
555fn redact_prefixed_tokens(line: &str) -> String {
556    let mut out = String::with_capacity(line.len());
557    let mut word = String::new();
558    let flush = |word: &mut String, out: &mut String| {
559        if !word.is_empty() {
560            // The prefixes are the history scanner's table (`rewrite::secrets`),
561            // so the log and the scanner mask the same shapes.
562            let is_token = crate::domain::rewrite::secrets::token_prefixes()
563                .any(|p| word.starts_with(p) && word.len() >= p.len() + 8);
564            if is_token {
565                out.push_str(MASK);
566            } else {
567                out.push_str(word);
568            }
569            word.clear();
570        }
571    };
572    for c in line.chars() {
573        if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
574            word.push(c);
575        } else {
576            flush(&mut word, &mut out);
577            out.push(c);
578        }
579    }
580    flush(&mut word, &mut out);
581    out
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587
588    #[test]
589    fn credentials_in_urls_are_masked() {
590        assert_eq!(
591            redact("fatal: unable to access 'https://user:hunter2@example.com/r.git/': x"),
592            "fatal: unable to access 'https://***@example.com/r.git/': x"
593        );
594        assert_eq!(
595            redact("remote https://ghp_abcdefghijklmnop@github.com/o/r"),
596            "remote https://***@github.com/o/r"
597        );
598        // No userinfo: untouched.
599        assert_eq!(
600            redact("https://github.com/o/r.git"),
601            "https://github.com/o/r.git"
602        );
603    }
604
605    #[test]
606    fn auth_headers_and_secret_pairs_are_masked() {
607        let out = redact("-c http.extraheader=Authorization: Basic dXNlcjpwYXNz\nnext line");
608        assert!(!out.contains("dXNlcjpwYXNz"), "{out}");
609        assert!(out.ends_with("next line"), "{out}");
610        let out = redact("curl -H 'Authorization: Bearer abcdef123456' x");
611        assert!(!out.contains("abcdef123456"), "{out}");
612        let out = redact("url?access_token=abc123xyz&per_page=5");
613        assert!(
614            !out.contains("abc123xyz") && out.contains("per_page=5"),
615            "{out}"
616        );
617        let out = redact("password = s3cret value");
618        assert!(!out.contains("s3cret"), "{out}");
619        let out = redact("PRIVATE-TOKEN: glpat-xxxxxxxxxxxxxxxxxxxx");
620        assert!(!out.contains("glpat-xxxx"), "{out}");
621    }
622
623    #[test]
624    fn token_shaped_words_are_masked_but_prose_is_not() {
625        let out = redact("pushed with ghp_0123456789abcdefghij to origin");
626        assert_eq!(out, "pushed with *** to origin");
627        let out = redact("key sk-ant-api03-ABCDEFGHIJKLMN end");
628        assert!(!out.contains("ABCDEFGH"), "{out}");
629        // Ordinary text survives, including words that merely contain keys.
630        let plain = "error: failed to push some refs to 'origin' (tokenizer, basic setup)";
631        assert_eq!(redact(plain), plain);
632    }
633
634    #[test]
635    fn a_registered_secret_is_masked_even_without_a_known_prefix() {
636        let secret = "zq81-plain-secret-value-4417";
637        let line = format!("remote: denied for {secret} at host\n");
638        assert!(redact(&line).contains(secret), "not registered yet");
639        redact_register_secret(secret);
640        redact_register_secret(secret);
641        redact_register_secret("abc");
642        assert_eq!(redact(&line), "remote: denied for *** at host\n");
643        // Too short to be a secret: ordinary text stays readable.
644        assert_eq!(redact("abc def"), "abc def");
645    }
646
647    #[test]
648    fn redaction_is_idempotent() {
649        let once = redact("https://u:p@h/x Authorization: Bearer abcdefghijkl token=zzz");
650        assert_eq!(redact(&once), once);
651    }
652
653    #[test]
654    fn a_detail_never_holds_the_secret_it_was_built_from() {
655        let d = ErrorDetail::from_git(
656            &["push", "https://me:topsecret@host/r.git"],
657            Some(128),
658            "fatal: Authentication failed for 'https://me:topsecret@host/r.git/'\n",
659        );
660        let all = format!("{:?}", d);
661        assert!(!all.contains("topsecret"), "{all}");
662        assert_eq!(d.kind(), FailureKind::AuthFailed);
663    }
664
665    #[test]
666    fn stderr_is_cut_to_its_tail() {
667        let long: String = (0..100).map(|i| format!("line {i}\n")).collect();
668        let d = ErrorDetail::from_git(&["fetch"], Some(1), &long);
669        assert!(d.stderr.contains("line 99"));
670        assert!(!d.stderr.contains("line 10\n"));
671        assert!(d.stderr.starts_with("[70 earlier lines omitted]"));
672    }
673
674    #[test]
675    fn git_messages_map_to_a_friendly_kind() {
676        use FailureKind as K;
677        let cases = [
678            (
679                " ! [rejected]        main -> main (non-fast-forward)\nerror: failed to push some refs",
680                K::NonFastForward,
681            ),
682            ("hint: Updates were rejected because the tip of your current branch is behind", K::NonFastForward),
683            ("fatal: Not possible to fast-forward, aborting.", K::NonFastForward),
684            ("remote: Invalid username or password.\nfatal: Authentication failed for 'https://h/r'", K::AuthFailed),
685            ("git@h: Permission denied (publickey).\nfatal: Could not read from remote repository.", K::AuthFailed),
686            ("fatal: could not read Username for 'https://h': terminal prompts disabled", K::AuthFailed),
687            ("CONFLICT (content): Merge conflict in a.txt\nAutomatic merge failed; fix conflicts", K::MergeConflict),
688            ("error: Your local changes to the following files would be overwritten by merge:\n\ta.txt", K::WouldOverwrite),
689            ("fatal: Unable to create '/r/.git/index.lock': File exists.", K::LockExists),
690            ("fatal: unable to access 'https://h/r/': Could not resolve host: h", K::NetworkUnreachable),
691            ("Host key verification failed.\nfatal: Could not read from remote repository.", K::HostKeyUnverified),
692            ("ssh: connect to host h port 22: Network is unreachable", K::NetworkUnreachable),
693            ("something unexpected", K::Other),
694            (HELPER_STDERR, K::CredentialHelperFailed),
695        ];
696        for (stderr, kind) in cases {
697            assert_eq!(FailureKind::classify(stderr), kind, "{stderr}");
698        }
699    }
700
701    #[test]
702    fn libgit2_auth_failures_are_recognized() {
703        let d = ErrorDetail::from_git2("fetch", "Http", "Auth", "authentication required");
704        assert_eq!(d.kind(), FailureKind::AuthFailed);
705    }
706
707    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/'";
708
709    #[test]
710    fn a_credential_helper_that_cannot_run_is_not_read_as_a_refusal() {
711        use FailureKind as K;
712        let line = K::credential_helper_line(HELPER_STDERR).unwrap();
713        assert_eq!(
714            line,
715            "sh: /c/Users/X/.config/my-tool/token.sh: No such file or directory"
716        );
717        for stderr in [
718            "git: 'credential-foo' is not a git command. See 'git --help'.\nfatal: Authentication failed for 'https://h/r'",
719            "/bin/sh: 1: /home/me/helper.sh: not found\nfatal: could not read Username for 'https://h': terminal prompts disabled",
720            "sh: /usr/bin/git-credential-manager: Permission denied\nfatal: Authentication failed for 'https://h/r'",
721            "fatal: credential helper '/x/y' told us to quit",
722            "'git-credential-foo' is not recognized as an internal or external command,\nfatal: Authentication failed for 'https://h/r'",
723            "error: cannot run git-credential-foo: No such file or directory\nfatal: Authentication failed for 'https://h/r'",
724            "/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",
725        ] {
726            assert_eq!(K::classify(stderr), K::CredentialHelperFailed, "{stderr}");
727            assert!(K::credential_helper_line(stderr).is_some(), "{stderr}");
728        }
729        // A plain refusal, and a bare shell failure without an auth failure
730        // (not provably the helper), keep their readings.
731        let refusal = "fatal: Authentication failed for 'https://h/r'";
732        assert_eq!(K::classify(refusal), K::AuthFailed);
733        let flat = format!("backend error: git fetch --all failed: {HELPER_STDERR}");
734        assert_eq!(K::classify(&flat), K::CredentialHelperFailed);
735        assert_eq!(
736            K::credential_helper_line(&flat).as_deref(),
737            Some("sh: /c/Users/X/.config/my-tool/token.sh: No such file or directory")
738        );
739        assert_eq!(K::credential_helper_line(refusal), None);
740        assert_eq!(
741            K::classify("sh: ./hook.sh: not found"),
742            K::Other,
743            "a bare shell failure is not a helper failure on its own"
744        );
745        assert_eq!(
746            K::classify("ssh: connect to host h port 22: Network is unreachable"),
747            K::NetworkUnreachable
748        );
749    }
750}