1use serde::{Deserialize, Serialize};
14
15pub const STDERR_TAIL_LINES: usize = 30;
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Git2Detail {
21 pub class: String,
23 pub code: String,
25 pub message: String,
26}
27
28#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
30pub struct ErrorDetail {
31 pub operation: String,
34 #[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 #[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 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 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 pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
82 self.operation = operation.into();
83 self
84 }
85
86 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
125#[serde(rename_all = "snake_case")]
126pub enum FailureKind {
127 NonFastForward,
129 AuthFailed,
131 CredentialHelperFailed,
136 MergeConflict,
138 WouldOverwrite,
140 HostKeyUnverified,
143 NetworkUnreachable,
145 LockExists,
147 LocalChangesBlockAbort,
151 Other,
152}
153
154impl FailureKind {
155 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 pub fn credential_helper_line(stderr: &str) -> Option<String> {
243 credential_helper_line(stderr).map(|(line, _)| line.trim().to_string())
244 }
245}
246
247fn credential_helper_line(stderr: &str) -> Option<(&str, bool)> {
259 for line in stderr.lines() {
260 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 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
306pub 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
319const 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
338pub 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
349fn 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
357const MIN_REGISTERED_SECRET: usize = 6;
359
360pub 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
400fn 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
424fn 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 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 let mut k = j + 1;
449 while k < bytes.len() && bytes[k] == b' ' {
450 k += 1;
451 }
452 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
494fn 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 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
532fn 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 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 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 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 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 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}