grow_better_stack_logs/logging/
redaction.rs1use regex::Regex;
5
6use super::{AttrValue, Attributes, LogRecord};
7
8pub const DEFAULT_REDACT_KEYS: &[&str] = &[
10 "password",
11 "passwd",
12 "token",
13 "authorization",
14 "secret",
15 "cookie",
16 "api_key",
17 "apikey",
18 "access_key",
19 "private_key",
20];
21
22#[derive(Debug, Clone)]
25pub struct RedactionProcessor {
26 keys: Vec<String>,
27 patterns: Vec<Regex>,
28 replacement: String,
29}
30
31impl Default for RedactionProcessor {
32 fn default() -> Self {
33 RedactionProcessor::new(DEFAULT_REDACT_KEYS.iter().copied(), Vec::new())
34 }
35}
36
37impl RedactionProcessor {
38 pub fn new<K, S>(keys: K, patterns: Vec<Regex>) -> Self
40 where
41 K: IntoIterator<Item = S>,
42 S: AsRef<str>,
43 {
44 RedactionProcessor {
45 keys: keys
46 .into_iter()
47 .map(|k| k.as_ref().to_lowercase())
48 .collect(),
49 patterns,
50 replacement: crate::core::REDACTED.to_string(),
51 }
52 }
53
54 pub fn with_extra_keys<S: AsRef<str>>(mut self, keys: impl IntoIterator<Item = S>) -> Self {
56 self.keys
57 .extend(keys.into_iter().map(|k| k.as_ref().to_lowercase()));
58 self
59 }
60
61 pub fn with_pattern(mut self, pattern: Regex) -> Self {
63 self.patterns.push(pattern);
64 self
65 }
66
67 pub fn with_replacement(mut self, replacement: impl Into<String>) -> Self {
69 self.replacement = replacement.into();
70 self
71 }
72
73 pub fn keys(&self) -> &[String] {
75 &self.keys
76 }
77
78 pub fn is_sensitive_key(&self, name: &str) -> bool {
80 let lower = name.to_lowercase();
81 self.keys.iter().any(|k| lower.contains(k.as_str()))
82 }
83
84 pub fn process(&self, record: &LogRecord) -> LogRecord {
86 let mut out = record.clone();
87 self.apply(&mut out);
88 out
89 }
90
91 pub fn apply(&self, record: &mut LogRecord) {
93 if !self.patterns.is_empty() {
94 record.body = self.redact_text(&record.body);
95 }
96 self.redact_map(&mut record.attributes);
97 }
98
99 fn redact_text(&self, text: &str) -> String {
100 self.patterns.iter().fold(text.to_string(), |acc, p| {
101 p.replace_all(&acc, self.replacement.as_str()).into_owned()
102 })
103 }
104
105 fn redact_map(&self, map: &mut Attributes) {
106 for (k, v) in map.iter_mut() {
107 if self.is_sensitive_key(k) {
108 *v = AttrValue::String(self.replacement.clone());
109 } else {
110 self.redact_value(v);
111 }
112 }
113 }
114
115 fn redact_value(&self, value: &mut AttrValue) {
116 match value {
117 AttrValue::String(s) if !self.patterns.is_empty() => *s = self.redact_text(s),
118 AttrValue::Array(items) => items.iter_mut().for_each(|v| self.redact_value(v)),
119 AttrValue::Object(m) => {
120 for (k, v) in m.iter_mut() {
121 if self.is_sensitive_key(k) {
122 *v = AttrValue::String(self.replacement.clone());
123 } else {
124 self.redact_value(v);
125 }
126 }
127 }
128 _ => {}
129 }
130 }
131}