use std::path::Path;
use std::sync::LazyLock;
use crate::env::{Env, Os};
use crate::secrets::classify::{find_tokens, is_high_entropy, is_sensitive_key};
use crate::secrets::scanner::SecretMemory;
pub const MASK: &str = "***";
pub const HOME_PLACEHOLDER: &str = "<SURJECTION_HOME>";
const MIN_ENV_VALUE_LEN: usize = 8;
const MIN_RANDOM_WORD_LEN: usize = 20;
static MEMORY: LazyLock<Option<SecretMemory>> = LazyLock::new(|| SecretMemory::new().ok());
fn memory() -> Option<&'static SecretMemory> {
MEMORY.as_ref()
}
pub fn remember(value: &str) {
if let Some(memory) = memory() {
memory.record_here(value);
}
}
#[derive(Debug, Clone)]
pub struct Redactor {
roots: Vec<(String, &'static str)>,
fold_case: bool,
values: Vec<String>,
}
impl Redactor {
pub fn new(env: &Env, surjection_home: &Path) -> Self {
let mut roots = Vec::new();
for (root, placeholder) in [(surjection_home, HOME_PLACEHOLDER), (env.home(), "~")] {
let native = root.to_string_lossy().into_owned();
let native = native.trim_end_matches(['/', '\\']).to_owned();
if native.is_empty() {
continue;
}
let forward = native.replace('\\', "/");
let doubled = native.replace('\\', "\\\\");
for form in [doubled, native, forward] {
if !roots.iter().any(|(known, _)| *known == form) {
roots.push((form, placeholder));
}
}
}
let mut values: Vec<String> = env
.vars()
.filter(|(name, _)| is_sensitive_key(name))
.filter_map(|(_, value)| value.to_str())
.map(str::trim)
.filter(|value| value.len() >= MIN_ENV_VALUE_LEN)
.map(str::to_owned)
.collect();
values.sort_by_key(|value| std::cmp::Reverse(value.len()));
values.dedup();
Self {
roots,
fold_case: env.os() == Os::Windows,
values,
}
}
pub fn redact(&self, text: &str) -> String {
let mut out = text.to_owned();
for value in &self.values {
out = out.replace(value.as_str(), MASK);
}
out = mask_remembered(&out);
out = redact_urls(&out);
for (form, placeholder) in &self.roots {
out = replace_root(&out, form, placeholder, self.fold_case);
}
out = mask_tokens(&out);
mask_random_words(&out)
}
}
fn mask_remembered(text: &str) -> String {
let Some(memory) = memory() else {
return text.to_owned();
};
if memory.is_empty() {
return text.to_owned();
}
let mut out = text.to_owned();
while let Some(range) = memory.find(out.as_bytes()) {
if !out.is_char_boundary(range.start) || !out.is_char_boundary(range.end) {
break;
}
out.replace_range(range, MASK);
}
out
}
fn redact_urls(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(sep) = rest.find("://") {
let (head, tail) = rest.split_at(sep + 3);
out.push_str(head);
let end = tail
.find(|c: char| c.is_whitespace() || "\"'<>`".contains(c))
.unwrap_or(tail.len());
let (url, after) = tail.split_at(end);
let authority_end = url.find(['/', '?', '#']).unwrap_or(url.len());
let (authority, path) = url.split_at(authority_end);
match authority.rfind('@') {
Some(at) => {
out.push_str(MASK);
out.push_str(&authority[at..]);
}
None => out.push_str(authority),
}
match path.find('?') {
Some(query) => {
out.push_str(&path[..query]);
out.push('?');
out.push_str(MASK);
if let Some(fragment) = path[query..].find('#') {
out.push_str(&path[query + fragment..]);
}
}
None => out.push_str(path),
}
rest = after;
}
out.push_str(rest);
out
}
fn replace_root(text: &str, form: &str, placeholder: &str, fold_case: bool) -> String {
let bytes = text.as_bytes();
let needle = form.as_bytes();
let mut out = String::with_capacity(text.len());
let mut copied = 0;
let mut i = 0;
while i + needle.len() <= bytes.len() {
let candidate = &bytes[i..i + needle.len()];
let matches = if fold_case {
candidate.eq_ignore_ascii_case(needle)
} else {
candidate == needle
};
let next = bytes.get(i + needle.len()).copied();
let whole = !next.is_some_and(|b| b.is_ascii_alphanumeric() || b"_-.".contains(&b));
if matches && whole && text.is_char_boundary(i) {
out.push_str(&text[copied..i]);
out.push_str(placeholder);
i += needle.len();
copied = i;
} else {
i += 1;
}
}
out.push_str(&text[copied..]);
out
}
fn mask_tokens(text: &str) -> String {
let mut out = text.to_owned();
for hit in find_tokens(text).into_iter().rev() {
out.replace_range(hit.range, MASK);
}
out
}
fn is_word_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b"_-+".contains(&b)
}
fn mask_random_words(text: &str) -> String {
let bytes = text.as_bytes();
let mut out = String::with_capacity(text.len());
let mut copied = 0;
let mut i = 0;
while i < bytes.len() {
if !is_word_byte(bytes[i]) {
i += 1;
continue;
}
let start = i;
while i < bytes.len() && is_word_byte(bytes[i]) {
i += 1;
}
let word = &text[start..i];
if looks_random(word) {
out.push_str(&text[copied..start]);
out.push_str(MASK);
copied = i;
}
}
out.push_str(&text[copied..]);
out
}
fn looks_random(word: &str) -> bool {
word.len() >= MIN_RANDOM_WORD_LEN
&& word.bytes().any(|b| b.is_ascii_digit())
&& word.bytes().any(|b| b.is_ascii_alphabetic())
&& !is_ulid(word)
&& is_high_entropy(word)
}
fn is_ulid(word: &str) -> bool {
word.len() == 26
&& word
.bytes()
.all(|b| b.is_ascii_digit() || (b.is_ascii_uppercase() && !b"ILOU".contains(&b)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn url_userinfo_and_query_are_masked() {
assert_eq!(
redact_urls("got https://me:pw@example.com/a/b?token=x&q=y#top end"),
"got https://***@example.com/a/b?***#top end"
);
assert_eq!(
redact_urls("https://example.com/a"),
"https://example.com/a"
);
}
#[test]
fn roots_match_whole_folders_only() {
assert_eq!(
replace_root("C:\\Users\\me\\x", "C:\\Users\\me", "~", true),
"~\\x"
);
assert_eq!(
replace_root("C:\\Users\\me2\\x", "C:\\Users\\me", "~", true),
"C:\\Users\\me2\\x"
);
assert_eq!(
replace_root("c:/users/ME/x", "C:/Users/me", "~", true),
"~/x"
);
assert_eq!(
replace_root("/home/ME/x", "/home/me", "~", false),
"/home/ME/x"
);
}
#[test]
fn random_words_are_masked_but_ulids_and_codes_stay() {
assert_eq!(mask_random_words("k=Zx81Qa9vLr02mWq7TbYc"), "k=***");
assert_eq!(
mask_random_words("id=01JDKQ7Z8M3N4P5Q6R7S8T9V0W code=scanner_download_failed"),
"id=01JDKQ7Z8M3N4P5Q6R7S8T9V0W code=scanner_download_failed"
);
}
}