1use serde::{Deserialize, Serialize};
15
16use crate::domain::rewrite::secrets::{preview, scan_text};
17
18pub const DEFAULT_SENSITIVE_PATTERNS: &[&str] = &[
22 ".env",
23 ".env.*",
24 "!.env.example",
25 "!.env.sample",
26 "!.env.template",
27 "*.pem",
28 "*.key",
29 "id_rsa*",
30 "id_ed25519*",
31 "id_ecdsa*",
32 "*.p12",
33 "*.pfx",
34 "*.jks",
35 "*.keystore",
36 "*.crt",
37 "*.cer",
38 "*.der",
39 "*.kdbx",
40];
41
42pub fn default_sensitive_patterns() -> Vec<String> {
44 DEFAULT_SENSITIVE_PATTERNS
45 .iter()
46 .map(|p| (*p).to_string())
47 .collect()
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub enum Reason {
53 Pattern(String),
55 Secret { rule: String, preview: String },
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct Sensitive {
63 pub path: String,
64 pub reason: Reason,
65 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub line: Option<u32>,
70}
71
72impl Sensitive {
73 pub fn describe(&self) -> String {
76 match &self.reason {
77 Reason::Pattern(p) => format!("matches {p}"),
78 Reason::Secret { rule, preview } => format!("secret: {rule} ({preview})"),
79 }
80 }
81}
82
83pub fn summary(files: &[Sensitive]) -> String {
85 let mut paths: Vec<&str> = Vec::new();
86 for f in files {
87 if !paths.contains(&f.path.as_str()) {
88 paths.push(&f.path);
89 }
90 }
91 let shown = paths.iter().take(5).copied().collect::<Vec<_>>().join(", ");
92 if paths.len() > 5 {
93 format!("{shown}, and {} more", paths.len() - 5)
94 } else {
95 shown
96 }
97}
98
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101pub struct Redaction {
102 pub rule: String,
103 pub preview: String,
104}
105
106pub fn matching_pattern<'a, S: AsRef<str>>(path: &str, patterns: &'a [S]) -> Option<&'a str> {
112 let path = path.replace('\\', "/");
113 let path = path.trim_start_matches("./");
114 let mut hit: Option<&'a str> = None;
115 for raw in patterns {
116 let raw = raw.as_ref().trim();
117 if raw.is_empty() || raw.starts_with('#') {
118 continue;
119 }
120 let (negated, body) = match raw.strip_prefix('!') {
121 Some(rest) => (true, rest.trim()),
122 None => (false, raw),
123 };
124 if body.is_empty() || !pattern_matches(body, path) {
125 continue;
126 }
127 hit = if negated { None } else { Some(raw) };
128 }
129 hit
130}
131
132fn pattern_matches(pattern: &str, path: &str) -> bool {
133 let pattern = pattern.trim_end_matches('/');
134 let anchored = pattern.starts_with('/');
135 let pattern = pattern.trim_start_matches('/');
136 if !anchored && !pattern.contains('/') {
137 let name = path.rsplit('/').next().unwrap_or(path);
138 return glob(pattern.as_bytes(), name.as_bytes());
139 }
140 glob(pattern.as_bytes(), path.as_bytes())
141}
142
143fn glob(pat: &[u8], text: &[u8]) -> bool {
145 match pat.first() {
146 None => text.is_empty(),
147 Some(b'*') => {
148 let double = pat.get(1) == Some(&b'*');
149 let rest = &pat[if double { 2 } else { 1 }..];
150 if double && rest.first() == Some(&b'/') && glob(&rest[1..], text) {
152 return true;
153 }
154 let mut i = 0;
155 loop {
156 if glob(rest, &text[i..]) {
157 return true;
158 }
159 if i == text.len() || (!double && text[i] == b'/') {
160 return false;
161 }
162 i += 1;
163 }
164 }
165 Some(b'?') => match text.first() {
166 Some(c) if *c != b'/' => glob(&pat[1..], &text[1..]),
167 _ => false,
168 },
169 Some(p) => match text.first() {
170 Some(c) if c.eq_ignore_ascii_case(p) => glob(&pat[1..], &text[1..]),
171 _ => false,
172 },
173 }
174}
175
176pub fn classify<S: AsRef<str>>(
180 path: &str,
181 content: Option<&[u8]>,
182 patterns: &[S],
183) -> Vec<Sensitive> {
184 let mut out = Vec::new();
185 if let Some(p) = matching_pattern(path, patterns) {
186 out.push(Sensitive {
187 path: path.to_string(),
188 reason: Reason::Pattern(p.to_string()),
189 line: None,
190 });
191 }
192 if let Some(bytes) = content {
193 let mut seen: Vec<(String, String)> = Vec::new();
194 for m in scan_text(bytes, path) {
195 let key = (m.rule.to_string(), preview(m.rule, &m.value));
196 if seen.contains(&key) {
197 continue;
198 }
199 seen.push(key.clone());
200 out.push(Sensitive {
201 path: path.to_string(),
202 reason: Reason::Secret {
203 rule: key.0,
204 preview: key.1,
205 },
206 line: Some(line_of(bytes, m.offset)),
207 });
208 }
209 }
210 out
211}
212
213fn line_of(text: &[u8], offset: usize) -> u32 {
215 let end = offset.min(text.len());
216 let newlines = text[..end].iter().filter(|b| **b == b'\n').count();
217 u32::try_from(newlines + 1).unwrap_or(u32::MAX)
218}
219
220pub fn redact(text: &str) -> (String, Vec<Redaction>) {
223 redact_in(text, "")
224}
225
226pub fn redact_in(text: &str, path: &str) -> (String, Vec<Redaction>) {
229 let bytes = text.as_bytes();
230 let found = scan_text(bytes, path);
231 if found.is_empty() {
232 return (text.to_string(), Vec::new());
233 }
234 let mut out = Vec::with_capacity(bytes.len());
235 let mut at = 0usize;
236 let mut redactions = Vec::new();
237 for m in found {
238 let end = m.offset + m.value.len();
239 if m.offset < at || end > bytes.len() {
240 continue;
241 }
242 out.extend_from_slice(&bytes[at..m.offset]);
243 out.extend_from_slice(format!("[REDACTED:{}]", m.rule).as_bytes());
244 redactions.push(Redaction {
245 rule: m.rule.to_string(),
246 preview: preview(m.rule, &m.value),
247 });
248 at = end;
249 }
250 out.extend_from_slice(&bytes[at..]);
251 (String::from_utf8_lossy(&out).into_owned(), redactions)
252}
253
254#[cfg(test)]
255mod tests;