crates/platform-anonymize/src/lib.rs
the anonymizer every log download goes through · 392 lines · compiled into this Worker from the repository as it is
| 1 | //! Personal data (PII/PHI) and secrets out of text and JSON before |
| 2 | //! anything leaves the platform (the admin site's log downloads). Each |
| 3 | //! value is replaced with a typed placeholder, `[email:3f2a]`: the four hex |
| 4 | //! digits are a keyed hash (HMAC-SHA256) of the value, so the same value |
| 5 | //! gets the same placeholder under one key (a download can still say "the |
| 6 | //! same address failed 40 times"), and nobody without the key can tell |
| 7 | //! what it was. Pure Rust, no I/O, no regex, Wasm-friendly; every detector |
| 8 | //! is a linear byte scanner. |
| 9 | //! |
| 10 | //! Text ([`Anonymizer::text`]), most specific first, never overlapping: |
| 11 | //! - key material: PEM blocks (private keys, certificates, PGP; across |
| 12 | //! lines, to the end when cut off), SSH public keys and their comment; |
| 13 | //! - credentials: `Authorization`/`Cookie`/`Set-Cookie`/token header values |
| 14 | //! (the scheme and cookie attributes stay), URL userinfo |
| 15 | //! (`scheme://user:pass@`), webhook URLs (Slack, Discord, Telegram, |
| 16 | //! Teams), `Bearer`/`Basic`/`Token` values, JWTs and other `eyJ…` |
| 17 | //! (our session cookie, tickets), vendor tokens by prefix (Cloudflare |
| 18 | //! Origin CA, AWS, GCP, GitHub, GitLab, Slack, Stripe, Twilio, SendGrid, |
| 19 | //! Mailgun, OpenAI, Anthropic, npm, PyPI, Hugging Face, Shopify, Vault, |
| 20 | //! DigitalOcean, …), Telegram bot tokens, Terraform `[id=…]`; |
| 21 | //! - user agents (cut to `Chrome 120 on macOS`, see [`ua_summary`]); |
| 22 | //! - emails (also `%40` and `[at]`/`[dot]`), UUIDs, MACs, IPv6 and IPv4 |
| 23 | //! (ports and lists stay around them); |
| 24 | //! - checked numbers: payment cards (prefix and Luhn), SSNs and ITINs, |
| 25 | //! UK NI numbers, Canadian SINs (Luhn), IBANs (mod 97); |
| 26 | //! - coordinate pairs, phone numbers (`+`/`00` international, North |
| 27 | //! American), dates of birth after a birth word; |
| 28 | //! - labeled values: passport, licence, tax and national IDs, bank |
| 29 | //! routing/account numbers, CVV, medical record and health plan numbers, |
| 30 | //! ICD-10 codes, diagnoses, medication, allergies, blood alcohol (BAC, |
| 31 | //! ‰), drinks, weight, sex, phone and postal code labels, names and Riot |
| 32 | //! IDs after `name:`-style labels, sign-in, invite, join and room codes; |
| 33 | //! - our apps' routes: the segment after `/v/`, `/join/`, `/u/`, |
| 34 | //! `/api/room/`, `/api/people/`, `/f/`, … (videos, codes, people, files), |
| 35 | //! thirstday room codes (`/BCDF`), `youtu.be/<id>`, account invite codes |
| 36 | //! (`INV-…`), failed-login labels (`h:<hex>`); |
| 37 | //! - `key=value` / `key: value` / `"key":"value"` pairs whose key names a |
| 38 | //! secret or a person (the same names as JSON fields, below; short |
| 39 | //! names like `key`, `code`, `sig`, `v`, `q` only in a query); |
| 40 | //! - Riot IDs (`name#TAG`), hex of 20+ digits (IDs, keys, hashes), dotted |
| 41 | //! and random-looking base64 tokens (20+), street addresses, `@handles`. |
| 42 | //! |
| 43 | //! JSON ([`Anonymizer::json`]): field names decide first ([`field_kind`], |
| 44 | //! case- and separator-insensitive): the whole value of a personal or |
| 45 | //! secret field is replaced (numbers too where they are the data: BAC, |
| 46 | //! weight, coordinates; bools for health data); a thirstday seat (an object |
| 47 | //! with `weight`, `female`, `sips`…) is a health record throughout; user |
| 48 | //! agents are summarized; strings that are themselves JSON are parsed and |
| 49 | //! walked; every other string and every object key goes through the text |
| 50 | //! pass. |
| 51 | //! |
| 52 | //! Kept readable: paths and route words, status codes, durations and |
| 53 | //! counts, dates and times, versions, hostnames, our app and Worker names, |
| 54 | //! country and colo codes, ASNs and their network names, game regions, |
| 55 | //! trace IDs (32 lowercase hex digits starting with a millisecond time, |
| 56 | //! see `platform_logging`), short hex (git short SHAs, Ray IDs), and full |
| 57 | //! commit SHAs (40/64 hex) after a commit word or in `sha`/`commit`/`hash` |
| 58 | //! fields: in a forge log a commit is no secret and its SHA is how you |
| 59 | //! find it. Branch names stay too. |
| 60 | |
| 61 | mod detect; |
| 62 | mod fields; |
| 63 | mod ua; |
| 64 | |
| 65 | use hmac::{Hmac, Mac}; |
| 66 | use serde_json::{Map, Value}; |
| 67 | use sha2::Sha256; |
| 68 | |
| 69 | pub use fields::field_kind; |
| 70 | pub use ua::ua_summary; |
| 71 | |
| 72 | type HmacSha256 = Hmac<Sha256>; |
| 73 | |
| 74 | /// What a placeholder stands for. |
| 75 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 76 | pub enum Kind { |
| 77 | Email, |
| 78 | Ip, |
| 79 | Mac, |
| 80 | Phone, |
| 81 | Card, |
| 82 | Ssn, |
| 83 | Iban, |
| 84 | /// Session IDs, API tokens, signatures, opaque IDs. |
| 85 | Token, |
| 86 | /// Passwords, PINs, one-time codes, recovery codes. |
| 87 | Secret, |
| 88 | /// Key material: private keys, PEM blocks, wrapped keys. |
| 89 | Key, |
| 90 | Uuid, |
| 91 | /// Usernames, account and member IDs, handles, Riot IDs. |
| 92 | User, |
| 93 | /// People's names (and chat server/channel names). |
| 94 | Name, |
| 95 | Address, |
| 96 | Dob, |
| 97 | /// Coordinates, cities, regions, postal codes. |
| 98 | Geo, |
| 99 | /// Health data: blood alcohol, drinks, weight, sex, diagnoses, |
| 100 | /// medication, record numbers. |
| 101 | Health, |
| 102 | /// National and document IDs: passport, licence, tax IDs, ITIN, NI, SIN. |
| 103 | Id, |
| 104 | /// Bank routing and account numbers. |
| 105 | Bank, |
| 106 | /// Sign-in, invite, join and room codes. |
| 107 | Code, |
| 108 | /// What someone watched: video and channel IDs, titles. |
| 109 | Media, |
| 110 | /// What someone wrote: messages, ciphertext, searches, notes. |
| 111 | Content, |
| 112 | /// A user agent that couldn't be summarized. |
| 113 | Ua, |
| 114 | } |
| 115 | |
| 116 | impl Kind { |
| 117 | pub fn label(self) -> &'static str { |
| 118 | match self { |
| 119 | Kind::Email => "email", |
| 120 | Kind::Ip => "ip", |
| 121 | Kind::Mac => "mac", |
| 122 | Kind::Phone => "phone", |
| 123 | Kind::Card => "card", |
| 124 | Kind::Ssn => "ssn", |
| 125 | Kind::Iban => "iban", |
| 126 | Kind::Token => "token", |
| 127 | Kind::Secret => "secret", |
| 128 | Kind::Key => "key", |
| 129 | Kind::Uuid => "uuid", |
| 130 | Kind::User => "user", |
| 131 | Kind::Name => "name", |
| 132 | Kind::Address => "address", |
| 133 | Kind::Dob => "dob", |
| 134 | Kind::Geo => "geo", |
| 135 | Kind::Health => "health", |
| 136 | Kind::Id => "id", |
| 137 | Kind::Bank => "bank", |
| 138 | Kind::Code => "code", |
| 139 | Kind::Media => "media", |
| 140 | Kind::Content => "content", |
| 141 | Kind::Ua => "ua", |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /// Every kind (for tests and docs). |
| 146 | pub const ALL: [Kind; 23] = [ |
| 147 | Kind::Email, Kind::Ip, Kind::Mac, Kind::Phone, Kind::Card, Kind::Ssn, Kind::Iban, Kind::Token, Kind::Secret, Kind::Key, |
| 148 | Kind::Uuid, Kind::User, Kind::Name, Kind::Address, Kind::Dob, Kind::Geo, Kind::Health, Kind::Id, Kind::Bank, Kind::Code, |
| 149 | Kind::Media, Kind::Content, Kind::Ua, |
| 150 | ]; |
| 151 | } |
| 152 | |
| 153 | /// Replaces personal data under one key. |
| 154 | #[derive(Clone)] |
| 155 | pub struct Anonymizer { |
| 156 | mac: HmacSha256, |
| 157 | } |
| 158 | |
| 159 | /// [`Anonymizer::text`] under `key`. |
| 160 | pub fn anonymize(key: &[u8], text: &str) -> String { |
| 161 | Anonymizer::new(key).text(text) |
| 162 | } |
| 163 | |
| 164 | /// [`Anonymizer::json`] under `key`. |
| 165 | pub fn anonymize_json(key: &[u8], v: &mut Value) { |
| 166 | Anonymizer::new(key).json(v) |
| 167 | } |
| 168 | |
| 169 | /// Trace IDs (see `platform_logging::new_trace_id`): 32 lowercase hex |
| 170 | /// digits, the first 12 a millisecond time between 2023 and 2040 (a random |
| 171 | /// 32-digit hex value passes by chance about once in 550). |
| 172 | pub fn is_trace_id(s: &str) -> bool { |
| 173 | s.len() == 32 |
| 174 | && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) |
| 175 | && u64::from_str_radix(&s[..12], 16).is_ok_and(|t| (1_672_531_200_000..2_208_988_800_000).contains(&t)) |
| 176 | } |
| 177 | |
| 178 | pub(crate) fn is_placeholder(s: &str) -> bool { |
| 179 | detect::placeholder_len(s.as_bytes(), 0) == Some(s.len()) |
| 180 | } |
| 181 | |
| 182 | impl Anonymizer { |
| 183 | pub fn new(key: &[u8]) -> Self { |
| 184 | Anonymizer { mac: HmacSha256::new_from_slice(key).expect("HMAC takes any key length") } |
| 185 | } |
| 186 | |
| 187 | /// A key for one purpose (and period) from a long-lived secret, so |
| 188 | /// placeholders can't be linked across purposes or periods. |
| 189 | pub fn derive(secret: &[u8], label: &str) -> Vec<u8> { |
| 190 | let mut m = HmacSha256::new_from_slice(secret).expect("HMAC takes any key length"); |
| 191 | m.update(b"platform-anonymize/v1/"); |
| 192 | m.update(label.as_bytes()); |
| 193 | m.finalize().into_bytes().to_vec() |
| 194 | } |
| 195 | |
| 196 | /// `[kind:hhhh]` for a value (normalized first, so `Bob@X.com` and |
| 197 | /// `bob@x.com` match). |
| 198 | pub fn placeholder(&self, kind: Kind, value: &str) -> String { |
| 199 | let norm = normalize(kind, value); |
| 200 | let mut m = self.mac.clone(); |
| 201 | m.update(kind.label().as_bytes()); |
| 202 | m.update(&[0]); |
| 203 | m.update(norm.as_bytes()); |
| 204 | let h = m.finalize().into_bytes(); |
| 205 | format!("[{}:{:02x}{:02x}]", kind.label(), h[0], h[1]) |
| 206 | } |
| 207 | |
| 208 | /// The text with every match replaced. Placeholders already in it |
| 209 | /// (and `[redacted]`, `[masked]`) are left alone, so running it twice |
| 210 | /// changes nothing. Text ending in JSON (`msg {"a":1}`) has the JSON |
| 211 | /// walked as JSON. |
| 212 | pub fn text(&self, s: &str) -> String { |
| 213 | if let Some(out) = self.embedded_json(s) { |
| 214 | return out; |
| 215 | } |
| 216 | self.scan(s) |
| 217 | } |
| 218 | |
| 219 | /// The detectors over `s`, again over their own output until nothing |
| 220 | /// changes (a replaced value can change what its neighbours look like: |
| 221 | /// `@eyJ.Mozilla/…` is no handle, `@eyJ.[ua:…]` is), so running the |
| 222 | /// anonymizer twice never changes more. |
| 223 | fn scan(&self, s: &str) -> String { |
| 224 | let mut cur = s.to_string(); |
| 225 | for _ in 0..5 { |
| 226 | match self.scan_once(&cur) { |
| 227 | Some(next) if next != cur => cur = next, |
| 228 | _ => break, |
| 229 | } |
| 230 | } |
| 231 | cur |
| 232 | } |
| 233 | |
| 234 | /// One pass; `None` when nothing matched. |
| 235 | fn scan_once(&self, s: &str) -> Option<String> { |
| 236 | let hits = detect::find_all(s); |
| 237 | if hits.is_empty() { |
| 238 | return None; |
| 239 | } |
| 240 | let mut out = String::with_capacity(s.len()); |
| 241 | let mut last = 0; |
| 242 | for h in hits { |
| 243 | out.push_str(&s[last..h.start]); |
| 244 | let v = &s[h.start..h.end]; |
| 245 | match (h.kind, ua_summary(v)) { |
| 246 | (Kind::Ua, Some(sum)) => out.push_str(&sum), |
| 247 | _ => out.push_str(&self.placeholder(h.kind, v)), |
| 248 | } |
| 249 | last = h.end; |
| 250 | } |
| 251 | out.push_str(&s[last..]); |
| 252 | Some(out) |
| 253 | } |
| 254 | |
| 255 | /// `prefix {json}` / `[json]`: the prefix as text, the JSON as JSON. |
| 256 | fn embedded_json(&self, s: &str) -> Option<String> { |
| 257 | let t = s.trim_end(); |
| 258 | if !(t.ends_with('}') || t.ends_with(']')) { |
| 259 | return None; |
| 260 | } |
| 261 | let candidates = [s.find('{'), s.find('[')]; |
| 262 | let mut starts: Vec<usize> = candidates.into_iter().flatten().collect(); |
| 263 | starts.sort_unstable(); |
| 264 | for p in starts { |
| 265 | if let Ok(mut v) = serde_json::from_str::<Value>(&s[p..]) { |
| 266 | if v.is_object() || v.is_array() { |
| 267 | self.json(&mut v); |
| 268 | return Some(format!("{}{}", self.scan(&s[..p]), v)); |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | None |
| 273 | } |
| 274 | |
| 275 | /// Every string (values and object keys) through [`Anonymizer::text`]; |
| 276 | /// whole values of known personal and secret fields replaced. |
| 277 | pub fn json(&self, v: &mut Value) { |
| 278 | self.walk(v, None); |
| 279 | } |
| 280 | |
| 281 | /// `inherited`: inside a field of this kind (a health record, a |
| 282 | /// secret's object): every scalar is that kind. |
| 283 | fn walk(&self, v: &mut Value, inherited: Option<Kind>) { |
| 284 | match v { |
| 285 | Value::String(s) => match inherited { |
| 286 | Some(k) if !fields::empty_like(s) && !is_placeholder(s) => *s = self.placeholder(k, s), |
| 287 | Some(_) => {} |
| 288 | None => { |
| 289 | if let Some(k) = opaque_hex(s) { |
| 290 | *s = self.placeholder(k, s); |
| 291 | } else { |
| 292 | *s = self.text(s); |
| 293 | } |
| 294 | } |
| 295 | }, |
| 296 | Value::Number(n) => { |
| 297 | if let Some(k) = inherited.filter(|k| matches!(k, Kind::Health | Kind::Secret | Kind::Key | Kind::Geo)) { |
| 298 | *v = Value::String(self.placeholder(k, &n.to_string())); |
| 299 | } |
| 300 | } |
| 301 | Value::Bool(x) => { |
| 302 | if inherited == Some(Kind::Health) { |
| 303 | *v = Value::String(self.placeholder(Kind::Health, &x.to_string())); |
| 304 | } |
| 305 | } |
| 306 | Value::Array(items) => items.iter_mut().for_each(|i| self.walk(i, inherited)), |
| 307 | Value::Object(map) => { |
| 308 | let health = inherited.is_none() && map.keys().any(|k| fields::health_record_key(&fields::norm(k))); |
| 309 | let old = std::mem::take(map); |
| 310 | let mut out = Map::new(); |
| 311 | for (k, mut val) in old { |
| 312 | let n = fields::norm(&k); |
| 313 | let kind = inherited.or_else(|| field_kind(&k)).or_else(|| (health && fields::health_context_key(&n)).then_some(Kind::Health)); |
| 314 | match kind { |
| 315 | _ if inherited.is_some() => self.walk(&mut val, inherited), |
| 316 | Some(Kind::Ua) => match &mut val { |
| 317 | Value::String(s) if !fields::empty_like(s) && !is_placeholder(s) => { |
| 318 | *s = ua_summary(s).unwrap_or_else(|| self.placeholder(Kind::Ua, s)); |
| 319 | } |
| 320 | _ => self.walk(&mut val, None), |
| 321 | }, |
| 322 | Some(kind) => self.field(kind, &k, &mut val), |
| 323 | None if fields::hash_field(&n) && val.as_str().is_some_and(|s| (7..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_hexdigit())) => {} |
| 324 | None if fields::query_field(&n) && val.is_string() => { |
| 325 | let s = val.as_str().unwrap_or_default(); |
| 326 | let q = self.text(&format!("?{s}")); |
| 327 | val = Value::String(q[1..].to_string()); |
| 328 | } |
| 329 | None => self.walk(&mut val, None), |
| 330 | } |
| 331 | out.insert(self.text(&k), val); |
| 332 | } |
| 333 | *map = out; |
| 334 | } |
| 335 | Value::Null => {} |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | /// The value of a field named `key` of `kind`. |
| 340 | fn field(&self, kind: Kind, key: &str, v: &mut Value) { |
| 341 | match v { |
| 342 | Value::String(s) => { |
| 343 | if !fields::keep_value(kind, key, s) { |
| 344 | *s = self.placeholder(kind, s); |
| 345 | } else if !is_placeholder(s) { |
| 346 | *s = self.text(s); |
| 347 | } |
| 348 | } |
| 349 | Value::Number(n) => { |
| 350 | if fields::masks_numbers(kind, key) { |
| 351 | *v = Value::String(self.placeholder(kind, &n.to_string())); |
| 352 | } |
| 353 | } |
| 354 | Value::Bool(x) => { |
| 355 | if kind == Kind::Health { |
| 356 | *v = Value::String(self.placeholder(kind, &x.to_string())); |
| 357 | } |
| 358 | } |
| 359 | Value::Array(items) => items.iter_mut().for_each(|i| self.field(kind, key, i)), |
| 360 | Value::Object(_) => { |
| 361 | let whole = matches!(kind, Kind::Health | Kind::Secret | Kind::Key | Kind::Content | Kind::Geo | Kind::Address); |
| 362 | self.walk(v, whole.then_some(kind)); |
| 363 | } |
| 364 | Value::Null => {} |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | /// A whole JSON string that is an opaque hex ID (16+ digits, letters and |
| 370 | /// digits: invite, server, channel, account IDs), not a trace ID. |
| 371 | fn opaque_hex(s: &str) -> Option<Kind> { |
| 372 | let ok = s.len() >= 16 |
| 373 | && s.bytes().all(|c| c.is_ascii_hexdigit()) |
| 374 | && s.bytes().any(|c| c.is_ascii_digit()) |
| 375 | && s.bytes().any(|c| c.is_ascii_alphabetic()) |
| 376 | && !is_trace_id(s); |
| 377 | ok.then_some(Kind::Token) |
| 378 | } |
| 379 | |
| 380 | fn normalize(kind: Kind, v: &str) -> String { |
| 381 | let v = v.trim(); |
| 382 | match kind { |
| 383 | Kind::Email | Kind::Ip | Kind::Uuid | Kind::User | Kind::Name => v.to_lowercase(), |
| 384 | Kind::Mac => v.to_ascii_lowercase().replace('-', ":"), |
| 385 | Kind::Phone | Kind::Card | Kind::Ssn => v.chars().filter(char::is_ascii_digit).collect(), |
| 386 | Kind::Iban | Kind::Id | Kind::Bank | Kind::Code => v.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_uppercase(), |
| 387 | _ => v.to_string(), |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | #[cfg(test)] |
| 392 | mod tests; |