Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienos.com/blob/main/crates/hive-feed/src/privacy.rs # aienos.com Source of www.aienos.com, served from my own hardware Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienos.com / crates / hive-feed / src / privacy.rs` 824 lines · 40126 bytes Raw Blame History 1 //! Unicode format characters (Cf) are removed, then tokens are split on the original text's Unicode White_Space and each token is normalized with NFKC, so a space that normalization creates stays inside the token; ASCII sentence punctuation (`. , ; : ! ?`), brackets, and quotes are trimmed from its edges and written back; a token that contains `@` or a numeric character is withheld unless it is a run of fewer than six numeric characters and no letters (`94043`, `(415)`), or ASCII letters with at most one hyphen and exactly one trailing numeric character (`hunter2`, `OAuth2`, `UTF-8`), or a hyphenated name of words and single digits totaling at most five, or one word followed by a number of two to five digits (`gpt-6-astra`, `claude-opus-5-5`, `COVID-19`, `UTF-16`, `ISO-8601`), or a density suffix of one or two digits, a lowercase `x`, a dot and letters whose local part would itself be kept (`icon@2x.png`, `image@2x.png`, `jane@2x.com`), or an address on the operator allowlist (`Owner@Example.org`), or a whole-token credential of equal-length letter strings whose password repeats a letter (`user:pass@10.1.2.3`; a scheme wrapper does not keep a userinfo the bare form withholds); any other token is split at `@`, `:`, `/` and `\` and each part is judged by this same rule, so an address, a phone, or a key after a colon or in a URL tail is withheld on its own; any other `@` with a non-empty side, after ASCII quotes are removed, is an address and needs no well-formed domain, and any other numeric character, including groups joined by a non-alphanumeric separator when six or more are present (`415.555.0199`, `2024-11-15`), is withheld, and a token with neither `@` nor a numeric character is kept. 2 //! 3 //! Written limits, each with a test. These are consequences of that sentence, not further rules: 4 //! - a token with no `@` and no numeric character is kept, including a letter-only password (`letmein`) and a base64 spelling with no digit (`dXNlcjpwYXNz`, `aHVudGVyMg==`); 5 //! - letters plus one trailing digit are a version (`hunter2`, `OAuth2`, `IPv6`, `UTF-8`); 6 //! - a hyphenated name of words and single digits, at most five numeric characters, is kept (`gpt-6-astra`, `claude-opus-5-5`), and so is one word followed by a number of two to five digits (`COVID-19`, `UTF-16`, `Win-11`, `ISO-8601`, `rfc-1918`); a letter prefix does not keep a phone, an SSN, a card, or a key; 7 //! - a density suffix of one or two digits and a lowercase `x` is kept only when its local part would itself be kept (`icon@2x.png`, `jane@2x.com`); 8 //! - fewer than six digits, with no letters, are kept (`94043`, `10000`, `4041`, `2024`, `1600`, `(415)`); 9 //! - a secret split by spaces stays (`4242 4242 4242 4242`, `+1 415 555 0199`); 10 //! - brackets and quotes around a kept token stay (`(COVID-19)`, `(UTF-16)`); 11 //! - a digit glued to letters stays withheld (`gpt-4o`, `python3.12`, `Qwen3.6-35B-A3B-FP8`); a shape that kept them would also keep `pass-w0rd`; 12 //! - `user:pass@10.1.2.3` stays; a scheme wrapper, a letter hostname, and any other password do not; 13 //! - `v1.2.3`, `x86_64`, `sha256`, a dotted or hyphenated phone, ZIP+4, and a hex digest are withheld; 14 //! - a lookalike that is not numeric and not `@` stays (`passwЗrd`), because this rule has no character list. 15 16 use std::collections::HashSet; 17 use std::sync::{LazyLock, OnceLock}; 18 use unicode_normalization::UnicodeNormalization; 19 20 pub const SECRET: &str = "[secret withheld]"; 21 pub const EMAIL: &str = "[email withheld]"; 22 23 static OWN_EMAILS: OnceLock> = OnceLock::new(); 24 25 /// Which branch of the rule to turn off. Production passes `None`. 26 #[derive(Clone, Copy, PartialEq, Eq)] 27 enum Mutant { 28 None, 29 NoNfkc, 30 SplitInside, 31 NoAllowlist, 32 /// NFKC the whole string before splitting, so a space created by normalization splits a token. 33 SplitNormalized, 34 /// A hyphenated name may contain digit segments of up to five digits, with no total cap. 35 NoHyphenCap, 36 /// A density suffix ignores whether its local part would be withheld. 37 DensityIgnoresLocal, 38 /// Any colon before `@` counts as userinfo, including a scheme colon. 39 SchemeColon, 40 /// A digit segment must be one character, so `COVID-19` is withheld. 41 SingleDigitHyphen, 42 /// A density suffix may contain any run of digits. 43 WideDensity, 44 /// Leave Unicode format characters in place. 45 KeepFormat, 46 /// Any single-colon `label:label@ipv4` is a credential. 47 LooseCredential, 48 /// A colon anywhere and an IPv4 after the last `@` keeps the whole token. 49 LooseTail, 50 /// The one-word number may be six digits, so `call-415555` is kept. 51 WordNumberSix, 52 /// A density suffix may use a capital `X`. 53 DensityCapitalX, 54 /// An all-letter hostname counts as IPv4. 55 LetterHost, 56 } 57 58 pub fn set_own_emails(addresses: Vec) -> Result<(), &'static str> { 59 let set = addresses.into_iter().map(|a| a.trim().to_ascii_lowercase()).filter(|a| !a.is_empty()).collect(); 60 OWN_EMAILS.set(set).map_err(|_| "own email list already initialized") 61 } 62 63 pub fn redact(input: &str, own: &HashSet) -> String { 64 apply(input, own, Mutant::None) 65 } 66 67 fn apply(input: &str, own: &HashSet, mutant: Mutant) -> String { 68 let source = if mutant == Mutant::SplitInside || mutant == Mutant::KeepFormat { input.to_owned() } else { strip_format(input) }; 69 if mutant == Mutant::SplitNormalized { 70 let text: String = source.nfkc().collect(); 71 return split_tokens(&text, own, Mutant::None); 72 } 73 split_tokens(&source, own, mutant) 74 } 75 76 fn strip_format(input: &str) -> String { 77 if !input.chars().any(is_format) { return input.to_owned(); } 78 input.chars().filter(|c| !is_format(*c)).collect() 79 } 80 81 fn is_format(c: char) -> bool { 82 let cp = c as u32; 83 let ranges = format_ranges(); 84 let i = ranges.partition_point(|r| r.1 < cp); 85 i < ranges.len() && ranges[i].0 <= cp 86 } 87 88 fn format_ranges() -> &'static [(u32, u32)] { 89 static RANGES: OnceLock> = OnceLock::new(); 90 RANGES.get_or_init(|| { 91 let mut ranges = Vec::new(); 92 for line in include_str!("../data/DerivedGeneralCategory.txt").lines() { 93 let body = line.split('#').next().unwrap_or("").trim(); 94 if body.is_empty() { continue; } 95 let mut fields = body.split(';'); 96 let Some(range) = fields.next() else { continue; }; 97 let Some(cat) = fields.next() else { continue; }; 98 if cat.trim() != "Cf" { continue; } 99 let range = range.trim(); 100 let (start, end) = match range.split_once("..") { 101 Some((a, b)) => (u32::from_str_radix(a, 16).unwrap(), u32::from_str_radix(b, 16).unwrap()), 102 None => { let v = u32::from_str_radix(range, 16).unwrap(); (v, v) } 103 }; 104 ranges.push((start, end)); 105 } 106 ranges 107 }) 108 } 109 110 /// Boundaries are the original characters. NFKC then runs on the whole token, so a 111 /// space created inside one character's expansion stays inside it, and marks still compose. 112 fn split_tokens(input: &str, own: &HashSet, mutant: Mutant) -> String { 113 let mut out = String::new(); 114 let mut token = String::new(); 115 for c in input.chars() { 116 if boundary(c, mutant) { 117 judge_raw(&token, own, mutant, &mut out); 118 token.clear(); 119 if mutant == Mutant::NoNfkc { out.push(c); } else { out.extend(c.nfkc()); } 120 } else { 121 token.push(c); 122 } 123 } 124 judge_raw(&token, own, mutant, &mut out); 125 out 126 } 127 128 fn judge_raw(raw: &str, own: &HashSet, mutant: Mutant, out: &mut String) { 129 if raw.is_empty() { return; } 130 if mutant == Mutant::NoNfkc { 131 judge_token(raw, own, mutant, out); 132 return; 133 } 134 let normalized: String = raw.nfkc().collect(); 135 judge_token(&normalized, own, mutant, out); 136 } 137 138 /// Unicode White_Space, from `char::is_whitespace`. `SplitInside` also breaks on 139 /// anything outside letters, digits, and the ASCII marks a kept shape uses, which 140 /// is how a format character or a mark used to publish the two halves. 141 fn boundary(c: char, mutant: Mutant) -> bool { 142 if c.is_whitespace() { return true; } 143 if mutant != Mutant::SplitInside { return false; } 144 !(c.is_alphanumeric() || matches!(c, '@' | '.' | '-' | '_' | '+' | ':' | '/' | '\'' | '"')) 145 } 146 147 fn judge_token(token: &str, own: &HashSet, mutant: Mutant, out: &mut String) { 148 if token.is_empty() { return; } 149 let (prefix, core, suffix) = trim_edge(token); 150 if core.is_empty() { out.push_str(token); return; } 151 if mutant != Mutant::NoAllowlist && allowed(core, own, mutant) { out.push_str(token); return; } 152 if has_sep(core) { 153 out.push_str(prefix); 154 out.push_str(&render_parts(core, mutant)); 155 out.push_str(suffix); 156 return; 157 } 158 match decide_flat(core, mutant) { 159 Some(mark) => { 160 out.push_str(prefix); 161 out.push_str(mark); 162 out.push_str(suffix); 163 } 164 None => out.push_str(token), 165 } 166 } 167 168 fn trim_edge(token: &str) -> (&str, &str, &str) { 169 let mut chars = token.char_indices(); 170 let mut start = 0; 171 for (i, c) in chars.by_ref() { 172 if !edge_mark(c) { start = i; break; } 173 start = token.len(); 174 } 175 if start == token.len() { return ("", token, ""); } 176 let mut end = token.len(); 177 for (i, c) in token.char_indices().rev() { 178 if !edge_mark(c) { break; } 179 end = i; 180 } 181 if end < start { end = start; } 182 (&token[..start], &token[start..end], &token[end..]) 183 } 184 185 fn edge_mark(c: char) -> bool { 186 matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>' | '"' | '\'') 187 } 188 189 fn decide_flat(core: &str, mutant: Mutant) -> Option<&'static str> { 190 if core.is_empty() { return None; } 191 if mutant != Mutant::NoAllowlist && (short_number(core) || version(core) || hyphen_name(core, mutant)) { return None; } 192 if core.chars().any(digit) { return Some(SECRET); } 193 None 194 } 195 196 fn allowed(token: &str, own: &HashSet, mutant: Mutant) -> bool { 197 short_number(token) || version(token) || hyphen_name(token, mutant) || density(token, mutant) || owned(token, own) || credential(token, mutant) 198 } 199 200 /// `is_numeric` is the Unicode number categories. `to_digit` is ASCII only, so an Nd 201 /// such as U+0661 would otherwise not count. NFKC has already folded compatibility digits. 202 fn digit(c: char) -> bool { c.is_numeric() } 203 204 fn short_number(token: &str) -> bool { 205 let digits = token.chars().filter(|c| digit(*c)).count(); 206 (1..6).contains(&digits) && token.chars().all(|c| !c.is_alphabetic()) 207 } 208 209 fn version(token: &str) -> bool { 210 let mut chars: Vec = token.chars().collect(); 211 let Some(last) = chars.pop() else { return false; }; 212 if chars.is_empty() || !digit(last) { return false; } 213 if chars.iter().any(|c| digit(*c)) { return false; } 214 let hyphens = chars.iter().filter(|c| **c == '-').count(); 215 hyphens <= 1 && chars.iter().all(|c| c.is_ascii_alphabetic() || *c == '-') 216 } 217 218 fn hyphen_name(token: &str, mutant: Mutant) -> bool { 219 if !token.contains('-') { return false; } 220 if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') { return false; } 221 let mut letter_segs = 0usize; 222 let mut digit_lens = Vec::new(); 223 for seg in token.split('-') { 224 if seg.is_empty() { return false; } 225 if seg.chars().all(|c| c.is_ascii_digit()) { 226 digit_lens.push(seg.len()); 227 } else if seg.chars().all(|c| c.is_ascii_alphabetic()) { 228 letter_segs += 1; 229 } else { 230 return false; 231 } 232 } 233 if letter_segs == 0 { return false; } 234 if mutant == Mutant::NoHyphenCap { return digit_lens.iter().all(|n| *n <= 5); } 235 let digits: usize = digit_lens.iter().sum(); 236 let trailing_number = token.split('-').next_back().is_some_and(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit())); 237 let word_cap = if mutant == Mutant::WordNumberSix { 6 } else { 5 }; 238 if mutant != Mutant::SingleDigitHyphen && letter_segs == 1 && digit_lens.len() == 1 && trailing_number && (2..=word_cap).contains(&digits) { 239 return true; 240 } 241 digit_lens.iter().all(|n| *n == 1) && digits <= 5 242 } 243 244 fn density(token: &str, mutant: Mutant) -> bool { 245 let Some((local, rest)) = token.split_once('@') else { return false; }; 246 if local.is_empty() || local.contains('@') { return false; } 247 let Some((name, ext)) = rest.split_once('.') else { return false; }; 248 if ext.len() < 2 || ext.contains('.') || !ext.chars().all(|c| c.is_ascii_alphabetic()) { return false; } 249 let mut chars = name.chars(); 250 let Some(last) = chars.next_back() else { return false; }; 251 if last != 'x' && !(mutant == Mutant::DensityCapitalX && last == 'X') { return false; } 252 let mut digits = 0; 253 for c in chars { 254 if !digit(c) { return false; } 255 digits += 1; 256 } 257 let bound = if mutant == Mutant::WideDensity { 1..=usize::MAX } else { 1..=2 }; 258 if !bound.contains(&digits) { return false; } 259 if local.chars().any(has_sep_char) { return false; } 260 mutant == Mutant::DensityIgnoresLocal || decide_flat(local, mutant).is_none() 261 } 262 263 fn unquote(token: &str) -> String { 264 token.chars().filter(|c| *c != '"' && *c != '\'').collect() 265 } 266 267 fn owned(token: &str, own: &HashSet) -> bool { 268 let bare = unquote(token); 269 own.iter().any(|a| a.eq_ignore_ascii_case(&bare)) 270 } 271 272 fn credential(token: &str, mutant: Mutant) -> bool { 273 if mutant == Mutant::LooseTail && token.contains("://") && loose_user_at_ip(token, mutant) { return true; } 274 bare_user_pass(token, mutant) 275 } 276 277 /// The accepted letter-only leak: `user:pass@ipv4`, not `https:jane@ipv4` or `acct:jane@ipv4`. 278 fn bare_user_pass(token: &str, mutant: Mutant) -> bool { 279 if token.contains('/') || token.contains('\\') { return false; } 280 let Some((user, rest)) = token.split_once(':') else { return false; }; 281 if rest.contains(':') { return false; } 282 let Some((pass, host)) = rest.split_once('@') else { return false; }; 283 if user.is_empty() || pass.is_empty() || host.contains('@') || !ipv4(host, mutant) { return false; } 284 if mutant == Mutant::LooseCredential || mutant == Mutant::SchemeColon { return true; } 285 user.chars().all(|c| c.is_ascii_alphabetic()) 286 && pass.chars().all(|c| c.is_ascii_alphabetic()) 287 && user.len() == pass.len() 288 && repeats_letter(pass) 289 } 290 291 fn repeats_letter(s: &str) -> bool { 292 let mut prev = '\0'; 293 for c in s.chars() { 294 if c == prev { return true; } 295 prev = c; 296 } 297 false 298 } 299 300 fn loose_user_at_ip(token: &str, mutant: Mutant) -> bool { 301 let Some((left, right)) = token.rsplit_once('@') else { return false; }; 302 if !left.contains(':') { return false; } 303 let host = right.split(['/', '?', '#']).next().unwrap_or(""); 304 let host = host.split(':').next().unwrap_or(""); 305 ipv4(host, mutant) 306 } 307 308 fn ipv4(host: &str, mutant: Mutant) -> bool { 309 if mutant == Mutant::LetterHost && !host.is_empty() && host.chars().all(|c| c.is_ascii_alphabetic()) { return true; } 310 let parts: Vec<&str> = host.split('.').collect(); 311 parts.len() == 4 && parts.iter().all(|p| (1..=3).contains(&p.len()) && p.chars().all(|c| c.is_ascii_digit())) 312 } 313 314 fn has_sep(token: &str) -> bool { token.chars().any(has_sep_char) } 315 316 fn has_sep_char(c: char) -> bool { matches!(c, '@' | ':' | '/' | '\\') } 317 318 fn render_parts(token: &str, mutant: Mutant) -> String { 319 let parts = split_parts(token); 320 let flags = email_flags(&parts); 321 let mut out = String::new(); 322 let mut i = 0; 323 while i < parts.len() { 324 if flags[i] { 325 while i < parts.len() && flags[i] { i += 1; } 326 out.push_str(EMAIL); 327 let sep = parts[i - 1].1; 328 if sep != '\0' { out.push(sep); } 329 } else { 330 let (text, sep) = &parts[i]; 331 if !text.is_empty() { 332 match decide_flat(text, mutant) { 333 Some(mark) => out.push_str(mark), 334 None => out.push_str(text), 335 } 336 } 337 if *sep != '\0' { out.push(*sep); } 338 i += 1; 339 } 340 } 341 out 342 } 343 344 fn split_parts(token: &str) -> Vec<(String, char)> { 345 let mut parts = Vec::new(); 346 let mut part = String::new(); 347 for c in token.chars() { 348 if has_sep_char(c) { 349 parts.push((std::mem::take(&mut part), c)); 350 } else { 351 part.push(c); 352 } 353 } 354 parts.push((part, '\0')); 355 parts 356 } 357 358 fn email_flags(parts: &[(String, char)]) -> Vec { 359 let mut flags = vec![false; parts.len()]; 360 for i in 0..parts.len() { 361 let before = if i == 0 { '\0' } else { parts[i - 1].1 }; 362 if before == '@' || parts[i].1 == '@' { flags[i] = true; } 363 } 364 for i in (0..parts.len()).rev() { 365 if !flags[i] { continue; } 366 let mut j = i; 367 while j > 0 && parts[j - 1].1 == ':' && !parts[j - 1].0.is_empty() { 368 flags[j - 1] = true; 369 j -= 1; 370 } 371 } 372 flags 373 } 374 375 /// The publishable form of `input`, cut to `limit` characters, or None when nothing is left. 376 pub fn public_text(input: &str, limit: usize) -> Option { 377 static EMPTY: LazyLock> = LazyLock::new(HashSet::new); 378 let own = OWN_EMAILS.get().unwrap_or(&EMPTY); 379 let clean: String = input.chars().filter(|&c| !c.is_control() || matches!(c, '\n' | '\r' | '\t')).collect(); 380 let text = redact(&clean, own); 381 let text = text.trim(); 382 if text.is_empty() { None } else { Some(cut(text, limit)) } 383 } 384 385 /// `text` cut to `limit` characters, never inside a marker. 386 pub fn cut(text: &str, limit: usize) -> String { 387 let Some((mut byte, _)) = text.char_indices().nth(limit) else { return text.to_owned(); }; 388 for marker in [SECRET, EMAIL] { 389 if let Some((i, _)) = text.match_indices(marker).find(|&(i, _)| i < byte && byte < i + marker.len()) { byte = i; } 390 } 391 text[..byte].trim_end().to_owned() 392 } 393 394 pub fn label(input: &str, fallback: &str) -> String { public_text(input, 180).unwrap_or_else(|| fallback.to_owned()) } 395 396 #[cfg(test)] 397 mod tests { 398 use super::*; 399 use sha2::{Digest, Sha256}; 400 use unicode_normalization::UnicodeNormalization; 401 402 fn own() -> HashSet { ["owner@example.org".to_owned()].into_iter().collect() } 403 fn clean(s: &str) -> String { redact(s, &own()) } 404 fn gone(input: &str, secret: &str) { 405 let out = clean(input); 406 assert!(!out.contains(secret), "{input} -> {out}"); 407 assert!(out.contains(SECRET) || out.contains(EMAIL), "{input} -> {out}"); 408 } 409 410 #[test] 411 fn shape_withholds_the_review_cases() { 412 let hex = "`9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60`"; 413 let pairs = vec![ 414 ("the password is p4ssw0rd".to_owned(), format!("the password is {SECRET}")), 415 ("password=s3cr3t".to_owned(), SECRET.to_owned()), 416 ("the token is t0k3n".to_owned(), format!("the token is {SECRET}")), 417 ("pass: 123456".to_owned(), format!("pass: {SECRET}")), 418 ("token: 123-456".to_owned(), format!("token: {SECRET}")), 419 ("the password is 415-555-0199".to_owned(), format!("the password is {SECRET}")), 420 ("the k\u{0435}y is Hunter2xyz".to_owned(), format!("the k\u{0435}y is {SECRET}")), 421 ("\u{FF50}\u{FF41}\u{FF53}\u{FF53}\u{FF57}\u{FF4F}\u{FF52}\u{FF44}: Hunter2xyz".to_owned(), format!("password: {SECRET}")), 422 ("passwo\u{0300}rd: Hunter2xyz".to_owned(), format!("passw\u{00F2}rd: {SECRET}")), 423 ("the password is Hunter\u{FF12}xyz".to_owned(), format!("the password is {SECRET}")), 424 ("I reset the password. Hunter2xyz is the new one.".to_owned(), format!("I reset the password. {SECRET} is the new one.")), 425 ("The password is below.\n\nHunter2xyz".to_owned(), format!("The password is below.\n\n{SECRET}")), 426 (format!("The private key is ready. {hex}"), format!("The private key is ready. {SECRET}")), 427 ("sk-proj-abcDEF\n1234567890abcdEF".to_owned(), format!("sk-proj-abcDEF\n{SECRET}")), 428 ("sk-proj-abcDEF 1234567890abcdEF".to_owned(), format!("sk-proj-abcDEF {SECRET}")), 429 ("use SK-PROJ-ABCDEF1234567890ABCDEF1234567890 now".to_owned(), format!("use {SECRET} now")), 430 ("use akiaiosfodnn7example in the client".to_owned(), format!("use {SECRET} in the client")), 431 ("use xai-abcdefghijklmnopqrstuvwxyz0123456789 now".to_owned(), format!("use {SECRET} now")), 432 ("eyJhbGciOiJIUzI1NiJ9.\neyJzdWIiOiIxMjM0In0.\nSflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV".to_owned(), format!("{SECRET}.\n{SECRET}.\n{SECRET}")), 433 ("https://example.com/cb?sig=hunter2xyz&x=1".to_owned(), format!("https://example.com/{SECRET}")), 434 ("https://example.com/cb?sig=Zx9Qw3Er7Ty1Ui5O".to_owned(), format!("https://example.com/{SECRET}")), 435 ("planted sk-ant-api03-FAKEplantedKEY0123456789 in the reply".to_owned(), format!("planted {SECRET} in the reply")), 436 ]; 437 for (input, expect) in pairs { 438 assert_eq!(clean(&input), expect, "{input}"); 439 } 440 } 441 442 #[test] 443 fn shape_keeps_ordinary_prose() { 444 for keep in [ 445 "The zip code is 94043.", 446 "The error code is 4041.", 447 "The key insight from 2024 still holds.", 448 "Seed 10000 rows and continue.", 449 "Auth: the client is JavaScript.", 450 "Auth: login flow now uses sessions", 451 "The code uses UTF-8, IPv6 and OAuth2, and the cache key changed in 2024.", 452 "The key is \"version 2 of the plan\".", 453 "I fixed the auth bug in \"module 2\" today.", 454 "image@2x.png", 455 "Use file icon@2x.png in the build.", 456 "The site code is at 1600 Amphitheatre Parkway, Mountain View, CA 94043.", 457 "primary key: id", 458 "the password is letmein", 459 "the password is correct horse battery staple", 460 "the password is hunter2", 461 "gpt-6-astra", 462 "claude-opus-5-5", 463 "dXNlcjpwYXNz", 464 "aHVudGVyMg==", 465 "4242 4242 4242 4242", 466 "+1 415 555 0199", 467 "user:pass@10.1.2.3", 468 "passw\u{0417}rd", 469 "jane@2x.com", 470 ] { 471 assert_eq!(clean(keep), keep, "{keep}"); 472 } 473 } 474 475 #[test] 476 fn a_sha256_digest_is_the_same_shape_as_a_hex_key_and_is_withheld() { 477 let line = "commit `657e670086659a07d6e5ce28a407831174be5c02` sha256 `9dbb932f967946df731375159545401d011c6c051fbed4c8d1b83c6bb4fbd0dd`"; 478 let out = clean(line); 479 assert!(!out.contains("`9dbb932f967946df731375159545401d011c6c051fbed4c8d1b83c6bb4fbd0dd`"), "{out}"); 480 assert!(!out.contains("`657e670086659a07d6e5ce28a407831174be5c02`"), "{out}"); 481 assert!(!out.contains("sha256"), "{out}"); 482 assert!(out.starts_with("commit "), "{out}"); 483 } 484 485 #[test] 486 fn other_peoples_emails_are_withheld_and_the_operators_are_kept() { 487 assert_eq!(clean("I wrote to someone@example.net and copied Owner@Example.org."), format!("I wrote to {EMAIL} and copied Owner@Example.org.")); 488 assert_eq!(redact("mail owner@example.org", &HashSet::new()), format!("mail {EMAIL}")); 489 assert_eq!(clean("image@2x.png"), "image@2x.png"); 490 } 491 492 #[test] 493 fn a_date_and_a_split_digit_run_show_the_limits() { 494 assert_eq!(clean("shipped on 2024-11-15"), format!("shipped on {SECRET}")); 495 assert_eq!(clean("123\u{200B}456"), SECRET); 496 assert_eq!(clean("v1.2.3"), SECRET); 497 assert_eq!(clean("x86_64"), SECRET); 498 assert_eq!(clean("sha256"), SECRET); 499 gone("\u{0455}3\u{0441}\u{0445}3\u{0430}", "\u{0455}"); 500 } 501 502 #[test] 503 fn mutants_each_fail_one_case() { 504 let own = own(); 505 let cases = [ 506 (Mutant::SplitInside, "123\u{17B5}456", SECRET.to_owned(), "123\u{17B5}456".to_owned()), 507 (Mutant::NoAllowlist, "icon@2x.png", "icon@2x.png".to_owned(), EMAIL.to_owned()), 508 (Mutant::NoNfkc, "jane\u{FF20}example.com", EMAIL.to_owned(), "jane\u{FF20}example.com".to_owned()), 509 (Mutant::SplitNormalized, "123\u{00A8}456", SECRET.to_owned(), "123 \u{0308}456".to_owned()), 510 (Mutant::NoHyphenCap, "call-415-555-0199", SECRET.to_owned(), "call-415-555-0199".to_owned()), 511 (Mutant::DensityIgnoresLocal, "`4155550199`@2x.com", EMAIL.to_owned(), "`4155550199`@2x.com".to_owned()), 512 (Mutant::SchemeColon, "mailto:jane@10.1.2.3", EMAIL.to_owned(), "mailto:jane@10.1.2.3".to_owned()), 513 (Mutant::SingleDigitHyphen, "COVID-19", "COVID-19".to_owned(), SECRET.to_owned()), 514 (Mutant::WideDensity, "jane@4155550199x.com", EMAIL.to_owned(), "jane@4155550199x.com".to_owned()), 515 (Mutant::KeepFormat, "icon@2\u{200B}x.png", "icon@2x.png".to_owned(), EMAIL.to_owned()), 516 (Mutant::LooseCredential, "https:jane@8.8.8.8", EMAIL.to_owned(), "https:jane@8.8.8.8".to_owned()), 517 (Mutant::LooseTail, "https://example.com/mailto:jane@10.1.2.3", "https://example.com/[email withheld]".to_owned(), "https://example.com/mailto:jane@10.1.2.3".to_owned()), 518 (Mutant::WordNumberSix, "call-415555", SECRET.to_owned(), "call-415555".to_owned()), 519 (Mutant::DensityCapitalX, "icon@2X.png", EMAIL.to_owned(), "icon@2X.png".to_owned()), 520 (Mutant::LetterHost, "user:pass@localhost", EMAIL.to_owned(), "user:pass@localhost".to_owned()), 521 ]; 522 for (mutant, input, real, broken) in cases { 523 assert_eq!(apply(input, &own, Mutant::None), real, "rule {input}"); 524 assert_eq!(apply(input, &own, mutant), broken, "mutant {input}"); 525 assert_ne!(real, broken, "mutant did not change {input}"); 526 } 527 } 528 529 #[test] 530 fn a_space_created_by_nfkc_does_not_split_the_token() { 531 assert_eq!(clean("415\u{00A8}555\u{00A8}0199"), SECRET); 532 assert_eq!(clean("jane@2x.co\u{00A8}.uk"), EMAIL); 533 assert_eq!(clean("123\u{00A8}456"), SECRET); 534 assert_eq!(clean("someone@exam\u{00A8}ple.com"), EMAIL); 535 let mut splitters = 0u32; 536 for cp in 0..=0x10FFFF { 537 let Some(c) = char::from_u32(cp) else { continue; }; 538 if c.is_whitespace() { continue; } 539 let norm: String = c.nfkc().collect(); 540 if !norm.chars().any(char::is_whitespace) { continue; } 541 splitters += 1; 542 assert_eq!(clean(&format!("123{c}456")), SECRET, "U+{cp:04X}"); 543 assert_eq!(clean(&format!("someone@exam{c}ple.com")), EMAIL, "U+{cp:04X}"); 544 } 545 assert!(splitters > 0, "no non-whitespace character expands to a space"); 546 } 547 548 #[test] 549 fn a_letter_prefix_does_not_keep_a_long_digit_run() { 550 for leak in [ 551 "call-415-555-0199", 552 "x-415-555-0199", 553 "call-1-800-555-0199", 554 "ssn-123-45-6789", 555 "zip-94043-1234", 556 "card-4242-4242-4242-4242", 557 "sk-ant-api-03-FAKEplantedKEY", 558 "sk-live-abc-123", 559 ] { 560 assert_eq!(clean(leak), SECRET, "{leak}"); 561 } 562 assert_eq!(clean("gpt-6-astra"), "gpt-6-astra"); 563 assert_eq!(clean("claude-opus-5-5"), "claude-opus-5-5"); 564 for keep in ["COVID-19", "UTF-16", "Win-11", "ISO-8601", "rfc-1918"] { 565 assert_eq!(clean(keep), keep, "{keep}"); 566 } 567 } 568 569 #[test] 570 fn a_density_suffix_does_not_keep_a_local_part_the_rule_withholds() { 571 for leak in ["`4155550199`@2x.com", "user:s3cr3t@2x.com", "sk-live-abc123@2x.com"] { 572 assert_eq!(clean(leak), EMAIL, "{leak}"); 573 } 574 assert_eq!(clean("https://user:s3cr3t@2x.com"), format!("https://{EMAIL}")); 575 for leak in ["jane@4155550199x.com", "a@123456x.com", "hunter2@4155550199x.com", "jane@4242424242424242x.com"] { 576 assert_eq!(clean(leak), EMAIL, "{leak}"); 577 assert!(!clean(leak).contains("415") && !clean(leak).contains("4242") && !clean(leak).contains("123456"), "{leak}"); 578 } 579 assert_eq!(clean("icon@2x.png"), "icon@2x.png"); 580 assert_eq!(clean("image@2x.png"), "image@2x.png"); 581 assert_eq!(clean("jane@2x.com"), "jane@2x.com"); 582 assert_eq!(clean("icon@2X.png"), EMAIL); 583 } 584 585 #[test] 586 fn a_scheme_colon_is_not_userinfo() { 587 assert_eq!(clean("mailto:jane@10.1.2.3"), EMAIL); 588 assert_eq!(clean("https://jane@8.8.8.8"), format!("https://{EMAIL}")); 589 assert_eq!(clean("https://jane@10.1.2.3"), format!("https://{EMAIL}")); 590 assert_eq!(clean("https://admin:s3cr3t@10.0.0.8/v1"), format!("https://{EMAIL}/v1")); 591 assert_eq!(clean("user:pass@10.1.2.3"), "user:pass@10.1.2.3"); 592 assert_eq!(clean("postgres://app:s3cr3t@127.0.0.1:5432/app"), format!("postgres://{EMAIL}:5432/app")); 593 assert!(!clean("postgres://app:s3cr3t@localhost:5432/app").contains("s3cr3t")); 594 assert_eq!(clean("user:pass@localhost"), EMAIL); 595 } 596 597 #[test] 598 fn digit_domains_are_emails_and_density_suffixes_are_not() { 599 for addr in [ 600 "jane@o2.co.uk", 601 "alerts@s3.amazonaws.com", 602 "bot@ec2-1-2-3-4.compute.amazonaws.com", 603 "user@mail2.example.com", 604 "noreply@s3.amazonaws.com", 605 "noreply@o2.co.uk", 606 ] { 607 assert_eq!(clean(addr), EMAIL, "{addr}"); 608 } 609 assert_eq!(clean("icon@2x.png"), "icon@2x.png"); 610 assert_eq!(clean("image@2x.png"), "image@2x.png"); 611 assert_eq!(clean("jane@2x.com"), "jane@2x.com"); 612 assert_eq!(clean("Owner@Example.org"), "Owner@Example.org"); 613 } 614 615 #[test] 616 fn unicode_digits_and_confusable_letters_are_withheld() { 617 assert_eq!(clean("\u{0661}\u{0662}\u{0663}\u{0664}\u{0665}\u{0666}"), SECRET); 618 assert_eq!(clean("s\u{0663}cr\u{0663}t"), SECRET); 619 assert_eq!(clean("passw\u{0417}rd"), "passw\u{0417}rd"); 620 assert_eq!(clean("someone@ex\u{0417}mple.com"), EMAIL); 621 } 622 623 #[test] 624 fn round3_dots_marks_letters_and_a_leading_plus() { 625 assert_eq!(clean("jane@o2.co.uk..."), format!("{EMAIL}...")); 626 assert_eq!(clean("See jane@o2.co.uk... thanks"), format!("See {EMAIL}... thanks")); 627 assert_eq!(clean("someone@example.net\u{2026}"), format!("{EMAIL}...")); 628 assert_eq!(clean("The zip code is 94043."), "The zip code is 94043."); 629 assert_eq!(clean("123\u{E0100}456"), SECRET); 630 assert_eq!(clean("123\u{180B}456"), SECRET); 631 assert_eq!(clean("someone@exam\u{E0100}ple.com"), EMAIL); 632 assert_eq!(clean("user@ex\u{00F8}mple.com"), EMAIL); 633 assert_eq!(clean("info@k\u{00F8}benhavn.dk"), EMAIL); 634 assert_eq!(clean("123\u{00F8}456"), SECRET); 635 assert_eq!(clean("jos\u{00E9}@example.com"), EMAIL); 636 assert_eq!(clean("user@ex\u{00E1}mple.com"), EMAIL); 637 assert_eq!(clean("+`14155550199`"), SECRET); 638 assert_eq!(clean("+1-415-555-0199"), SECRET); 639 assert_eq!(clean("415-555-0199"), SECRET); 640 } 641 642 #[test] 643 fn round4_marks_phones_dots_quotes_and_ideographic_stops() { 644 assert_eq!(clean("123\u{17B5}456"), SECRET); 645 assert_eq!(clean("someone@exam\u{17B5}ple.com"), EMAIL); 646 assert_eq!(clean("123\u{FFF9}456"), SECRET); 647 assert_eq!(clean("someone@exam\u{1D173}ple.com"), EMAIL); 648 assert_eq!(clean("someone@exam\u{20DD}ple.com"), EMAIL); 649 assert_eq!(clean("someone@exam\u{070F}ple.com"), EMAIL); 650 assert_eq!(clean("415.555.0199"), SECRET); 651 assert_eq!(clean("+1.415.555.0199"), SECRET); 652 assert_eq!(clean("415\u{2024}555\u{2024}0199"), SECRET); 653 assert_eq!(clean("jane@example..com"), EMAIL); 654 assert_eq!(clean("jane@ex..ample.com"), EMAIL); 655 assert_eq!(clean("jane@.example.com"), EMAIL); 656 assert_eq!(clean("jane@o2.co.uk...thanks"), EMAIL); 657 assert_eq!(clean("someone@example.net\u{2026}thanks"), EMAIL); 658 assert_eq!(clean("See jane@o2.co.uk...thanks"), format!("See {EMAIL}")); 659 assert_eq!(clean("\"jane.doe\"@example.com"), format!("\"{EMAIL}")); 660 assert_eq!(clean("jane@example\u{3002}com"), EMAIL); 661 assert_eq!(clean("jane\u{FF20}example\u{FF61}com"), EMAIL); 662 assert_eq!(clean("(415) 555-0199"), format!("(415) {SECRET}")); 663 assert_eq!(clean("(415)555-0199"), format!("({SECRET}")); 664 assert_eq!(clean("icon@2x.png"), "icon@2x.png"); 665 assert_eq!(clean("jane@2x.com"), "jane@2x.com"); 666 assert_eq!(clean("user:pass@10.1.2.3"), "user:pass@10.1.2.3"); 667 } 668 669 #[test] 670 fn every_format_character_and_combining_mark_stays_inside_the_token() { 671 let mut format = Vec::new(); 672 let mut marks = Vec::new(); 673 for line in include_str!("../data/DerivedGeneralCategory.txt").lines() { 674 let body = line.split('#').next().unwrap_or("").trim(); 675 if body.is_empty() { continue; } 676 let mut fields = body.split(';'); 677 let Some(range) = fields.next() else { continue; }; 678 let Some(cat) = fields.next() else { continue; }; 679 let cat = cat.trim(); 680 let keep = match cat { 681 "Cf" => &mut format, 682 "Mn" | "Mc" | "Me" => &mut marks, 683 _ => continue, 684 }; 685 let range = range.trim(); 686 let (start, end) = match range.split_once("..") { 687 Some((a, b)) => (u32::from_str_radix(a, 16).unwrap(), u32::from_str_radix(b, 16).unwrap()), 688 None => { let v = u32::from_str_radix(range, 16).unwrap(); (v, v) } 689 }; 690 for cp in start..=end { 691 if let Some(c) = char::from_u32(cp) { keep.push(c); } 692 } 693 } 694 let digest = Sha256::digest(include_bytes!("../data/DerivedGeneralCategory.txt")); 695 let sha = "`d6b151d2d40ee9b1876d26f417980f45ffae47b6055ccf7203cb31f07a030f94`"; 696 assert_eq!(format!("{digest:x}"), sha); 697 assert_eq!(format.len(), 170, "Cf count pinned to DerivedGeneralCategory.txt sha {sha}"); 698 assert_eq!(marks.len(), 2580, "mark count pinned to DerivedGeneralCategory.txt sha {sha}"); 699 for c in format.iter().chain(marks.iter()) { 700 let mail = format!("someone@exam{c}ple.com"); 701 assert_eq!(clean(&mail), EMAIL, "U+{:04X} mail", u32::from(*c)); 702 let digits = format!("123{c}456"); 703 assert_eq!(clean(&digits), SECRET, "U+{:04X} digits", u32::from(*c)); 704 } 705 assert_eq!(clean("icon@2x.png"), "icon@2x.png"); 706 assert_eq!(clean("jane@2x.com"), "jane@2x.com"); 707 assert_eq!(clean("Owner@Example.org"), "Owner@Example.org"); 708 assert_eq!(clean("icon@2\u{200B}x.png"), "icon@2x.png"); 709 } 710 711 #[test] 712 fn a_scheme_colon_or_a_url_tail_does_not_keep_an_address() { 713 for leak in [ 714 "https:jane@8.8.8.8", 715 "HTTPS:jane@8.8.8.8", 716 "acct:jane@127.0.0.1", 717 "sip:jane@127.0.0.1", 718 "sips:jane@127.0.0.1", 719 "xmpp:jane@127.0.0.1", 720 "smtp:jane@127.0.0.1", 721 "imap:jane@127.0.0.1", 722 "ftp:jane@127.0.0.1", 723 "ssh:jane@127.0.0.1", 724 "git:jane@127.0.0.1", 725 "redis:jane@127.0.0.1", 726 "mysql:jane@127.0.0.1", 727 "ldap:jane@127.0.0.1", 728 "postgres:jane@127.0.0.1", 729 "mailto::jane@10.1.2.3", 730 "mailto:x:jane@10.1.2.3", 731 "mailto:jane:doe@10.1.2.3", 732 "urn:mailto:jane@10.1.2.3", 733 " {out}"); 749 assert!(out.contains(EMAIL) || out.contains(SECRET), "{leak} -> {out}"); 750 } 751 assert_eq!(clean("http:/jane@8.8.8.8"), format!("http:/{EMAIL}")); 752 assert_eq!(clean("https:\\\\jane@8.8.8.8"), format!("https:\\\\{EMAIL}")); 753 assert_eq!(clean("https://example.com/mailto:jane@10.1.2.3"), format!("https://example.com/{EMAIL}")); 754 assert_eq!(clean("https://admin:s3cr3t@10.0.0.8/415-555-0199"), format!("https://{EMAIL}/{SECRET}")); 755 assert_eq!(clean("https://admin:s3cr3t@10.0.0.8/v1"), format!("https://{EMAIL}/v1")); 756 assert_eq!(clean("user:pass@10.1.2.3"), "user:pass@10.1.2.3"); 757 assert_eq!(clean("postgres://app:s3cr3t@127.0.0.1:5432/app"), format!("postgres://{EMAIL}:5432/app")); 758 } 759 760 #[test] 761 fn a_scheme_wrapper_withholds_a_userinfo_the_bare_form_withholds() { 762 let userinfos = [ 763 "admin:s3cr3t", 764 "app:s3cr3t", 765 "dbadmin:Pr0d-DB_Passw0rd", 766 "deploy:AKIAIOSFODNN7EXAMPLE", 767 "api:", 768 "api:eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig", 769 "bot:ghp_1234567890abcdefABCDEF1234", 770 "bot:xoxb-`123456789012`-abcdefghijklmnopqrstuvwx", 771 "user:pass", 772 "jane:doe", 773 "ab:aa", 774 ]; 775 let hosts = ["10.0.0.8", "127.0.0.1", "10.1.2.3", "8.8.8.8", "localhost"]; 776 let schemes = ["https", "postgres", "http"]; 777 let tails = ["v1", "app", "repo"]; 778 for u in userinfos { 779 let pass = u.split_once(':').map(|(_, p)| p).unwrap_or(""); 780 for host in hosts { 781 let bare = format!("{u}@{host}"); 782 if clean(&bare) == bare { continue; } 783 for scheme in schemes { 784 for tail in tails { 785 let wrapped = format!("{scheme}://{u}@{host}/{tail}"); 786 let out = clean(&wrapped); 787 assert_ne!(out, wrapped, "{wrapped}"); 788 assert!(out.contains(EMAIL) || out.contains(SECRET), "{wrapped} -> {out}"); 789 if pass.len() >= 4 { assert!(!out.contains(pass), "{wrapped} -> {out}"); } 790 } 791 } 792 } 793 } 794 assert_eq!(clean("https://admin:s3cr3t@10.0.0.8/v1"), format!("https://{EMAIL}/v1")); 795 assert_eq!(clean("postgres://app:s3cr3t@127.0.0.1:5432/app"), format!("postgres://{EMAIL}:5432/app")); 796 assert_eq!(clean("https://dbadmin:Pr0d-DB_Passw0rd@10.0.0.8/v1"), format!("https://{EMAIL}/v1")); 797 assert_eq!(clean("https://deploy:AKIAIOSFODNN7EXAMPLE@10.0.0.8/v1"), format!("https://{EMAIL}/v1")); 798 assert_eq!(clean("https://api:@10.0.0.8/v1"), format!("https://{EMAIL}/v1")); 799 assert_eq!(clean("https://bot:ghp_1234567890abcdefABCDEF1234@10.1.2.3/repo"), format!("https://{EMAIL}/repo")); 800 assert_eq!(clean("https://bot:xoxb-`123456789012`-abcdefghijklmnopqrstuvwx@10.1.2.3/v1"), format!("https://{EMAIL}/v1")); 801 } 802 803 #[test] 804 fn brackets_and_quotes_stay_around_a_kept_token() { 805 for keep in ["(COVID-19)", "(UTF-16)", "\"COVID-19\""] { 806 assert_eq!(clean(keep), keep, "{keep}"); 807 } 808 assert_eq!(clean("gpt-4o"), SECRET); 809 assert_eq!(clean("python3.12"), SECRET); 810 assert_eq!(clean("Qwen3.6-35B-A3B-FP8"), SECRET); 811 assert_eq!(clean("pass-w0rd"), SECRET); 812 assert_eq!(clean("s3cr3t"), SECRET); 813 assert_eq!(clean("v1.2.3"), SECRET); 814 assert_eq!(clean("call-415555"), SECRET); 815 assert_eq!(clean("icon@2X.png"), EMAIL); 816 } 817 818 #[test] 819 fn cut_does_not_split_a_marker() { 820 assert_eq!(cut(&format!("ab {SECRET} cd"), 6), "ab"); 821 assert_eq!(public_text(" hello ", 180).as_deref(), Some("hello")); 822 assert_eq!(public_text(" ", 180), None); 823 } 824 }