use serde::{Deserialize, Serialize};
use crate::domain::rewrite::secrets::{preview, scan_text};
pub const DEFAULT_SENSITIVE_PATTERNS: &[&str] = &[
".env",
".env.*",
"!.env.example",
"!.env.sample",
"!.env.template",
"*.pem",
"*.key",
"id_rsa*",
"id_ed25519*",
"id_ecdsa*",
"*.p12",
"*.pfx",
"*.jks",
"*.keystore",
"*.crt",
"*.cer",
"*.der",
"*.kdbx",
];
pub fn default_sensitive_patterns() -> Vec<String> {
DEFAULT_SENSITIVE_PATTERNS
.iter()
.map(|p| (*p).to_string())
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Reason {
Pattern(String),
Secret { rule: String, preview: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Sensitive {
pub path: String,
pub reason: Reason,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub line: Option<u32>,
}
impl Sensitive {
pub fn describe(&self) -> String {
match &self.reason {
Reason::Pattern(p) => format!("matches {p}"),
Reason::Secret { rule, preview } => format!("secret: {rule} ({preview})"),
}
}
}
pub fn summary(files: &[Sensitive]) -> String {
let mut paths: Vec<&str> = Vec::new();
for f in files {
if !paths.contains(&f.path.as_str()) {
paths.push(&f.path);
}
}
let shown = paths.iter().take(5).copied().collect::<Vec<_>>().join(", ");
if paths.len() > 5 {
format!("{shown}, and {} more", paths.len() - 5)
} else {
shown
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Redaction {
pub rule: String,
pub preview: String,
}
pub fn matching_pattern<'a, S: AsRef<str>>(path: &str, patterns: &'a [S]) -> Option<&'a str> {
let path = path.replace('\\', "/");
let path = path.trim_start_matches("./");
let mut hit: Option<&'a str> = None;
for raw in patterns {
let raw = raw.as_ref().trim();
if raw.is_empty() || raw.starts_with('#') {
continue;
}
let (negated, body) = match raw.strip_prefix('!') {
Some(rest) => (true, rest.trim()),
None => (false, raw),
};
if body.is_empty() || !pattern_matches(body, path) {
continue;
}
hit = if negated { None } else { Some(raw) };
}
hit
}
fn pattern_matches(pattern: &str, path: &str) -> bool {
let pattern = pattern.trim_end_matches('/');
let anchored = pattern.starts_with('/');
let pattern = pattern.trim_start_matches('/');
if !anchored && !pattern.contains('/') {
let name = path.rsplit('/').next().unwrap_or(path);
return glob(pattern.as_bytes(), name.as_bytes());
}
glob(pattern.as_bytes(), path.as_bytes())
}
fn glob(pat: &[u8], text: &[u8]) -> bool {
match pat.first() {
None => text.is_empty(),
Some(b'*') => {
let double = pat.get(1) == Some(&b'*');
let rest = &pat[if double { 2 } else { 1 }..];
if double && rest.first() == Some(&b'/') && glob(&rest[1..], text) {
return true;
}
let mut i = 0;
loop {
if glob(rest, &text[i..]) {
return true;
}
if i == text.len() || (!double && text[i] == b'/') {
return false;
}
i += 1;
}
}
Some(b'?') => match text.first() {
Some(c) if *c != b'/' => glob(&pat[1..], &text[1..]),
_ => false,
},
Some(p) => match text.first() {
Some(c) if c.eq_ignore_ascii_case(p) => glob(&pat[1..], &text[1..]),
_ => false,
},
}
}
pub fn classify<S: AsRef<str>>(
path: &str,
content: Option<&[u8]>,
patterns: &[S],
) -> Vec<Sensitive> {
let mut out = Vec::new();
if let Some(p) = matching_pattern(path, patterns) {
out.push(Sensitive {
path: path.to_string(),
reason: Reason::Pattern(p.to_string()),
line: None,
});
}
if let Some(bytes) = content {
let mut seen: Vec<(String, String)> = Vec::new();
for m in scan_text(bytes, path) {
let key = (m.rule.to_string(), preview(m.rule, &m.value));
if seen.contains(&key) {
continue;
}
seen.push(key.clone());
out.push(Sensitive {
path: path.to_string(),
reason: Reason::Secret {
rule: key.0,
preview: key.1,
},
line: Some(line_of(bytes, m.offset)),
});
}
}
out
}
fn line_of(text: &[u8], offset: usize) -> u32 {
let end = offset.min(text.len());
let newlines = text[..end].iter().filter(|b| **b == b'\n').count();
u32::try_from(newlines + 1).unwrap_or(u32::MAX)
}
pub fn redact(text: &str) -> (String, Vec<Redaction>) {
redact_in(text, "")
}
pub fn redact_in(text: &str, path: &str) -> (String, Vec<Redaction>) {
let bytes = text.as_bytes();
let found = scan_text(bytes, path);
if found.is_empty() {
return (text.to_string(), Vec::new());
}
let mut out = Vec::with_capacity(bytes.len());
let mut at = 0usize;
let mut redactions = Vec::new();
for m in found {
let end = m.offset + m.value.len();
if m.offset < at || end > bytes.len() {
continue;
}
out.extend_from_slice(&bytes[at..m.offset]);
out.extend_from_slice(format!("[REDACTED:{}]", m.rule).as_bytes());
redactions.push(Redaction {
rule: m.rule.to_string(),
preview: preview(m.rule, &m.value),
});
at = end;
}
out.extend_from_slice(&bytes[at..]);
(String::from_utf8_lossy(&out).into_owned(), redactions)
}
#[cfg(test)]
mod tests;