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 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
321pub 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
328pub 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
341const 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
360pub 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
371fn 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
379const MIN_REGISTERED_SECRET: usize = 6;
381
382pub 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
422fn 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
446fn 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 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 let mut k = j + 1;
471 while k < bytes.len() && bytes[k] == b' ' {
472 k += 1;
473 }
474 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
516fn 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 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
554fn 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 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 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 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 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 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}