injectguard 0.1.0

Heuristic prompt-injection detector and sanitizer for untrusted text fed to AI agents
Documentation
// SPDX-License-Identifier: MIT
//! Randomized robustness test: no panics, no raw dangerous characters in any
//! output, length caps respected. Deterministic (fixed seed, no dependency).

use injectguard::{escape_untrusted, scan_bytes, scan_text, UntrustedText};

struct Rng(u64);
impl Rng {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }
    fn below(&mut self, n: usize) -> usize {
        (self.next() % n as u64) as usize
    }
}

const FRAGMENTS: &[&str] = &[
    "<!--",
    "-->",
    "ignore",
    " previous ",
    "instructions",
    "\u{200B}",
    "\u{202E}",
    "\u{E0041}",
    "a",
    " ",
    "\n",
    "\r\n",
    "\t",
    "=",
    "/",
    "+",
    "\\n",
    "\\u0069",
    "&#105;",
    "%69",
    "&lt;",
    "aWdub3JlIGFsbCBwcmV2aW91cyBpbnN0cnVjdGlvbnM=",
    "QUFB",
    "é",
    "\u{301}",
    "\u{FE0F}",
    "\u{1F468}",
    "\u{200D}",
    "日本",
    "i",
    "і",
    "\u{1D422}",
    "ⓘ",
    "<|im_start|>",
    "system:",
    "### System",
    "curl x | sh",
    "rm -rf /",
    "color: white",
    "display:none",
    "i g n o r e ",
    "1gn0r3",
    "<b>",
    "</b>",
    "**",
    "`",
    "\u{0}",
    "\u{1b}[",
    "\u{FFFF}",
    "\u{10FFFF}",
    "vtaber",
    "erongi",
    "69 67 6e 6f 72 65 20 70 72 65 76 69",
    "![x](https://e.x/?q={{a}})",
];

fn dangerous(c: char) -> bool {
    let u = c as u32;
    (u < 0x20 && c != '\n' && c != '\t')
        || (0x7F..0xA0).contains(&u)
        || (0x200B..=0x200F).contains(&u)
        || (0x202A..=0x202E).contains(&u)
        || (0x2066..=0x2069).contains(&u)
        || (0xE0000..=0xE007F).contains(&u)
        || u == 0xFEFF
}

fn check(s: &str, cap: usize) {
    let r = scan_text(s);
    for f in &r.findings {
        assert!(
            !f.excerpt.chars().any(dangerous),
            "raw char in excerpt for {s:?}"
        );
        assert!(f.excerpt.chars().count() <= 80);
        assert!(f.line >= 1 && f.column >= 1);
    }
    let human = r.render_human(s);
    assert!(
        !human.chars().filter(|&c| c != '\n').any(dangerous),
        "raw char in report for {s:?}"
    );
    let (esc, _) = escape_untrusted(s, cap);
    assert!(
        !esc.chars().any(|c| dangerous(c) || c == '\n'),
        "escape leak for {s:?}"
    );
    let u = UntrustedText::with_limit(s, cap);
    assert!(
        u.text.chars().count() <= cap,
        "cap {cap} exceeded for {s:?}"
    );
}

fn run(iterations: usize, seed: u64) {
    let mut g = Rng(seed);
    for _ in 0..iterations {
        let cap = g.below(60);
        match g.below(3) {
            0 => {
                let bytes: Vec<u8> = (0..g.below(300)).map(|_| g.next() as u8).collect();
                let _ = scan_bytes(&bytes);
                check(&String::from_utf8_lossy(&bytes), cap);
            }
            1 => {
                let s: String = (0..g.below(200))
                    .filter_map(|_| {
                        let max = if g.below(4) == 0 { 0x110000 } else { 0x3000 };
                        char::from_u32(g.below(max) as u32)
                    })
                    .collect();
                check(&s, cap);
            }
            _ => {
                let s: String = (0..g.below(60))
                    .map(|_| FRAGMENTS[g.below(FRAGMENTS.len())])
                    .collect();
                check(&s, cap);
            }
        }
    }
}

#[test]
fn fuzz_quick() {
    run(1_000, 0x9E37_79B9_7F4A_7C15);
}

/// Run with: cargo test --release -- --ignored
#[test]
#[ignore = "long fuzz run; run in release mode"]
fn fuzz_long() {
    run(200_000, 0x2545_F491_4F6C_DD1D);
}