vtcode-commons 0.185.5

Shared traits for paths, telemetry, and error reporting reused across VT Code component extractions
Documentation
//! XML escaping for untrusted content embedded in model-facing fences.
//!
//! Tool descriptions, skill instructions, and similar untrusted payloads are
//! wrapped in XML-style fences before being shown to the model. Escaping here
//! is a single-sourced security primitive: every consumer must produce
//! byte-identical escapes so a payload cannot close one consumer's fence with
//! syntax another consumer would have escaped.
//!
//! Two flavors exist:
//! - [`escape_xml`] / [`escape_xml_attribute`] escape a whole string.
//! - [`escape_xml_body_bounded`] escapes while capping the output at a byte
//!   budget, appending a caller-supplied truncation marker (wording is
//!   consumer-specific, the arithmetic is shared).

/// Escape a value for use inside an XML attribute or text node.
pub fn escape_xml_attribute(value: &str) -> String {
    escape_xml(value)
}

/// Escape `value` into an XML body capped at `max_bytes`, appending
/// `truncation_marker` when characters had to be dropped. The marker's byte
/// length is reserved up-front so the closing marker never overflows the
/// budget.
pub fn escape_xml_body_bounded(value: &str, max_bytes: usize, truncation_marker: &str) -> String {
    let marker = truncation_marker.as_bytes();
    let mut output = String::with_capacity(value.len().min(max_bytes));
    let mut truncated = false;

    for character in value.chars() {
        let escaped = escape_xml_character(character);
        if output.len().saturating_add(escaped.len()).saturating_add(marker.len()) > max_bytes {
            truncated = true;
            break;
        }
        output.push_str(&escaped);
    }

    if truncated {
        output.push_str(truncation_marker);
    }
    output
}

/// Escape every XML-significant and control character in `value`.
pub fn escape_xml(value: &str) -> String {
    let mut output = String::with_capacity(value.len());
    for character in value.chars() {
        output.push_str(&escape_xml_character(character));
    }
    output
}

/// Escape one character: the five XML entities, plus control characters
/// outside the ordinary-whitespace set replaced with U+FFFD (XML 1.0 does
/// not allow most control characters; ordinary whitespace stays useful to
/// the model).
pub fn escape_xml_character(character: char) -> String {
    match character {
        '&' => "&".to_owned(),
        '<' => "&lt;".to_owned(),
        '>' => "&gt;".to_owned(),
        '"' => "&quot;".to_owned(),
        '\'' => "&apos;".to_owned(),
        character if character.is_control() && !matches!(character, '\n' | '\r' | '\t') => "\u{FFFD}".to_owned(),
        character => character.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn escape_xml_encodes_all_five_entities() {
        assert_eq!(escape_xml("a&b<c>d\"e'f"), "a&amp;b&lt;c&gt;d&quot;e&apos;f");
    }

    #[test]
    fn escape_xml_character_replaces_control_characters_but_keeps_whitespace() {
        assert_eq!(escape_xml_character('\u{07}'), "\u{FFFD}");
        assert_eq!(escape_xml_character('\n'), "\n");
        assert_eq!(escape_xml_character('\r'), "\r");
        assert_eq!(escape_xml_character('\t'), "\t");
        assert_eq!(escape_xml_character('x'), "x");
    }

    #[test]
    fn escape_xml_body_bounded_reserves_marker_room_and_never_exceeds_budget() {
        let marker = "\n[…truncated…]";
        let budget = 40;
        let output = escape_xml_body_bounded("&".repeat(40).as_str(), budget, marker);
        assert!(output.ends_with(marker), "truncation must append the marker");
        assert!(output.len() <= budget, "output {} exceeds {budget}", output.len());
        // A budget smaller than the marker still terminates with the full
        // marker (original contract): content is dropped, not the marker.
        let tiny = escape_xml_body_bounded("abcdef&ghijkl", 8, marker);
        assert_eq!(tiny, marker);
    }

    #[test]
    fn escape_xml_body_bounded_keeps_fully_fitting_input_untouched() {
        let marker = "\n[…truncated…]";
        assert_eq!(escape_xml_body_bounded("ab<cd", 64, marker), "ab&lt;cd");
    }

    #[test]
    fn escape_xml_attribute_matches_escape_xml() {
        assert_eq!(escape_xml_attribute("a<b"), escape_xml("a<b"));
    }
}