use std::collections::VecDeque;
use std::sync::Mutex;
const CAPACITY: usize = 200;
static LOG: Mutex<VecDeque<Entry>> = Mutex::new(VecDeque::new());
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub args: String,
pub code: Option<i32>,
pub ms: u128,
pub at: String,
}
pub fn record(args: &[&str], code: Option<i32>, ms: u128) {
let entry = Entry {
args: display_args(args),
code,
ms,
at: chrono::Local::now().format("%H:%M:%S").to_string(),
};
let mut log = LOG.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
log.push_front(entry);
log.truncate(CAPACITY);
}
pub fn entries() -> Vec<Entry> {
let log = LOG.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
log.iter().cloned().collect()
}
fn display_args(args: &[&str]) -> String {
let mut parts = Vec::with_capacity(args.len());
let mut after_c = false;
for arg in args {
let shown = if after_c && arg.to_ascii_lowercase().contains("extraheader") {
match arg.split_once('=') {
Some((key, _)) => format!("{key}=***"),
None => (*arg).to_string(),
}
} else {
(*arg).to_string()
};
after_c = *arg == "-c";
parts.push(quote(&shown));
}
mask(&parts.join(" "))
}
fn quote(arg: &str) -> String {
if arg.is_empty() || arg.contains(char::is_whitespace) || arg.contains('"') {
format!("\"{}\"", arg.replace('"', "\\\""))
} else {
arg.to_string()
}
}
pub fn mask(text: &str) -> String {
mask_tokens(&mask_userinfo(text))
}
fn mask_userinfo(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(at) = rest.find("://") {
let start = at + 3;
out.push_str(&rest[..start]);
let tail = &rest[start..];
let end = tail
.find(|c: char| c == '/' || c == '?' || c == '#' || c.is_whitespace())
.unwrap_or(tail.len());
let authority = &tail[..end];
match authority.rfind('@') {
Some(sign) if sign > 0 => {
out.push_str("***");
out.push_str(&authority[sign..]);
}
_ => out.push_str(authority),
}
rest = &tail[end..];
}
out.push_str(rest);
out
}
fn mask_tokens(text: &str) -> String {
const PREFIXES: [(&str, bool); 7] = [
("github_pat_", true),
("ghp_", false),
("gho_", false),
("ghs_", false),
("ghu_", false),
("ghr_", false),
("x-access-token:", true),
];
let bytes = text.as_bytes();
let mut out = String::with_capacity(text.len());
let mut i = 0;
'scan: while i < bytes.len() {
for (prefix, underscore) in PREFIXES {
if text[i..].starts_with(prefix) {
let value_start = i + prefix.len();
let mut j = value_start;
while j < bytes.len() {
let b = bytes[j];
let ok = if prefix.starts_with("x-access") {
!(b.is_ascii_whitespace() || b == b'@' || b == b'/' || b == b'"')
} else {
b.is_ascii_alphanumeric() || (underscore && b == b'_')
};
if !ok {
break;
}
j += 1;
}
if j > value_start {
out.push_str("***");
i = j;
continue 'scan;
}
}
}
let ch = text[i..].chars().next().unwrap_or_default();
out.push(ch);
i += ch.len_utf8().max(1);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn masks_secrets() {
let cases = [
(
"push https://user:pa55@github.com/o/r.git main",
"push https://***@github.com/o/r.git main",
),
(
"https://ghp_abc123@github.com/x",
"https://***@github.com/x",
),
("token ghp_ABCdef0123456789 end", "token *** end"),
("gho_x ghs_y ghu_z ghr_w", "*** *** *** ***"),
("github_pat_11AB_cd99 rest", "*** rest"),
("x-access-token:abc.def@github.com", "***@github.com"),
("ssh://git@host/repo", "ssh://***@host/repo"),
("https://github.com/o/r.git", "https://github.com/o/r.git"),
("ghp_ alone", "ghp_ alone"),
("plain ünïcode text", "plain ünïcode text"),
("", ""),
];
for (input, expected) in cases {
assert_eq!(mask(input), expected, "{input}");
}
}
#[test]
fn display_masks_extraheader_and_quotes() {
let shown = display_args(&[
"-c",
"http.extraheader=AUTHORIZATION: basic c2VjcmV0",
"commit",
"-m",
"two words",
"",
]);
assert_eq!(
shown,
"-c http.extraheader=*** commit -m \"two words\" \"\""
);
let shown = display_args(&["-c", "http.https://x.com/.extraHeader=Bearer t", "fetch"]);
assert_eq!(shown, "-c http.https://x.com/.extraHeader=*** fetch");
}
#[test]
fn records_newest_first_and_masked() {
record(
&["remote", "add", "o", "https://u:secret-zz91@h/r"],
Some(0),
3,
);
record(&["status", "--probe-zz91"], Some(1), 4);
let all = entries();
let first = all
.iter()
.position(|e| e.args == "status --probe-zz91")
.unwrap();
let second = all
.iter()
.position(|e| e.args.contains("https://***@h/r"))
.unwrap();
assert!(first < second);
assert_eq!(all[first].code, Some(1));
assert!(!all.iter().any(|e| e.args.contains("secret-zz91")));
assert!(all.len() <= CAPACITY);
}
}