fix(credentials): harden masked debug output (#2114)

Signed-off-by: heihutu <30542132+heihutu@users.noreply.github.com>
Co-authored-by: houseme <housemecn@gmail.com>
Co-authored-by: heihutu <30542132+heihutu@users.noreply.github.com>
This commit is contained in:
安正超
2026-03-11 15:40:37 +08:00
committed by GitHub
parent 7d7e0b2654
commit e1f24f764d
+11 -3
View File
@@ -233,15 +233,18 @@ impl<'a> fmt::Debug for Masked<'a> {
match self.0 { match self.0 {
None => Ok(()), None => Ok(()),
Some(s) => { Some(s) => {
let len = s.len(); let len = s.chars().count();
if len == 0 { if len == 0 {
Ok(()) Ok(())
} else if len == 1 { } else if len == 1 {
write!(f, "***") write!(f, "***")
} else if len == 2 { } else if len == 2 {
write!(f, "{}***|{}", &s[0..1], len) let first = s.chars().next().ok_or(fmt::Error)?;
write!(f, "{}***|{}", first, len)
} else { } else {
write!(f, "{}***{}|{}", &s[0..1], &s[len - 1..], len) let first = s.chars().next().ok_or(fmt::Error)?;
let last = s.chars().last().ok_or(fmt::Error)?;
write!(f, "{}***{}|{}", first, last, len)
} }
} }
} }
@@ -482,5 +485,10 @@ mod tests {
// Test longer string // Test longer string
assert_eq!(format!("{:?}", Masked(Some("secretpassword"))), "s***d|14"); assert_eq!(format!("{:?}", Masked(Some("secretpassword"))), "s***d|14");
// Test Unicode input should not panic and should keep character boundary
assert_eq!(format!("{:?}", Masked(Some(""))), "***");
assert_eq!(format!("{:?}", Masked(Some("中文"))), "中***|2");
assert_eq!(format!("{:?}", Masked(Some("中文测试"))), "中***试|4");
} }
} }