Skip to main content

magi/
scrub.rs

1//! Last-line scrub for text that lands on GitHub.
2//!
3//! The prompts tell agents not to put machine- or operator-identifying data
4//! (hostnames, account names, IPs, home paths, emails, tokens) into pull
5//! requests and issues, but a prompt is advisory. [`scrub`] is the enforced
6//! half: shared rules used by the GitHub text posting gate.
7//!
8//! It scans the input left to right exactly once and pushes into a *separate*
9//! output string, so a replacement is never scanned again (compare the
10//! `blind::redact` loop, whose `[REDACTED]` contains the letters of the words it
11//! hunted). It prefers missing something to mangling ordinary prose: repo-
12//! relative paths, URLs, `std::io::Error`, `v1.2.3` and `@handle` all pass.
13
14/// The local facts worth hiding. `Default` is "nothing known", which leaves only
15/// the pattern-based rules.
16#[derive(Debug, Clone, Default)]
17pub struct Identity {
18    /// Local account name.
19    pub user: String,
20    /// Machine hostname.
21    pub host: String,
22    /// Home directory path.
23    pub home: String,
24}
25
26impl Identity {
27    /// Read the current account, host and home directory. The only I/O here.
28    pub fn current() -> Self {
29        let env = |k: &str| std::env::var(k).ok().filter(|v| !v.trim().is_empty());
30        let host = env("HOSTNAME")
31            .or_else(|| env("COMPUTERNAME"))
32            .or_else(|| {
33                std::fs::read_to_string("/etc/hostname")
34                    .ok()
35                    .map(|s| s.trim().to_owned())
36                    .filter(|s| !s.is_empty())
37            })
38            .unwrap_or_default();
39        Self {
40            user: env("USER").or_else(|| env("USERNAME")).unwrap_or_default(),
41            host,
42            home: dirs::home_dir()
43                .map(|p| p.to_string_lossy().into_owned())
44                .unwrap_or_default(),
45        }
46    }
47}
48
49const TOKEN_PREFIXES: [&str; 9] = [
50    "AKIA",
51    "github_pat_",
52    "ghp_",
53    "gho_",
54    "ghs_",
55    "ghu_",
56    "sk-",
57    "xoxb-",
58    "xoxp-",
59];
60const TOKEN_MIN_TAIL: usize = 16;
61/// Identity words shorter than this are too likely to be ordinary prose.
62const MIN_IDENTITY_WORD: usize = 3;
63
64fn is_word(c: char) -> bool {
65    c.is_ascii_alphanumeric() || c == '_' || c == '-'
66}
67
68fn is_name(c: char) -> bool {
69    c.is_alphanumeric() || matches!(c, '_' | '-' | '.')
70}
71
72fn is_email_local(c: char) -> bool {
73    c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '%' | '+' | '-')
74}
75
76/// A path component: the name run minus trailing dots, which are punctuation.
77fn name_len(s: &str) -> usize {
78    s[..run(s, is_name)].trim_end_matches('.').len()
79}
80
81/// Length in bytes of the leading run of `s` whose chars satisfy `f`.
82fn run(s: &str, f: impl Fn(char) -> bool) -> usize {
83    s.char_indices()
84        .find(|&(_, c)| !f(c))
85        .map_or(s.len(), |(i, _)| i)
86}
87
88/// Replace machine- and operator-identifying data in `text`. Pure.
89pub fn scrub(text: &str, id: &Identity) -> String {
90    let mut out = String::with_capacity(text.len());
91    let mut i = 0;
92    while i < text.len() {
93        let prev = text[..i].chars().next_back();
94        if let Some((len, rep)) = match_at(&text[i..], prev, id) {
95            out.push_str(rep);
96            i += len;
97        } else {
98            let c = text[i..].chars().next().expect("i is on a char boundary");
99            out.push(c);
100            i += c.len_utf8();
101        }
102    }
103    out
104}
105
106fn match_at(rest: &str, prev: Option<char>, id: &Identity) -> Option<(usize, &'static str)> {
107    let starts_word = prev.is_none_or(|p| !is_word(p));
108    home_path(rest, prev, id)
109        .or_else(|| {
110            starts_word
111                .then(|| {
112                    token(rest).or_else(|| credential(rest)).or_else(|| {
113                        prev.is_none_or(|c| !is_name(c))
114                            .then(|| named_identity(rest))
115                            .flatten()
116                    })
117                })
118                .flatten()
119        })
120        .or_else(|| absolute_path(rest, prev))
121        .or_else(|| {
122            prev.is_none_or(|p| !is_email_local(p))
123                .then(|| email(rest))
124                .flatten()
125        })
126        .or_else(|| {
127            prev.is_none_or(|p| !p.is_ascii_alphanumeric() && p != '.' && p != ':')
128                .then(|| ipv4(rest).or_else(|| ipv6(rest)))
129                .flatten()
130        })
131        .or_else(|| starts_word.then(|| identity_word(rest, id)).flatten())
132}
133
134/// `/Users/x`, `/home/x`, `/root`, `C:\Users\x`, `C:/Users/x` and the literal
135/// home directory, each collapsed to `~` so the repo-relative tail survives.
136fn home_path(rest: &str, prev: Option<char>, id: &Identity) -> Option<(usize, &'static str)> {
137    if prev.is_some_and(|p| p.is_ascii_alphanumeric() || matches!(p, '.' | '_' | '-' | '~')) {
138        return None;
139    }
140    if id.home.len() > 1 && rest.starts_with(id.home.as_str()) {
141        let tail = &rest[id.home.len()..];
142        if tail.chars().next().is_none_or(|c| !is_name(c)) {
143            return Some((id.home.len(), "~"));
144        }
145    }
146    for base in ["/Users/", "/home/"] {
147        if let Some(tail) = rest.strip_prefix(base) {
148            let n = name_len(tail);
149            if n > 0 {
150                return Some((base.len() + n, "~"));
151            }
152        }
153    }
154    if let Some(tail) = rest.strip_prefix("/root")
155        && tail.chars().next().is_none_or(|c| !is_word(c))
156    {
157        return Some(("/root".len(), "~"));
158    }
159    let b = rest.as_bytes();
160    if b.len() > 9
161        && b[0].is_ascii_alphabetic()
162        && b[1] == b':'
163        && matches!(b[2], b'\\' | b'/')
164        && b[3..8].eq_ignore_ascii_case(b"users")
165        && matches!(b[8], b'\\' | b'/')
166    {
167        let n = name_len(&rest[9..]);
168        if n > 0 {
169            return Some((9 + n, "~"));
170        }
171    }
172    None
173}
174
175fn token(rest: &str) -> Option<(usize, &'static str)> {
176    let prefix = TOKEN_PREFIXES.iter().find(|p| rest.starts_with(**p))?;
177    let tail = run(&rest[prefix.len()..], is_word);
178    (tail >= TOKEN_MIN_TAIL).then_some((prefix.len() + tail, "[redacted-token]"))
179}
180
181/// Explicit assignments avoid guessing whether an ordinary word is an account.
182fn named_identity(rest: &str) -> Option<(usize, &'static str)> {
183    for key in [
184        "hostname=",
185        "hostname: ",
186        "username=",
187        "username: ",
188        "user=",
189        "host=",
190    ] {
191        if rest
192            .get(..key.len())
193            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(key))
194        {
195            let n = run(&rest[key.len()..], is_name);
196            if n > 0 {
197                return Some((key.len() + n, "[redacted-identity]"));
198            }
199        }
200    }
201    let n = name_len(rest);
202    if n > 0
203        && [".local", ".internal", ".lan"].iter().any(|suffix| {
204            n.checked_sub(suffix.len())
205                .and_then(|start| rest.get(start..n))
206                .is_some_and(|tail| tail.eq_ignore_ascii_case(suffix))
207        })
208    {
209        return Some((n, "[redacted-host]"));
210    }
211    None
212}
213
214/// `"password": "value"` and `'token':'value'`: the key is quoted, so the
215/// unquoted `key=` / `key: ` forms below never match.
216fn quoted_credential(rest: &str) -> Option<(usize, &'static str)> {
217    for key in [
218        "password", "token", "api_key", "api-key", "apikey", "secret",
219    ] {
220        let Some(after) = rest
221            .get(..key.len())
222            .filter(|p| p.eq_ignore_ascii_case(key))
223            .map(|_| &rest[key.len()..])
224        else {
225            continue;
226        };
227        let Some(after_quote) = after.strip_prefix(['"', '\'']) else {
228            continue;
229        };
230        let t = after_quote.trim_start();
231        let Some(t) = t.strip_prefix([':', '=']) else {
232            continue;
233        };
234        let t = t.trim_start();
235        // A quoted value runs to its closing quote and may hold spaces or commas.
236        let n = match t.chars().next() {
237            Some(q @ ('"' | '\'')) => {
238                let inner = &t[1..];
239                let end = quoted_end(inner, q).unwrap_or(inner.len());
240                1 + end + usize::from(end < inner.len())
241            }
242            _ => run(t, |c| {
243                !c.is_whitespace() && !matches!(c, '`' | '<' | '>' | ',' | '}')
244            }),
245        };
246        let value = t;
247        if n > 0 {
248            return Some((rest.len() - value.len() + n, "[redacted-token]"));
249        }
250    }
251    None
252}
253
254/// Byte offset of the first `q` in `inner` that no backslash escapes.
255fn quoted_end(inner: &str, q: char) -> Option<usize> {
256    let mut chars = inner.char_indices();
257    while let Some((i, c)) = chars.next() {
258        if c == '\\' {
259            chars.next();
260        } else if c == q {
261            return Some(i);
262        }
263    }
264    None
265}
266
267fn credential(rest: &str) -> Option<(usize, &'static str)> {
268    if let Some(hit) = quoted_credential(rest) {
269        return Some(hit);
270    }
271    for key in [
272        "password=",
273        "token=",
274        "api_key=",
275        "api-key=",
276        "password: ",
277        "token: ",
278        "api_key: ",
279        "bearer ",
280        "password ",
281        "token ",
282        "api key ",
283    ] {
284        if rest
285            .get(..key.len())
286            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(key))
287        {
288            let tail = &rest[key.len()..];
289            let padding = tail.len() - tail.trim_start_matches([' ', '\'', '"']).len();
290            let value = &tail[padding..];
291            let n = run(value, |c| {
292                !c.is_whitespace() && !matches!(c, '`' | '<' | '>' | '"' | '\'')
293            });
294            let contextual = matches!(key, "password " | "token " | "api key ");
295            let entropy = n >= 20
296                && value[..n].bytes().any(|b| b.is_ascii_digit())
297                && value[..n].bytes().any(|b| b.is_ascii_alphabetic());
298            if n > 0 && (!contextual || entropy) {
299                return Some((key.len() + padding + n, "[redacted-token]"));
300            }
301        }
302    }
303    None
304}
305
306fn absolute_path(rest: &str, prev: Option<char>) -> Option<(usize, &'static str)> {
307    if prev.is_some_and(|c| c.is_alphanumeric() || matches!(c, '/' | ':' | '.' | '~')) {
308        return None;
309    }
310    let b = rest.as_bytes();
311    let windows =
312        b.len() > 3 && b[0].is_ascii_alphabetic() && b[1] == b':' && matches!(b[2], b'/' | b'\\');
313    // Known filesystem roots, rather than arbitrary slash-prefixed API routes.
314    let unix = [
315        "/tmp/",
316        "/private/",
317        "/var/",
318        "/etc/",
319        "/opt/",
320        "/srv/",
321        "/usr/",
322        "/mnt/",
323        "/Volumes/",
324    ]
325    .iter()
326    .any(|root| rest.starts_with(root));
327    if windows || unix {
328        let n = run(rest, |c| {
329            !c.is_whitespace() && !matches!(c, '`' | '"' | '\'' | '<' | '>')
330        });
331        return Some((n, "[redacted-path]"));
332    }
333    None
334}
335
336fn email(rest: &str) -> Option<(usize, &'static str)> {
337    let local = run(rest, is_email_local);
338    if local == 0 || !rest[local..].starts_with('@') {
339        return None;
340    }
341    let domain = &rest[local + 1..];
342    let mut end = 0;
343    let mut labels = 0;
344    loop {
345        let n = run(&domain[end..], |c| c.is_ascii_alphanumeric() || c == '-');
346        if n == 0 {
347            break;
348        }
349        end += n;
350        labels += 1;
351        if domain[end..].starts_with('.')
352            && run(&domain[end + 1..], |c| c.is_ascii_alphanumeric()) > 0
353        {
354            end += 1;
355        } else {
356            break;
357        }
358    }
359    (labels >= 2).then_some((local + 1 + end, "[redacted-email]"))
360}
361
362fn ipv4(rest: &str) -> Option<(usize, &'static str)> {
363    let mut len = 0;
364    for part in 0..4 {
365        let s = &rest[len..];
366        let n = run(s, |c| c.is_ascii_digit());
367        if n == 0 || n > 3 || s[..n].parse::<u16>().ok()? > 255 {
368            return None;
369        }
370        len += n;
371        if part < 3 {
372            if !rest[len..].starts_with('.') {
373                return None;
374            }
375            len += 1;
376        }
377    }
378    let after = &rest[len..];
379    let mut chars = after.chars();
380    match chars.next() {
381        Some(c) if c.is_ascii_alphanumeric() => return None,
382        Some('.') if chars.next().is_some_and(|c| c.is_ascii_digit()) => return None,
383        _ => {}
384    }
385    Some((len, "[redacted-ip]"))
386}
387
388fn ipv6(rest: &str) -> Option<(usize, &'static str)> {
389    let mut n = run(rest, |c| c.is_ascii_hexdigit() || c == ':');
390    // A trailing single colon is punctuation, not part of the address.
391    while n > 0 && rest[..n].ends_with(':') && !rest[..n].ends_with("::") {
392        n -= 1;
393    }
394    let cand = &rest[..n];
395    let colons = cand.matches(':').count();
396    let shaped = (cand.contains("::") && colons >= 2) || colons == 7;
397    if !shaped
398        || !cand.bytes().any(|b| b.is_ascii_digit())
399        || cand.split(':').any(|g| g.len() > 4)
400        || rest[n..]
401            .chars()
402            .next()
403            .is_some_and(|c| c.is_ascii_alphanumeric())
404    {
405        return None;
406    }
407    Some((n, "[redacted-ip]"))
408}
409
410fn identity_word(rest: &str, id: &Identity) -> Option<(usize, &'static str)> {
411    for (word, rep) in [(&id.user, "[redacted-user]"), (&id.host, "[redacted-host]")] {
412        let w = word.trim();
413        if w.len() < MIN_IDENTITY_WORD || rest.len() < w.len() || !rest.is_char_boundary(w.len()) {
414            continue;
415        }
416        if rest[..w.len()].eq_ignore_ascii_case(w)
417            && rest[w.len()..].chars().next().is_none_or(|c| !is_word(c))
418        {
419            return Some((w.len(), rep));
420        }
421    }
422    None
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428
429    fn id() -> Identity {
430        Identity {
431            user: "alice".into(),
432            host: "buildbox".into(),
433            home: "/srv/people/alice".into(),
434        }
435    }
436
437    fn s(t: &str) -> String {
438        scrub(t, &id())
439    }
440
441    #[test]
442    fn quoted_credentials_honor_escaped_quotes() {
443        let out = s(r#"{"password":"prefix\"hunter2"} tail"#);
444        assert!(!out.contains("hunter2") && !out.contains("prefix"), "{out}");
445        assert!(out.ends_with("} tail"), "{out}");
446        // An even run of backslashes leaves the quote as the closer.
447        let out = s(r#"{"password":"a\\\\"} tail"#);
448        assert!(out.ends_with("} tail") && !out.contains("a\\"), "{out}");
449        // An odd run escapes it.
450        let out = s(r#"{"password":"a\\\"hunter2"} tail"#);
451        assert!(!out.contains("hunter2"), "{out}");
452        let out = s(r#"{'token':'x\'hunter2'} tail"#);
453        assert!(!out.contains("hunter2"), "{out}");
454        let out = s(r#"{"password":"日本\"語hunter2"} tail"#);
455        assert!(!out.contains("hunter2") && !out.contains('語'), "{out}");
456        // No closing quote: everything after is removed.
457        let out = s(r#"{"password":"abc\"hunter2"#);
458        assert!(!out.contains("hunter2"), "{out}");
459    }
460
461    #[test]
462    fn home_paths_collapse_and_keep_the_tail() {
463        assert_eq!(s("see /Users/bob/src/x.rs now"), "see ~/src/x.rs now");
464        assert_eq!(s("in /home/bob-1/.config"), "in ~/.config");
465        assert_eq!(s("at C:\\Users\\Bob\\proj\\a.rs"), "at ~\\proj\\a.rs");
466        assert_eq!(s("at C:/Users/Bob/proj"), "at ~/proj");
467        assert_eq!(s("/root/x and /root."), "~/x and ~.");
468        assert_eq!(s("/srv/people/alice/wt/a"), "~/wt/a");
469    }
470
471    #[test]
472    fn emails_ips_and_tokens() {
473        assert_eq!(s("mail dev.x+y@example.co.uk!"), "mail [redacted-email]!");
474        assert_eq!(s("host 192.168.0.12:8080"), "host [redacted-ip]:8080");
475        assert_eq!(
476            s("v6 fe80::1 and ::1"),
477            "v6 [redacted-ip] and [redacted-ip]"
478        );
479        assert_eq!(s("full 2001:db8:0:0:0:0:0:1."), "full [redacted-ip].");
480        assert_eq!(
481            s("tok ghp_abcdefghijklmnopqrstuv end"),
482            "tok [redacted-token] end"
483        );
484    }
485
486    #[test]
487    fn identity_words_match_whole_words_only() {
488        assert_eq!(
489            s("by Alice on buildbox"),
490            "by [redacted-user] on [redacted-host]"
491        );
492        assert_eq!(
493            s("alicein wonderland, xbuildbox"),
494            "alicein wonderland, xbuildbox"
495        );
496    }
497
498    #[test]
499    fn ordinary_text_is_untouched() {
500        for t in [
501            "Change src/graph.rs and tests/common/mod.rs.",
502            "See https://github.com/o/r/pull/12 for #12",
503            "returns std::io::Error, or a::b, Vec::new()",
504            "released v1.2.3, version 0.41.1, 300.1.1.1",
505            "thanks @coderabbitai; at 12:34:56 it ran",
506            "/api/v1/runs; docs/home/x and ./Users/y",
507            "A plain sentence about background and motivation.",
508            "日本語のテキスト 🎉 with émoji",
509        ] {
510            assert_eq!(s(t), t);
511        }
512    }
513
514    #[test]
515    fn multibyte_input_does_not_panic_and_replacement_is_not_rescanned() {
516        assert_eq!(
517            s("C:\\日本語 and C:/日本"),
518            "[redacted-path] and [redacted-path]"
519        );
520        assert_eq!(s("é/Users/bob/é 日本 alice"), "é~/é 日本 [redacted-user]");
521        let once = s("/Users/bob 10.0.0.1 a@b.io alice");
522        assert_eq!(scrub(&once, &Identity::default()), once);
523        // A user named like the replacement text cannot loop or re-match.
524        let odd = Identity {
525            user: "redacted".into(),
526            ..Identity::default()
527        };
528        assert_eq!(scrub("redacted x", &odd), "[redacted-user] x");
529    }
530}