injectguard 0.1.0

Heuristic prompt-injection detector and sanitizer for untrusted text fed to AI agents
Documentation
// SPDX-License-Identifier: MIT
//! Escaping and labeling of untrusted strings.
//!
//! [`escape_untrusted`] turns every control, invisible, bidi, tag, variation
//! selector, private-use and otherwise suspicious character into a visible
//! `\u{XXXX}` escape (or `\n`, `\r`, `\t`), doubles backslashes so escapes
//! cannot be forged, and caps the output length.

use serde::Serialize;

use crate::detect::scan_text;

/// Default output cap (in chars) used by [`UntrustedText::new`].
pub const DEFAULT_MAX_CHARS: usize = 256;

/// Kinds of invisible characters the detector reports (and strips before the
/// second scan pass).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Invisible {
    ZeroWidth,
    Bidi,
    Tag,
    VariationSelector,
    Bom,
    /// C0/C1 control characters (other than tab/newline/CR) and DEL:
    /// terminal escape sequences can spoof output in a user's terminal.
    Control,
}

/// Classifies `c` as an invisible character, if it is one.
pub(crate) fn invisible_kind(c: char) -> Option<Invisible> {
    match c as u32 {
        0x200B..=0x200D
        | 0x2060..=0x2064
        | 0x00AD
        | 0x180E
        | 0x034F
        | 0x115F
        | 0x1160
        | 0x17B4
        | 0x17B5
        | 0x3164
        | 0xFFA0 => Some(Invisible::ZeroWidth),
        0x200E | 0x200F | 0x202A..=0x202E | 0x2066..=0x2069 | 0x061C => Some(Invisible::Bidi),
        0xE0000..=0xE007F => Some(Invisible::Tag),
        0xFE00..=0xFE0F | 0xE0100..=0xE01EF => Some(Invisible::VariationSelector),
        0xFEFF => Some(Invisible::Bom),
        // Form feed (0x0C) is excluded: it is a normal page break in licence texts (still escaped on output).
        0x00..=0x08 | 0x0B | 0x0E..=0x1F | 0x7F..=0x9F => Some(Invisible::Control),
        _ => None,
    }
}

/// Returns true if `c` must be shown as an escape sequence.
pub(crate) fn needs_escape(c: char) -> bool {
    let u = c as u32;
    // Noncharacters: U+xxFFFE / U+xxFFFF in every plane, and U+FDD0..U+FDEF.
    if u & 0xFFFE == 0xFFFE {
        return true;
    }
    matches!(
        u,
        // C0 controls, DEL, C1 controls.
        0x00..=0x1F | 0x7F..=0x9F
        // Invisible / format characters (category Cf and friends).
        | 0x00AD | 0x034F | 0x061C | 0x115F | 0x1160 | 0x17B4 | 0x17B5
        | 0x180B..=0x180F | 0x3164 | 0xFFA0
        | 0x0600..=0x0605 | 0x06DD | 0x070F | 0x0890 | 0x0891 | 0x08E2
        | 0x110BD | 0x110CD | 0x13430..=0x1345F | 0x1BCA0..=0x1BCA3 | 0x1D173..=0x1D17A
        // Unusual spaces, zero-width chars, bidi marks/embeddings, line and
        // paragraph separators, word joiners, invisible operators, bidi
        // isolates and deprecated format chars (U+2065 is unassigned).
        | 0x1680 | 0x2000..=0x200F | 0x2028..=0x202F | 0x205F..=0x206F | 0x3000
        // Variation selectors, BOM / zero-width no-break space.
        | 0xFE00..=0xFE0F | 0xFEFF
        // Interlinear annotation controls, unassigned specials.
        | 0xFFF0..=0xFFFB
        // Noncharacter block.
        | 0xFDD0..=0xFDEF
        // Private use area (BMP).
        | 0xE000..=0xF8FF
        // Unassigned planes 4..=13.
        | 0x40000..=0xDFFFF
        // Plane 14: tag characters, variation selectors supplement, and the
        // rest of the plane (unassigned).
        | 0xE0000..=0xEFFFF
        // Supplementary private use planes 15 and 16.
        | 0xF0000..=0x10FFFF
    )
}

/// Combining diacritical marks (the blocks used for "Zalgo" stacking).
fn is_combining_mark(c: char) -> bool {
    matches!(
        c as u32,
        0x0300..=0x036F | 0x1AB0..=0x1AFF | 0x1DC0..=0x1DFF | 0x20D0..=0x20FF | 0xFE20..=0xFE2F
    )
}

/// Combining marks allowed in a row before the rest of the run is escaped
/// (real scripts rarely stack more; long stacks can hide or overdraw text).
pub const MAX_COMBINING_RUN: usize = 2;

/// Escapes untrusted text and caps it at `max_chars` output chars.
///
/// Every character for which escaping is required (ASCII and C1 controls,
/// zero-width and invisible characters, bidi controls, Unicode tag chars,
/// variation selectors, private use, noncharacters and a few unassigned
/// ranges) becomes `\u{XXXX}`; `\n`, `\r` and `\t` become `\n`, `\r` and
/// `\t`; a backslash becomes `\\`. In a run of combining marks, marks after
/// the first [`MAX_COMBINING_RUN`] are escaped too. The output never splits an
/// escape sequence. Returns `(escaped, truncated)`.
pub fn escape_untrusted(s: &str, max_chars: usize) -> (String, bool) {
    let mut out = String::with_capacity(s.len().min(max_chars.saturating_mul(4)));
    let mut out_chars = 0usize;
    let mut token = String::with_capacity(12);
    let mut combining_run = 0usize;
    for c in s.chars() {
        token.clear();
        combining_run = if is_combining_mark(c) {
            combining_run + 1
        } else {
            0
        };
        match c {
            '\\' => token.push_str("\\\\"),
            '\n' => token.push_str("\\n"),
            '\r' => token.push_str("\\r"),
            '\t' => token.push_str("\\t"),
            c if needs_escape(c) || combining_run > MAX_COMBINING_RUN => {
                use std::fmt::Write;
                // Writing to a String cannot fail.
                let _ = write!(token, "\\u{{{:04X}}}", c as u32);
            }
            c => token.push(c),
        }
        let token_chars = token.chars().count();
        if out_chars + token_chars > max_chars {
            return (out, true);
        }
        out.push_str(&token);
        out_chars += token_chars;
    }
    (out, false)
}

/// An untrusted string, escaped, capped and labeled for an AI's context.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct UntrustedText {
    /// Always `true`: marks this value as data, never instructions.
    pub untrusted: bool,
    /// The escaped and length-capped text.
    pub text: String,
    /// Whether `text` was cut at the length cap.
    pub truncated: bool,
    /// Length of the raw input in bytes.
    pub original_len: usize,
    /// Sorted, deduplicated rule ids from scanning the raw input.
    pub injection_flags: Vec<String>,
}

impl UntrustedText {
    /// Wraps `raw` using [`DEFAULT_MAX_CHARS`].
    pub fn new(raw: &str) -> Self {
        Self::with_limit(raw, DEFAULT_MAX_CHARS)
    }

    /// Wraps `raw`, capping the escaped text at `max_chars` chars.
    pub fn with_limit(raw: &str, max_chars: usize) -> Self {
        let (text, truncated) = escape_untrusted(raw, max_chars);
        UntrustedText {
            untrusted: true,
            text,
            truncated,
            original_len: raw.len(),
            injection_flags: scan_text(raw).rules(),
        }
    }

    /// Whether the scanner flagged the raw input at all.
    pub fn is_flagged(&self) -> bool {
        !self.injection_flags.is_empty()
    }
}

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

    fn all_chars() -> impl Iterator<Item = char> {
        (0u32..=0xFFFF)
            .chain(0xE0000..=0xE01EF)
            .chain(0xF0000..=0xF0100)
            .filter_map(char::from_u32)
    }

    #[test]
    fn long_combining_runs_are_escaped() {
        // Two marks stay (real scripts), the third and later are escaped.
        let (e, _) = escape_untrusted("e\u{301}\u{302}\u{303}\u{304}x\u{301}", 100);
        assert_eq!(e, "e\u{301}\u{302}\\u{0303}\\u{0304}x\u{301}");
    }

    #[test]
    fn listed_classes_are_escaped() {
        let ranges: &[(u32, u32)] = &[
            (0x00, 0x1F),
            (0x7F, 0x7F),
            (0x80, 0x9F),
            (0x200B, 0x200F),
            (0x2060, 0x2064),
            (0xFEFF, 0xFEFF),
            (0x00AD, 0x00AD),
            (0x180E, 0x180E),
            (0x034F, 0x034F),
            (0x202A, 0x202E),
            (0x2066, 0x2069),
            (0x061C, 0x061C),
            (0xE0000, 0xE007F),
            (0xFE00, 0xFE0F),
            (0xE0100, 0xE01EF),
            (0xE000, 0xF8FF),
            (0xF0000, 0xFFFFD),
            (0x100000, 0x10FFFD),
        ];
        for &(lo, hi) in ranges {
            for u in lo..=hi {
                let c = char::from_u32(u).unwrap();
                assert!(needs_escape(c), "U+{u:04X} must be escaped");
                let (e, t) = escape_untrusted(&c.to_string(), 64);
                assert!(!t);
                assert!(!e.contains(c), "U+{u:04X} leaked raw");
                assert!(e.starts_with('\\'));
            }
        }
    }

    #[test]
    fn invisible_kinds_are_escaped() {
        for c in all_chars() {
            if invisible_kind(c).is_some() {
                assert!(needs_escape(c), "U+{:04X}", c as u32);
            }
        }
    }

    #[test]
    fn exact_escape_forms() {
        assert_eq!(escape_untrusted("a\\b", 99).0, "a\\\\b");
        assert_eq!(escape_untrusted("\n\r\t", 99).0, "\\n\\r\\t");
        assert_eq!(escape_untrusted("\u{200B}", 99).0, "\\u{200B}");
        assert_eq!(escape_untrusted("\u{E0041}", 99).0, "\\u{E0041}");
        assert_eq!(escape_untrusted("\0", 99).0, "\\u{0000}");
        assert_eq!(escape_untrusted("héllo 日本", 99).0, "héllo 日本");
    }

    #[test]
    fn property_no_raw_escaped_char_survives() {
        let all: Vec<char> = all_chars().collect();
        // Escape in chunks so the test also covers mixed content.
        for chunk in all.chunks(512) {
            let s: String = chunk.iter().collect();
            let (e, t) = escape_untrusted(&s, usize::MAX);
            assert!(!t);
            for c in e.chars() {
                assert!(!needs_escape(c), "raw U+{:04X} in output", c as u32);
            }
        }
    }

    #[test]
    fn truncation_never_splits_escape() {
        let s = "ab\u{200B}cd\u{E0041}\\x\n";
        // Token boundaries (byte offsets into the full escaped output).
        let mut boundaries = vec![0usize];
        let mut acc = 0usize;
        for c in s.chars() {
            acc += escape_untrusted(&c.to_string(), usize::MAX).0.len();
            boundaries.push(acc);
        }
        let (full, _) = escape_untrusted(s, usize::MAX);
        assert_eq!(acc, full.len());
        for max in 0..=full.chars().count() + 2 {
            let (e, t) = escape_untrusted(s, max);
            assert!(e.chars().count() <= max, "cap {max} exceeded: {e}");
            assert!(full.starts_with(&e));
            assert_eq!(t, e != full);
            assert!(
                boundaries.contains(&e.len()),
                "split escape at cap {max}: {e}"
            );
        }
    }

    #[test]
    fn cap_counts_multibyte_as_one() {
        let (e, t) = escape_untrusted("日本語テキスト", 3);
        assert_eq!(e, "日本語");
        assert!(t);
    }
}