BlueGit

ict rusty-teams

Files

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

scrub.rs

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