BlueGit

ict rusty-teams

Files

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

scrub.rs

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