Skip to main content

vtcode_commons/
untrusted_xml.rs

1//! XML escaping for untrusted content embedded in model-facing fences.
2//!
3//! Tool descriptions, skill instructions, and similar untrusted payloads are
4//! wrapped in XML-style fences before being shown to the model. Escaping here
5//! is a single-sourced security primitive: every consumer must produce
6//! byte-identical escapes so a payload cannot close one consumer's fence with
7//! syntax another consumer would have escaped.
8//!
9//! Two flavors exist:
10//! - [`escape_xml`] / [`escape_xml_attribute`] escape a whole string.
11//! - [`escape_xml_body_bounded`] escapes while capping the output at a byte
12//!   budget, appending a caller-supplied truncation marker (wording is
13//!   consumer-specific, the arithmetic is shared).
14
15/// Escape a value for use inside an XML attribute or text node.
16pub fn escape_xml_attribute(value: &str) -> String {
17    escape_xml(value)
18}
19
20/// Escape `value` into an XML body capped at `max_bytes`, appending
21/// `truncation_marker` when characters had to be dropped. The marker's byte
22/// length is reserved up-front so the closing marker never overflows the
23/// budget.
24pub fn escape_xml_body_bounded(value: &str, max_bytes: usize, truncation_marker: &str) -> String {
25    let marker = truncation_marker.as_bytes();
26    let mut output = String::with_capacity(value.len().min(max_bytes));
27    let mut truncated = false;
28
29    for character in value.chars() {
30        let escaped = escape_xml_character(character);
31        if output.len().saturating_add(escaped.len()).saturating_add(marker.len()) > max_bytes {
32            truncated = true;
33            break;
34        }
35        output.push_str(&escaped);
36    }
37
38    if truncated {
39        output.push_str(truncation_marker);
40    }
41    output
42}
43
44/// Escape every XML-significant and control character in `value`.
45pub fn escape_xml(value: &str) -> String {
46    let mut output = String::with_capacity(value.len());
47    for character in value.chars() {
48        output.push_str(&escape_xml_character(character));
49    }
50    output
51}
52
53/// Escape one character: the five XML entities, plus control characters
54/// outside the ordinary-whitespace set replaced with U+FFFD (XML 1.0 does
55/// not allow most control characters; ordinary whitespace stays useful to
56/// the model).
57pub fn escape_xml_character(character: char) -> String {
58    match character {
59        '&' => "&".to_owned(),
60        '<' => "&lt;".to_owned(),
61        '>' => "&gt;".to_owned(),
62        '"' => "&quot;".to_owned(),
63        '\'' => "&apos;".to_owned(),
64        character if character.is_control() && !matches!(character, '\n' | '\r' | '\t') => "\u{FFFD}".to_owned(),
65        character => character.to_string(),
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn escape_xml_encodes_all_five_entities() {
75        assert_eq!(escape_xml("a&b<c>d\"e'f"), "a&amp;b&lt;c&gt;d&quot;e&apos;f");
76    }
77
78    #[test]
79    fn escape_xml_character_replaces_control_characters_but_keeps_whitespace() {
80        assert_eq!(escape_xml_character('\u{07}'), "\u{FFFD}");
81        assert_eq!(escape_xml_character('\n'), "\n");
82        assert_eq!(escape_xml_character('\r'), "\r");
83        assert_eq!(escape_xml_character('\t'), "\t");
84        assert_eq!(escape_xml_character('x'), "x");
85    }
86
87    #[test]
88    fn escape_xml_body_bounded_reserves_marker_room_and_never_exceeds_budget() {
89        let marker = "\n[…truncated…]";
90        let budget = 40;
91        let output = escape_xml_body_bounded("&".repeat(40).as_str(), budget, marker);
92        assert!(output.ends_with(marker), "truncation must append the marker");
93        assert!(output.len() <= budget, "output {} exceeds {budget}", output.len());
94        // A budget smaller than the marker still terminates with the full
95        // marker (original contract): content is dropped, not the marker.
96        let tiny = escape_xml_body_bounded("abcdef&ghijkl", 8, marker);
97        assert_eq!(tiny, marker);
98    }
99
100    #[test]
101    fn escape_xml_body_bounded_keeps_fully_fitting_input_untouched() {
102        let marker = "\n[…truncated…]";
103        assert_eq!(escape_xml_body_bounded("ab<cd", 64, marker), "ab&lt;cd");
104    }
105
106    #[test]
107    fn escape_xml_attribute_matches_escape_xml() {
108        assert_eq!(escape_xml_attribute("a<b"), escape_xml("a<b"));
109    }
110}