1use serde_json::Value;
24
25#[cfg(test)]
26mod tests;
27
28pub const MASK: &str = "****";
30
31#[must_use]
33pub fn masked(config: &crate::Config) -> Value {
34 let mut value = serde_json::to_value(config).unwrap_or(Value::Null);
35 mask(&mut value);
36 mask_channels(&mut value);
37 value
38}
39
40fn mask_channels(value: &mut Value) {
44 let Some(channels) = value
45 .pointer_mut("/notifications/channels")
46 .and_then(Value::as_object_mut)
47 else {
48 return;
49 };
50 for channel in channels.values_mut() {
51 if let Some(Value::String(url)) = channel.get_mut("url") {
52 *url = origin(url);
53 }
54 if let Some(body) = channel.get_mut("body") {
55 *body = Value::String(MASK.to_owned());
56 }
57 }
58}
59
60fn origin(url: &str) -> String {
62 let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
63 let host = rest.split(['/', '?', '#']).next().unwrap_or_default();
64 let host = host.rsplit_once('@').map_or(host, |(_, host)| host);
66 format!("{scheme}://{host}/{MASK}")
67}
68
69pub fn mask(value: &mut Value) {
71 mask_under(value, "");
72}
73
74pub fn mask_data(value: &mut Value) {
79 match value {
80 Value::String(text) => *text = mask_text(text),
81 Value::Array(items) => items.iter_mut().for_each(mask_data),
82 Value::Object(fields) => {
83 for (name, field) in fields.iter_mut() {
84 let empty = field.is_null() || field.as_str().is_some_and(str::is_empty);
85 if !empty && names_secret_in_words(name) {
86 *field = Value::String(MASK.to_owned());
87 } else {
88 mask_data(field);
89 }
90 }
91 mask_keys(fields);
92 }
93 Value::Null | Value::Bool(_) | Value::Number(_) => {}
94 }
95}
96
97fn mask_keys(fields: &mut serde_json::Map<String, Value>) {
100 if !fields.keys().any(|name| mask_text(name) != *name) {
101 return;
102 }
103 let mut masked = serde_json::Map::new();
104 for (name, field) in std::mem::take(fields) {
105 let shown = mask_text(&name);
106 let mut unique = shown.clone();
107 let mut n = 1;
108 while masked.contains_key(&unique) {
109 n += 1;
110 unique = format!("{shown} ({n})");
111 }
112 masked.insert(unique, field);
113 }
114 *fields = masked;
115}
116
117#[must_use]
122pub fn names_secret_in_words(name: &str) -> bool {
123 let chars: Vec<char> = name.chars().collect();
124 let mut words: Vec<String> = Vec::new();
125 let mut word = String::new();
126 for (at, &c) in chars.iter().enumerate() {
127 if !c.is_alphanumeric() {
128 words.push(std::mem::take(&mut word));
129 continue;
130 }
131 let previous = at.checked_sub(1).map(|p| chars[p]);
132 let next_lower = chars.get(at + 1).is_some_and(|n| n.is_lowercase());
133 let starts_word = c.is_uppercase()
134 && previous.is_some_and(|p| {
135 p.is_lowercase() || p.is_ascii_digit() || (p.is_uppercase() && next_lower)
136 });
137 if starts_word {
138 words.push(std::mem::take(&mut word));
139 }
140 word.extend(c.to_lowercase());
141 }
142 words.push(word);
143 words.retain(|w| !w.is_empty());
144 let alone = [
145 "password",
146 "passwords",
147 "passwd",
148 "pwd",
149 "passphrase",
150 "secret",
151 "secrets",
152 "token",
153 "tokens",
154 "credential",
155 "credentials",
156 "apikey",
157 "privatekey",
158 "accesskey",
159 "secretkey",
160 ];
161 words.iter().any(|w| alone.contains(&w.as_str()))
162 || words.windows(2).any(|pair| {
163 pair[1] == "key" && matches!(pair[0].as_str(), "api" | "private" | "access" | "secret")
164 })
165}
166
167pub(crate) fn mask_url(text: &str) -> String {
173 let read = url_as_read(text);
174 if read.len() != text.len() && looks_like_url(&read) {
175 let masked = mask_text(&read);
176 if masked != read {
177 return masked;
178 }
179 }
180 mask_text(text)
181}
182
183pub(crate) fn url_as_read(url: &str) -> String {
185 url.chars()
186 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
187 .collect()
188}
189
190fn looks_like_url(text: &str) -> bool {
192 text.split_once("://").is_some_and(|(scheme, _)| {
193 scheme.starts_with(|c: char| c.is_ascii_alphabetic())
194 && scheme
195 .chars()
196 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
197 }) && !text.contains(char::is_whitespace)
198}
199
200fn mask_under(value: &mut Value, table: &str) {
202 match value {
203 Value::String(text) => *text = mask_url(text),
204 Value::Array(items) => items.iter_mut().for_each(|item| mask_under(item, table)),
205 Value::Object(fields) => {
206 for (name, field) in fields.iter_mut() {
207 if holds_secret(table, name, field) {
208 *field = Value::String(MASK.to_owned());
209 } else {
210 mask_under(field, name);
211 }
212 }
213 mask_keys(fields);
214 }
215 Value::Null | Value::Bool(_) | Value::Number(_) => {}
216 }
217}
218
219fn holds_secret(table: &str, name: &str, value: &Value) -> bool {
222 let empty = match value {
223 Value::Null => true,
224 Value::String(text) => text.is_empty(),
225 _ => false,
226 };
227 if empty {
228 return false;
229 }
230 let name = compact(name);
231 let points_elsewhere = ["file", "files", "path", "paths", "dir", "header", "env"]
232 .iter()
233 .any(|end| name.ends_with(end));
234 if points_elsewhere {
235 return false;
236 }
237 if name == "key" {
240 return !(table == "tls" && value.as_str().is_some_and(looks_like_path));
241 }
242 names_secret(&name)
243}
244
245fn compact(name: &str) -> String {
247 name.chars()
248 .filter(|c| !matches!(c, '_' | '-' | '.' | ' '))
249 .flat_map(char::to_lowercase)
250 .collect()
251}
252
253fn names_secret(name: &str) -> bool {
255 [
256 "password",
257 "passwd",
258 "pwd",
259 "secret",
260 "token",
261 "credential",
262 "apikey",
263 "privatekey",
264 "accesskey",
265 ]
266 .iter()
267 .any(|word| name.contains(word))
268 || name == "key"
269 || (name.len() > 3 && name.ends_with("key"))
270}
271
272fn looks_like_path(text: &str) -> bool {
273 text.contains('/')
274 || text.contains('\\')
275 || std::path::Path::new(text)
276 .extension()
277 .is_some_and(|ext| ext.eq_ignore_ascii_case("pem") || ext.eq_ignore_ascii_case("key"))
278}
279
280#[must_use]
284pub fn mask_text(text: &str) -> String {
285 mask_text_after("", text)
286}
287
288#[must_use]
293pub fn mask_text_after(before: &str, text: &str) -> String {
294 let chars: Vec<char> = before.chars().chain(text.chars()).collect();
295 let mut hidden = vec![false; chars.len()];
296 hide_passwords(&chars, &mut hidden);
297 for at in 0..chars.len() {
298 if matches!(chars[at], '=' | ':') && !hidden[at] {
300 hide_value_after(&chars, at, &mut hidden);
301 }
302 }
303 let skip = before.chars().count();
304 let mut out = String::with_capacity(text.len());
305 let mut in_mask = false;
306 for (c, hide) in chars.iter().zip(&hidden).skip(skip) {
307 if *hide {
308 if !in_mask {
309 out.push_str(MASK);
310 in_mask = true;
311 }
312 } else {
313 out.push(*c);
314 in_mask = false;
315 }
316 }
317 out
318}
319
320fn ends_token(c: char) -> bool {
323 c.is_whitespace() || matches!(c, '"' | '<' | '>' | '`')
324}
325
326fn hide_passwords(chars: &[char], hidden: &mut [bool]) {
331 let ahead = at_ahead(chars);
332 let mut start = 0;
333 let mut colon: Option<usize> = None;
334 let mut last_at: Option<usize> = None;
335 let mut i = 0;
336 while i < chars.len() {
337 let c = chars[i];
338 let scheme_end =
339 c == ':' && chars.get(i + 1) == Some(&'/') && chars.get(i + 2) == Some(&'/');
340 let network_path = c == '/' && chars.get(i + 1) == Some(&'/') && i == start;
341 let in_password = c == '"' && colon.is_some() && ahead[i];
344 if (ends_token(c) && !in_password) || scheme_end || network_path {
345 end_segment(colon, last_at, hidden);
346 (colon, last_at) = (None, None);
347 i += if scheme_end {
348 3
349 } else if network_path {
350 2
351 } else {
352 1
353 };
354 start = i;
355 continue;
356 }
357 match c {
358 ':' if colon.is_none() => colon = Some(i),
359 '@' => last_at = Some(i),
360 _ => {}
361 }
362 i += 1;
363 }
364 end_segment(colon, last_at, hidden);
365}
366
367fn at_ahead(chars: &[char]) -> Vec<bool> {
370 let mut ahead = vec![false; chars.len()];
371 let mut seen = false;
372 for (i, c) in chars.iter().enumerate().rev() {
373 ahead[i] = seen;
374 if *c == '@' {
375 seen = true;
376 } else if *c != '"' && ends_token(*c) {
377 seen = false;
378 }
379 }
380 ahead
381}
382
383fn end_segment(colon: Option<usize>, last_at: Option<usize>, hidden: &mut [bool]) {
385 if let (Some(colon), Some(at)) = (colon, last_at)
386 && colon < at
387 {
388 hidden[colon + 1..at]
389 .iter_mut()
390 .for_each(|flag| *flag = true);
391 }
392}
393
394fn hide_value_after(chars: &[char], at: usize, hidden: &mut [bool]) {
398 let mut end = at;
400 while end > 0 && chars[end - 1] == ' ' {
401 end -= 1;
402 }
403 if end > 0 && matches!(chars[end - 1], '"' | '\'') {
404 end -= 1;
405 }
406 let name_char = |c: char| c.is_alphanumeric() || matches!(c, '_' | '-' | '.' | '%');
407 let mut start = end;
408 while start > 0 && name_char(chars[start - 1]) {
409 start -= 1;
410 }
411 let mut across = end;
416 while across > 0 && (name_char(chars[across - 1]) || chars[across - 1] == '\t') {
417 across -= 1;
418 }
419 if across == end {
420 return;
421 }
422 let names = |from: usize| {
423 let name: String = chars[from..end].iter().collect();
424 names_secret(&compact(&percent_decoded(&name)))
425 };
426 let secret = (start < end && names(start)) || (across < start && names(across));
427 if !secret {
428 return;
429 }
430 if chars[at] == ':' && chars.get(at + 1) == Some(&'/') {
432 return;
433 }
434 let mut from = at + 1;
435 while from < chars.len() && chars[from] == ' ' {
436 from += 1;
437 }
438 if chars[at] == ':' && starts_os_error(&chars[from..]) {
442 return;
443 }
444 let quote = chars.get(from).copied().filter(|c| matches!(c, '"' | '\''));
445 if quote.is_some() {
446 from += 1;
447 }
448 let mut to = from;
449 while to < chars.len() {
450 let c = chars[to];
451 let ends = match quote {
452 Some(_) if c == '\\' => {
453 to += 2;
454 continue;
455 }
456 Some(q) => c == q,
457 None => ends_token(c) || matches!(c, '&' | ';' | '#'),
458 };
459 if ends {
460 break;
461 }
462 to += 1;
463 }
464 let to = to.min(chars.len());
465 hidden[from..to].iter_mut().for_each(|flag| *flag = true);
466}
467
468fn starts_os_error(text: &[char]) -> bool {
470 const ERRORS: [&str; 6] = [
471 "No such file or directory",
472 "Permission denied",
473 "Is a directory",
474 "Not a directory",
475 "cannot open shared object file",
476 "File exists",
477 ];
478 ERRORS.iter().any(|error| {
479 let error: Vec<char> = error.chars().collect();
480 text.starts_with(&error)
481 })
482}
483
484pub(crate) fn percent_decoded(text: &str) -> String {
487 let text: String = text
490 .chars()
491 .filter(|c| !matches!(c, '\t' | '\n' | '\r'))
492 .collect();
493 let bytes = text.as_bytes();
494 let mut out = Vec::with_capacity(bytes.len());
495 let mut i = 0;
496 while i < bytes.len() {
497 if bytes[i] == b'%'
498 && let Some(hex) = text.get(i + 1..i + 3)
499 && let Ok(byte) = u8::from_str_radix(hex, 16)
500 {
501 out.push(byte);
502 i += 3;
503 } else {
504 out.push(bytes[i]);
505 i += 1;
506 }
507 }
508 String::from_utf8_lossy(&out).into_owned()
509}