BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-call-model / src / report / scrub.rs

scrub.rs

scrub.rs 15.9 KiB Download Raw
1use std::collections::HashMap;
2use std::sync::LazyLock;
3
4use regex::{Captures, Regex, escape};
5
6use super::common_words::is_common_word;
7
8pub const SELF_PLACEHOLDER: &str = "self";
9pub const ECHO_PLACEHOLDER: &str = "echo-bot";
10const ORGID_PREFIX: &str = "8:orgid:";
11const MIN_NAME_PART: usize = 3;
12const ID_SEGMENT_MIN: usize = 8;
13const REMOVED: &str = "[removed]";
14
15fn compiled(pattern: &str) -> Regex {
16 Regex::new(pattern).expect("scrub pattern compiles")
17}
18
19static URL: LazyLock<Regex> = LazyLock::new(|| compiled(r#"(?i)\b[a-z][a-z0-9+.-]*://[^\s"'<>)\]]+"#));
20static JWT: LazyLock<Regex> = LazyLock::new(|| compiled(r"\beyJ[\w-]+\.[\w-]+\.[\w-]*"));
21static COOKIE: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(set-cookie|cookie)\s*[:=][^\n]*"));
22static BEARER: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(bearer|basic)\s+[\w\-.~+/=]+"));
23static CREDENTIAL: LazyLock<Regex> = LazyLock::new(|| {
24 compiled(
25 r"(?i)\b(access_token|refresh_token|id_token|skypetoken|authtoken|token|authorization|password|passwd|secret|signature|sig)\b\s*[:=]\s*[^\s&;,]+",
26 )
27});
28static ICE_CREDENTIAL: LazyLock<Regex> =
29 LazyLock::new(|| compiled(r"(?i)\b(ice-ufrag|ice-pwd|ufrag|pwd)\b[:=\s]+\S+"));
30static FINGERPRINT: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b(?:[0-9a-f]{2}:){15,}[0-9a-f]{2}\b"));
31static THREAD: LazyLock<Regex> = LazyLock::new(|| compiled(r#"\b19:[^\s,;"'<>()]+@[A-Za-z0-9.\-]+"#));
32static ENCODED_THREAD: LazyLock<Regex> = LazyLock::new(|| compiled(r"(?i)\b19%3a\S+?%40[A-Za-z0-9.\-]+"));
33static MRI: LazyLock<Regex> = LazyLock::new(|| {
34 compiled(r#"\b(?:8:(?:orgid|live|acs|teamsvisitor|spo|gid):[A-Za-z0-9_.+\-=]+|28:[A-Za-z0-9_.\-]{8,}|4:\+?\d{5,})"#)
35});
36static EMAIL: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9._%+'\-]+@[A-Za-z0-9\-]+(?:\.[A-Za-z0-9\-]+)+"));
37static UUID: LazyLock<Regex> = LazyLock::new(|| {
38 compiled(r"(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b")
39});
40static IPV4: LazyLock<Regex> = LazyLock::new(|| compiled(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"));
41static IPV6: LazyLock<Regex> = LazyLock::new(|| {
42 compiled(
43 r"(?i)\b(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}\b|(?:\b[0-9a-f]{1,4}:){1,7}:(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,6})?|::(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4}\b",
44 )
45});
46static PHONE: LazyLock<Regex> = LazyLock::new(|| compiled(r"\+\d[\d ()\-/]{6,}\d"));
47static OPAQUE: LazyLock<Regex> = LazyLock::new(|| compiled(r"[A-Za-z0-9+/_\-]{40,}={0,2}"));
48
49#[derive(Debug, Clone)]
50struct NameMatch {
51 name: String,
52 placeholder: String,
53 exact_case: bool,
54}
55
56impl NameMatch {
57 fn matches(&self, text: &str) -> bool {
58 if self.exact_case {
59 self.name == text
60 } else {
61 self.name.to_lowercase() == text.to_lowercase()
62 }
63 }
64}
65
66#[derive(Debug, Clone, Default)]
67pub struct Scrubber {
68 people: HashMap<String, String>,
69 names: Vec<NameMatch>,
70 meetings: HashMap<String, String>,
71 identifiers: HashMap<String, String>,
72 person_count: usize,
73}
74
75impl Scrubber {
76 pub fn new() -> Self {
77 Scrubber::default()
78 }
79
80 pub fn register_self(&mut self, mri: &str, display_name: &str, email: &str) {
81 for key in [mri, email].into_iter().filter(|key| !key.trim().is_empty()) {
82 self.alias(key, SELF_PLACEHOLDER);
83 }
84 self.add_name(display_name, SELF_PLACEHOLDER);
85 }
86
87 pub fn register_person(&mut self, mri: &str, display_name: &str) {
88 let placeholder = if mri == calling::signaling::ECHO_BOT_MRI {
89 self.alias(mri, ECHO_PLACEHOLDER);
90 if !display_name.trim().is_empty() {
91 self.push_name(display_name, ECHO_PLACEHOLDER, false);
92 }
93 return;
94 } else if mri.is_empty() {
95 self.person(display_name)
96 } else {
97 self.person(mri)
98 };
99 self.add_name(display_name, &placeholder);
100 }
101
102 pub fn person(&mut self, key: &str) -> String {
103 let normalized = normalize(key);
104 if let Some(found) = self.people.get(&normalized) {
105 return found.clone();
106 }
107 self.person_count += 1;
108 let placeholder = format!("person-{}", self.person_count);
109 self.alias(key, &placeholder);
110 placeholder
111 }
112
113 fn alias(&mut self, key: &str, placeholder: &str) {
114 let normalized = normalize(key);
115 if let Some(user_id) = normalized.strip_prefix(ORGID_PREFIX) {
116 self.people.insert(user_id.to_owned(), placeholder.to_owned());
117 }
118 self.people.insert(normalized, placeholder.to_owned());
119 }
120
121 fn add_name(&mut self, name: &str, placeholder: &str) {
122 if name.trim().is_empty() {
123 return;
124 }
125 let full_name = name.trim();
126 let parts: Vec<&str> =
127 full_name.split(|character: char| !character.is_alphanumeric()).filter(|part| !part.is_empty()).collect();
128 if full_name.chars().count() > 1 {
129 self.push_name(full_name, placeholder, parts.len() == 1 && is_common_word(full_name));
130 }
131 for part in parts.into_iter().filter(|part| is_name_part(part)) {
132 self.push_name(part, placeholder, is_common_word(part));
133 }
134 }
135
136 /// `exact_case`: a dictionary word only counts as the name in the name's own spelling ("Mark", not "mark").
137 fn push_name(&mut self, name: &str, placeholder: &str, exact_case: bool) {
138 if self.names.iter().any(|known| known.name.eq_ignore_ascii_case(name)) {
139 return;
140 }
141 self.names.push(NameMatch {
142 name: name.to_owned(),
143 placeholder: placeholder.to_owned(),
144 exact_case,
145 });
146 }
147
148 pub fn scrub(&mut self, text: &str) -> String {
149 let mut text = URL.replace_all(text, |captures: &Captures| scrub_url(&captures[0])).into_owned();
150 text = JWT.replace_all(&text, REMOVED).into_owned();
151 text = COOKIE.replace_all(&text, "$1: [removed]").into_owned();
152 text = BEARER.replace_all(&text, "$1 [removed]").into_owned();
153 text = CREDENTIAL.replace_all(&text, "$1 [removed]").into_owned();
154 text = ICE_CREDENTIAL.replace_all(&text, "$1 [removed]").into_owned();
155 text = FINGERPRINT.replace_all(&text, "[fingerprint]").into_owned();
156 text = THREAD.replace_all(&text, |captures: &Captures| self.meeting(&captures[0])).into_owned();
157 text = ENCODED_THREAD.replace_all(&text, |captures: &Captures| self.meeting(&captures[0])).into_owned();
158 text = MRI.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
159 text = EMAIL.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
160 text = PHONE.replace_all(&text, |captures: &Captures| self.person(&captures[0])).into_owned();
161 text = UUID.replace_all(&text, |captures: &Captures| self.identifier(&captures[0])).into_owned();
162 text = IPV6.replace_all(&text, "[ip]").into_owned();
163 text = IPV4.replace_all(&text, "[ip]").into_owned();
164 text = self.replace_names(&text);
165 OPAQUE.replace_all(&text, REMOVED).into_owned()
166 }
167
168 fn meeting(&mut self, key: &str) -> String {
169 let next = self.meetings.len() + 1;
170 self.meetings.entry(normalize(key)).or_insert_with(|| format!("meeting-{next}")).clone()
171 }
172
173 fn identifier(&mut self, key: &str) -> String {
174 let normalized = normalize(key);
175 if let Some(found) = self.people.get(&normalized) {
176 return found.clone();
177 }
178 let next = self.identifiers.len() + 1;
179 self.identifiers.entry(normalized).or_insert_with(|| format!("id-{next}")).clone()
180 }
181
182 fn replace_names(&self, text: &str) -> String {
183 if self.names.is_empty() {
184 return text.to_owned();
185 }
186 let mut ordered: Vec<&NameMatch> = self.names.iter().collect();
187 ordered.sort_by_key(|entry| std::cmp::Reverse(entry.name.chars().count()));
188 let alternatives: Vec<String> = ordered
189 .iter()
190 .map(|entry| if entry.exact_case { escape(&entry.name) } else { format!("(?i:{})", escape(&entry.name)) })
191 .collect();
192 let pattern = format!(r"\b(?:{})\b", alternatives.join("|"));
193 let Ok(names) = Regex::new(&pattern) else {
194 return text.to_owned();
195 };
196 names
197 .replace_all(text, |captures: &Captures| {
198 ordered
199 .iter()
200 .find(|entry| entry.matches(&captures[0]))
201 .map_or_else(|| REMOVED.to_owned(), |entry| entry.placeholder.clone())
202 })
203 .into_owned()
204 }
205}
206
207fn is_name_part(part: &str) -> bool {
208 part.chars().count() >= MIN_NAME_PART
209 && !part.chars().all(|character| character.is_ascii_digit())
210 && (!is_common_word(part) || part.chars().next().is_some_and(char::is_uppercase))
211}
212
213fn normalize(key: &str) -> String {
214 key.trim().to_lowercase()
215}
216
217pub fn scrub_url(url: &str) -> String {
218 let (scheme, rest) = url.split_once("://").unwrap_or(("", url));
219 let (authority_and_path, has_query) = match rest.find(['?', '#']) {
220 Some(position) => (&rest[..position], true),
221 None => (rest, false),
222 };
223 let (authority, path) = match authority_and_path.find('/') {
224 Some(position) => authority_and_path.split_at(position),
225 None => (authority_and_path, ""),
226 };
227 let host = authority.rsplit('@').next().unwrap_or(authority);
228 let host_name = host.split(':').next().unwrap_or(host);
229 let host = if IPV4.is_match(host_name) || host.starts_with('[') {
230 "[ip]".to_owned()
231 } else {
232 host.to_lowercase()
233 };
234 let path: Vec<String> = path
235 .split('/')
236 .map(|segment| if is_identifier_segment(segment) { "{id}".to_owned() } else { segment.to_owned() })
237 .collect();
238 let query = if has_query { "?..." } else { "" };
239 format!("{scheme}://{host}{}{query}", path.join("/"))
240}
241
242fn is_identifier_segment(segment: &str) -> bool {
243 let has_digit = segment.chars().any(|character| character.is_ascii_digit());
244 let encoded = segment.contains(['@', ':', '%', '=']);
245 encoded || (segment.chars().count() >= ID_SEGMENT_MIN && has_digit) || UUID.is_match(segment)
246}
247
248#[cfg(test)]
249mod tests {
250 use super::*;
251
252 fn scrubber() -> Scrubber {
253 let mut scrubber = Scrubber::new();
254 scrubber.register_self("8:orgid:11111111-2222-3333-4444-555555555555", "Daniel Daeschle", "daniel@example.com");
255 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Mara Lindqvist");
256 scrubber
257 }
258
259 const FIXTURE: &str = "\
260Mara Lindqvist called 8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee from daniel@example.com; \
261Daniel Daeschle answered. Colleague jonas.ortega@contoso.com and +49 170 1234567 joined, also 8:orgid:99999999-8888-7777-6666-555555555555 and 4:+4917012345678. \
262Thread 19:meeting_ZmFrZWlkMTIzNDU2Nzg5@thread.v2 and 19:abc123_def456@unq.gbl.spaces. \
263GET https://emea.ng.msg.teams.microsoft.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages?token=abc123&skypetoken=zzz#frag \
264Authorization: Bearer abcdef.ghijkl.mnopqr and eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiIxMjM0In0.c2lnbmF0dXJl. \
265Cookie: session=abc; other=def\n\
266Retry with access_token=hunter2 failed. \
267a=ice-ufrag:Xy12 a=ice-pwd:supersecretpasswordvalue12 candidate 1 UDP 2122 203.0.113.9 50000 typ host ufrag Xy12 and 2001:db8:85a3::8a2e:370:7334 \
268a=fingerprint:sha-256 AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89:AB:CD:EF:01:23:45:67:89 \
269opaque QWxhZGRpbjpvcGVuIHNlc2FtZVF1ZXJ5U3RyaW5nVGhhdElzTG9uZ0Vub3VnaEZvckFUb2tlbg \
270meeting id 12345678-aaaa-bbbb-cccc-1234567890ab at 12:30:45.";
271
272 #[test]
273 fn nothing_personal_survives_the_fixture() {
274 let scrubbed = scrubber().scrub(FIXTURE);
275 for leaked in [
276 "Mara", "Lindqvist", "Daniel", "Daeschle", "daniel@", "example.com", "jonas", "contoso", "+49", "1234567",
277 "aaaaaaaa", "99999999", "11111111", "ZmFrZW", "abc123", "def456", "skypetoken=zzz", "token=abc", "abcdef.ghijkl",
278 "eyJ", "session=abc", "access_token=hunter2", "Xy12", "supersecret", "203.0.113.9", "2001:db8", "AB:CD:EF", "QWxhZGRp", "12345678-aaaa",
279 ] {
280 assert!(!scrubbed.contains(leaked), "{leaked} leaked in: {scrubbed}");
281 }
282 }
283
284 #[test]
285 fn people_get_stable_placeholders_across_forms() {
286 let mut scrubber = scrubber();
287 let scrubbed = scrubber.scrub("Mara Lindqvist 8:orgid:AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee mara");
288 assert_eq!(scrubbed, "person-1 person-1 person-1 person-1");
289 assert_eq!(scrubber.scrub("daniel@example.com Daniel"), "self self");
290 assert_eq!(scrubber.scrub("8:orgid:99999999-8888-7777-6666-555555555555"), "person-2");
291 assert_eq!(scrubber.scrub("jonas.ortega@contoso.com 8:orgid:99999999-8888-7777-6666-555555555555"), "person-3 person-2");
292 }
293
294 #[test]
295 fn threads_become_numbered_meetings() {
296 let mut scrubber = Scrubber::new();
297 let scrubbed = scrubber.scrub("19:abc@thread.v2 then 19:def@thread.v2 then 19:abc@thread.v2");
298 assert_eq!(scrubbed, "meeting-1 then meeting-2 then meeting-1");
299 }
300
301 #[test]
302 fn urls_keep_host_and_path_shape() {
303 assert_eq!(
304 scrub_url("https://Host.Example.com/v1/users/ME/conversations/19%3Aabc%40thread.v2/messages/1699999999999?x=1"),
305 "https://host.example.com/v1/users/ME/conversations/{id}/messages/{id}?..."
306 );
307 assert_eq!(scrub_url("https://203.0.113.9:3478/turn"), "https://[ip]/turn");
308 assert_eq!(scrub_url("https://user:pass@host.example.com/a"), "https://host.example.com/a");
309 }
310
311 #[test]
312 fn plain_diagnostics_stay_readable() {
313 let mut scrubber = scrubber();
314 let text = "ICE state Connected at 12:30:45, in packets=1200 level=0.031 mixer reports 4 (rtt 31 ms)";
315 assert_eq!(scrubber.scrub(text), text);
316 }
317
318 #[test]
319 fn common_words_in_a_name_are_only_replaced_in_the_names_spelling() {
320 let mut scrubber = Scrubber::new();
321 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Check Testperson");
322 scrubber.register_person("8:orgid:99999999-8888-7777-6666-555555555555", "Max Video");
323 assert_eq!(
324 scrubber.scrub("check video max bitrate, Check Testperson and Max Video joined, testperson left"),
325 "check video max bitrate, person-1 and person-2 joined, person-1 left"
326 );
327 }
328
329 #[test]
330 fn name_parts_match_only_whole_words() {
331 let mut scrubber = Scrubber::new();
332 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Quilla Brandtmoor");
333 assert_eq!(
334 scrubber.scrub("Quillay quilla Brandtmoorish BRANDTMOOR"),
335 "Quillay person-1 Brandtmoorish person-1"
336 );
337 }
338
339 #[test]
340 fn short_and_numeric_name_parts_are_ignored() {
341 let mut scrubber = Scrubber::new();
342 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Yu Zentrel 2024");
343 assert_eq!(scrubber.scrub("yu 2024 Zentrel Yu Zentrel 2024"), "yu 2024 person-1 person-1");
344 }
345
346 #[test]
347 fn a_single_word_common_name_is_replaced_only_in_its_spelling() {
348 let mut scrubber = Scrubber::new();
349 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Test");
350 assert_eq!(scrubber.scrub("test call Test"), "test call person-1");
351 }
352
353 #[test]
354 fn a_given_name_that_is_a_word_is_still_replaced_when_capitalized() {
355 let mut scrubber = Scrubber::new();
356 scrubber.register_person("8:orgid:aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", "Mark Zentrel");
357 assert_eq!(scrubber.scrub("Mark joined, mark the stream"), "person-1 joined, mark the stream");
358 }
359
360 #[test]
361 fn the_echo_bot_is_named_not_numbered() {
362 let mut scrubber = Scrubber::new();
363 scrubber.register_person(calling::signaling::ECHO_BOT_MRI, "Teams echo");
364 assert_eq!(scrubber.scrub(&format!("{} Teams echo", calling::signaling::ECHO_BOT_MRI)), "echo-bot echo-bot");
365 }
366}