Skip to main content

ai_usagebar/
display.rs

1//! Sanitization for text that crosses an untrusted data boundary into a UI.
2//!
3//! Vendor responses and cached diagnostics are data, not terminal programs.
4//! Keep ordinary Unicode and line breaks, but remove terminal control bytes
5//! before the text is persisted or handed to Pango/ratatui/ANSI renderers.
6
7/// Generous bound for one remote label or diagnostic field. Legitimate values
8/// are normally a few dozen characters; the cap prevents a valid-but-hostile
9/// JSON response from turning one UI cell or cache sidecar into megabytes.
10pub const MAX_UNTRUSTED_FIELD_CHARS: usize = 4 * 1024;
11
12/// Strip terminal control characters while preserving readable line layout.
13///
14/// Newlines are safe and useful in diagnostics. Tabs and carriage returns are
15/// normalized to spaces; every other Unicode control character (including ESC,
16/// BEL, DEL, and C1 controls) is removed. Invisible bidirectional markers and
17/// overrides are also removed so an untrusted label cannot visually reorder
18/// neighboring UI text. The result is capped by character, not byte, so UTF-8
19/// is never split.
20pub fn sanitize_untrusted_field(value: &str) -> String {
21    value
22        .chars()
23        .filter_map(|ch| match ch {
24            '\n' => Some('\n'),
25            '\t' | '\r' => Some(' '),
26            _ if ch.is_control() || is_bidi_control(ch) => None,
27            _ => Some(ch),
28        })
29        .take(MAX_UNTRUSTED_FIELD_CHARS)
30        .collect()
31}
32
33/// One line of untrusted text on its way to a terminal or a log.
34///
35/// [`sanitize_untrusted_field`] keeps newlines, which is right for a multi-line
36/// diagnostic in a UI cell and wrong for anything sharing a line-oriented
37/// stream with output the user is reading: one embedded newline forges a line.
38/// A subprocess's stderr is exactly that case — it is one or more lines on
39/// their way into an error message.
40pub fn sanitize_untrusted_line(value: &str) -> String {
41    sanitize_untrusted_field(value).replace('\n', " ")
42}
43
44/// A filesystem path on its way to the same place.
45///
46/// [`std::path::Display`] escapes nothing, and a path is not always a literal
47/// this program chose — it can carry a component from an account name, a
48/// vendor response, or an archive member. This is what [`crate::error::AppError::Io`]
49/// renders its path through, so an attacker-chosen path cannot carry a terminal
50/// escape out of *any* error site rather than only the ones that remembered.
51pub fn sanitize_untrusted_path(path: &std::path::Path) -> String {
52    sanitize_untrusted_line(&path.to_string_lossy())
53}
54
55fn is_bidi_control(ch: char) -> bool {
56    matches!(
57        ch,
58        '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}'
59    )
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn strips_terminal_sequences_but_keeps_text_and_newlines() {
68        let input = "before\x1b]52;c;Y2xpcGJvYXJk\x07after\nnext\tcolumn\rreturn\u{202e}spoof";
69        assert_eq!(
70            sanitize_untrusted_field(input),
71            "before]52;c;Y2xpcGJvYXJkafter\nnext column returnspoof"
72        );
73    }
74
75    /// A subprocess's stderr shares a line-oriented stream with the message
76    /// carrying it, so a newline in it forges a line the program never wrote.
77    /// This is the shape `security` and `tar` diagnostics arrive in.
78    #[test]
79    fn collapses_newlines_so_untrusted_text_cannot_forge_a_line() {
80        let stderr = "tar: \x1b[2Kall good\nRESTORED: 0 files";
81        let out = sanitize_untrusted_line(stderr);
82        assert!(!out.contains('\n'), "{out:?}");
83        assert!(!out.contains('\u{1b}'), "{out:?}");
84        assert_eq!(out, "tar: [2Kall good RESTORED: 0 files");
85    }
86
87    #[test]
88    fn a_path_carrying_an_escape_renders_without_it() {
89        let path = std::path::Path::new("/tmp/\x1b[2Kspoofed");
90        assert_eq!(sanitize_untrusted_path(path), "/tmp/[2Kspoofed");
91    }
92
93    #[test]
94    fn caps_untrusted_fields_without_splitting_unicode() {
95        let input = "é".repeat(MAX_UNTRUSTED_FIELD_CHARS + 10);
96        let output = sanitize_untrusted_field(&input);
97        assert_eq!(output.chars().count(), MAX_UNTRUSTED_FIELD_CHARS);
98        assert!(output.chars().all(|ch| ch == 'é'));
99    }
100}
101
102/// Width of plain (non-markup) text in terminal columns.
103///
104/// Use this for layout arithmetic — column padding, gauge widths, the widest
105/// label in a report. A character count is wrong for any locale with CJK text,
106/// where one glyph occupies two cells, and for combining marks, which occupy
107/// none.
108///
109/// This is deliberately separate from [`crate::pango::visible_width`], which
110/// additionally strips `<span>` markup. Feeding plain text to that function
111/// would treat a literal `<` as the start of a tag and silently undercount the
112/// rest of the line; feeding markup to this one would count the tags.
113///
114/// Character counts remain correct for *limits* (a config field documented as
115/// "1 to 48 characters") and for edit-cursor positions, which move per
116/// character rather than per column. Those are not layout.
117pub fn text_width(s: &str) -> usize {
118    unicode_width::UnicodeWidthStr::width(s)
119}
120
121/// Left-align `s` in a field `width` columns wide, padding with spaces.
122///
123/// `format!("{s:width$}")` cannot do this: Rust's fill/align pads a `str` by
124/// character count, so a label of three CJK ideographs in a field of ten gets
125/// seven trailing spaces and renders thirteen columns wide, pushing the next
126/// column out of line. Padding is computed from [`text_width`] instead.
127///
128/// A string already at or past `width` is returned unpadded rather than
129/// truncated — the callers use this for column alignment, where clipping a
130/// label is worse than a single long row.
131pub fn pad_end(s: &str, width: usize) -> String {
132    let w = text_width(s);
133    if w >= width {
134        return s.to_string();
135    }
136    let mut out = String::with_capacity(s.len() + (width - w));
137    out.push_str(s);
138    out.extend(std::iter::repeat_n(' ', width - w));
139    out
140}
141
142#[cfg(test)]
143mod width_tests {
144    use super::{pad_end, text_width};
145
146    #[test]
147    fn text_width_measures_columns_not_characters() {
148        assert_eq!(text_width("Weekly"), 6);
149        assert_eq!(text_width("日本語"), 6); // 3 chars, 6 columns
150        assert_eq!(text_width("사용량"), 6);
151        assert_eq!(text_width("e\u{301}"), 1); // combining mark adds nothing
152    }
153
154    #[test]
155    fn pad_end_pads_by_columns_not_characters() {
156        // The bug this exists to prevent: `format!("{:10}", "日本語")` appends
157        // seven spaces to a six-column string, yielding thirteen columns.
158        assert_eq!(text_width(&pad_end("日本語", 10)), 10);
159        assert_eq!(text_width(&pad_end("Weekly", 10)), 10);
160        assert_eq!(pad_end("Weekly", 10), "Weekly    ");
161        // Already wide enough: returned unchanged rather than truncated.
162        assert_eq!(pad_end("Weekly", 3), "Weekly");
163        assert_eq!(pad_end("日本語", 6), "日本語");
164    }
165
166    #[test]
167    fn text_width_counts_a_literal_angle_bracket() {
168        // The reason this is not `pango::visible_width`: that function would
169        // read `<` as a tag opening and drop everything after it.
170        assert_eq!(text_width("a<b"), 3);
171        assert_eq!(text_width("Claude & GPT"), 12);
172    }
173}