Skip to main content

base/text/
mod.rs

1//! UTF-8-safe string truncation.
2//!
3//! Rust's `&s[..n]` **panics** when `n` lands inside a multi-byte character.
4//! Every truncation in this codebase is expressed as a byte budget (token
5//! estimates, tool-result caps, prompt budgets), and the content being
6//! truncated is routinely non-ASCII — skill descriptions, prompts, and
7//! conversation text in this repo are frequently Chinese, where one character
8//! is 3 bytes and a cut at an arbitrary byte offset lands mid-character with
9//! probability ~2/3.
10
11pub mod frontmatter;
12
13/// Truncate `s` to at most `max_bytes` bytes, cutting at a character boundary.
14///
15/// Returns a prefix of `s` whose length is `<= max_bytes`. When `max_bytes`
16/// falls inside a multi-byte character, the cut moves *backwards* to the start
17/// of that character, so the result is never longer than requested (important
18/// when the caller is enforcing a hard budget).
19///
20/// ```
21/// # use base::text::truncate_at_char_boundary as t;
22/// assert_eq!(t("hello", 10), "hello");        // shorter than budget
23/// assert_eq!(t("hello", 3), "hel");           // ASCII cut
24/// assert_eq!(t("中文测试", 5), "中");          // byte 5 is mid-character → back off
25/// assert_eq!(t("中文测试", 6), "中文");        // byte 6 is a boundary
26/// ```
27pub fn truncate_at_char_boundary(s: &str, max_bytes: usize) -> &str {
28    if s.len() <= max_bytes {
29        return s;
30    }
31    let mut end = max_bytes;
32    while end > 0 && !s.is_char_boundary(end) {
33        end -= 1;
34    }
35    &s[..end]
36}
37
38/// Truncate a string at `max` chars, appending `marker` when truncated.
39pub fn truncate_chars(s: &str, max: usize, marker: &str) -> String {
40    if s.chars().count() <= max {
41        s.to_string()
42    } else {
43        let head: String = s.chars().take(max).collect();
44        format!("{head}{marker}")
45    }
46}
47
48/// `text` with the credentials a log line could carry masked: `sk-…` style
49/// keys, the word after `Bearer` / `Basic`, and the value of any `name=value`
50/// whose name says token, key, secret, password or auth (URL query strings
51/// and `--flag=value` arguments included).
52pub fn scrub_secrets(text: &str) -> String {
53    const MASK: &str = "***";
54    const SECRET_NAMES: &[&str] = &["token", "key", "secret", "passw", "auth", "credential"];
55    let is_boundary =
56        |c: char| c.is_whitespace() || matches!(c, '"' | '\'' | '&' | '?' | ',' | ';');
57    let mut out = String::with_capacity(text.len());
58    let mut after_scheme = false;
59    let mut rest = text;
60    while !rest.is_empty() {
61        let end = rest.find(is_boundary).unwrap_or(rest.len());
62        let (word, tail) = rest.split_at(end);
63        let masked = if word.is_empty() {
64            None
65        } else if after_scheme {
66            Some(MASK.to_string())
67        } else if let Some((name, value)) = word.split_once('=') {
68            let lower = name.to_ascii_lowercase();
69            (!value.is_empty() && SECRET_NAMES.iter().any(|n| lower.contains(n)))
70                .then(|| format!("{name}={MASK}"))
71        } else if (word.starts_with("sk-") || word.starts_with("sk_")) && word.len() >= 10 {
72            Some(MASK.to_string())
73        } else {
74            None
75        };
76        if !word.is_empty() {
77            after_scheme = matches!(word, "Bearer" | "bearer" | "Basic" | "basic");
78        }
79        out.push_str(masked.as_deref().unwrap_or(word));
80        let sep_len = tail.chars().next().map_or(0, char::len_utf8);
81        out.push_str(&tail[..sep_len]);
82        rest = &tail[sep_len..];
83    }
84    out
85}
86
87/// [`scrub_secrets`], and the password of each URL's userinfo
88/// (`https://user:***@host`).
89pub fn scrub_url(text: &str) -> String {
90    let scrubbed = scrub_secrets(text);
91    let mut out = String::with_capacity(scrubbed.len());
92    let mut rest = scrubbed.as_str();
93    while let Some(at) = rest.find("://") {
94        let (head, tail) = rest.split_at(at + 3);
95        out.push_str(head);
96        let end = tail
97            .find(|c: char| matches!(c, '/' | '?' | '#') || c.is_whitespace())
98            .unwrap_or(tail.len());
99        let (authority, after) = tail.split_at(end);
100        match authority
101            .rsplit_once('@')
102            .and_then(|(userinfo, host)| Some((userinfo.split_once(':')?.0, host)))
103        {
104            Some((user, host)) => out.push_str(&format!("{user}:***@{host}")),
105            None => out.push_str(authority),
106        }
107        rest = after;
108    }
109    out.push_str(rest);
110    out
111}
112
113#[cfg(test)]
114mod tests {
115    use super::truncate_at_char_boundary as t;
116
117    #[test]
118    fn shorter_than_budget_is_returned_whole() {
119        assert_eq!(t("hello", 10), "hello");
120        assert_eq!(t("中文", 100), "中文");
121        assert_eq!(t("", 0), "");
122    }
123
124    #[test]
125    fn ascii_cuts_exactly_at_the_budget() {
126        assert_eq!(t("hello world", 5), "hello");
127    }
128
129    /// Every byte offset inside a multi-byte string must be safe, not just the
130    /// boundaries.
131    #[test]
132    fn every_byte_offset_of_a_multibyte_string_is_safe() {
133        let s = "中文测试abc混合デ";
134        for n in 0..=s.len() + 4 {
135            let out = t(s, n);
136            assert!(
137                out.len() <= n.min(s.len()),
138                "n={n} produced {} bytes",
139                out.len()
140            );
141            assert!(s.starts_with(out), "n={n} produced a non-prefix");
142        }
143    }
144
145    #[test]
146    fn cut_moves_backwards_never_forwards() {
147        // byte 5 is inside the second 3-byte char, so we must fall back to 3.
148        assert_eq!(t("中文测试", 5), "中");
149        assert_eq!(t("中文测试", 6), "中文");
150        // A budget of 0, or one smaller than the first character, yields "".
151        assert_eq!(t("中文", 0), "");
152        assert_eq!(t("中文", 2), "");
153    }
154
155    #[test]
156    fn combining_marks_and_emoji_survive() {
157        let s = "e\u{301}👨‍👩‍👧"; // combining acute + ZWJ family sequence
158        for n in 0..=s.len() {
159            let out = t(s, n);
160            assert!(s.starts_with(out));
161        }
162    }
163
164    #[test]
165    fn truncate_long_string() {
166        let s: String = "x".repeat(3000);
167        let t = super::truncate_chars(&s, 100, "[truncated]");
168        assert_eq!(t.chars().count(), 100 + "[truncated]".chars().count());
169        assert!(t.ends_with("[truncated]"));
170    }
171
172    #[test]
173    fn truncate_short_string_is_passthrough() {
174        let t = super::truncate_chars("hi", 10, "[truncated]");
175        assert_eq!(t, "hi");
176    }
177
178    #[test]
179    fn scrub_secrets_masks_keys_bearers_and_secret_named_values() {
180        use super::scrub_secrets;
181        let line = "got sk-abcdef1234567890 and Authorization: Bearer abc.def \
182                    from https://x.test/cb?token=hunter2&page=2 --api-key=zzz";
183        let out = scrub_secrets(line);
184        for leaked in ["abcdef1234567890", "abc.def", "hunter2", "zzz"] {
185            assert!(!out.contains(leaked), "{leaked} in {out}");
186        }
187        assert!(
188            out.contains("page=2") && out.contains("https://x.test/cb"),
189            "{out}"
190        );
191    }
192}