noctis 0.6.0

Open-source black-box vulnerability scanner: readable YAML checks that prove each bug on the live service, QoD-graded findings, REST API.
use std::collections::HashMap;

use crate::error::{NoctisError, Result};

static TEMPLATE_RE: std::sync::LazyLock<regex::Regex> =
    std::sync::LazyLock::new(|| regex::Regex::new(r"\{\{([^}]+)\}\}").expect("static regex"));

/// Substitutes every `{{key}}` placeholder in a single left-to-right pass over
/// `template`. Inserted values are copied literally and never re-scanned, so a
/// value that itself contains `{{...}}` text (e.g. target-controlled response
/// data) cannot capture a later placeholder (#1970).
pub fn interpolate(template: &str, vars: &HashMap<String, serde_json::Value>) -> Result<String> {
    let mut result = String::with_capacity(template.len());
    let mut last = 0;

    for cap in TEMPLATE_RE.captures_iter(template) {
        let whole = cap.get(0).expect("group 0 always matches");
        let key = cap[1].trim();

        let value = resolve_path(key, vars)
            .ok_or_else(|| NoctisError::Template(format!("undefined variable: {key}")))?;

        result.push_str(&template[last..whole.start()]);
        match &value {
            serde_json::Value::String(s) => result.push_str(s),
            other => result.push_str(&other.to_string()),
        }
        last = whole.end();
    }
    result.push_str(&template[last..]);

    Ok(result)
}

pub fn interpolate_lenient(template: &str, vars: &HashMap<String, serde_json::Value>) -> String {
    interpolate(template, vars).unwrap_or_else(|_| template.to_string())
}

/// Like [`interpolate_lenient`], but passes each substituted value through
/// `map` before it is inserted, leaving the template's literal text untouched.
/// Used to redact credential secrets in finding text without masking words the
/// feed author wrote (a password `admin` must not rewrite `/admin/admin.php`).
/// Single pass: a substituted value is never re-scanned for placeholders.
/// On an undefined variable the template is returned as-is, like the lenient form.
pub fn interpolate_lenient_mapped(
    template: &str,
    vars: &HashMap<String, serde_json::Value>,
    map: impl Fn(&str) -> String,
) -> String {
    let mut undefined = false;
    let out = TEMPLATE_RE.replace_all(template, |cap: &regex::Captures| {
        match resolve_path(cap[1].trim(), vars) {
            Some(serde_json::Value::String(s)) => map(&s),
            // Map each string inside an object / array before it is written
            // out as JSON: the escapes (`\n` → `\\n`) would otherwise glue a
            // secret to a word character or split it.
            Some(other) => map_strings(&other, &map).to_string(),
            None => {
                undefined = true;
                String::new()
            }
        }
    });
    if undefined {
        template.to_string()
    } else {
        out.into_owned()
    }
}

/// Apply `map` to every string (object keys included) inside a JSON value.
fn map_strings(v: &serde_json::Value, map: &impl Fn(&str) -> String) -> serde_json::Value {
    use serde_json::Value;
    match v {
        Value::String(s) => Value::String(map(s)),
        Value::Array(a) => Value::Array(a.iter().map(|x| map_strings(x, map)).collect()),
        Value::Object(o) => Value::Object(
            o.iter()
                .map(|(k, x)| (map(k), map_strings(x, map)))
                .collect(),
        ),
        // A number leaf can spell a numeric password (`1234`): keep it as a
        // number unless redaction changed its text.
        Value::Number(n) => {
            let text = n.to_string();
            let mapped = map(&text);
            if mapped == text {
                v.clone()
            } else {
                Value::String(mapped)
            }
        }
        other => other.clone(),
    }
}

fn resolve_path(
    path: &str,
    vars: &HashMap<String, serde_json::Value>,
) -> Option<serde_json::Value> {
    if let Some(v) = vars.get(path) {
        return Some(v.clone());
    }

    let parts: Vec<&str> = path.splitn(2, '.').collect();
    if parts.len() == 2 {
        if let Some(parent) = vars.get(parts[0]) {
            return json_path(parent, parts[1]);
        }
    }

    None
}

fn json_path(root: &serde_json::Value, path: &str) -> Option<serde_json::Value> {
    let parts: Vec<&str> = path.splitn(2, '.').collect();
    match root {
        serde_json::Value::Object(map) => {
            let child = map.get(parts[0])?;
            if parts.len() == 1 {
                Some(child.clone())
            } else {
                json_path(child, parts[1])
            }
        }
        _ => None,
    }
}

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

    fn v(pairs: &[(&str, serde_json::Value)]) -> HashMap<String, serde_json::Value> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.clone()))
            .collect()
    }

    #[test]
    fn no_placeholder_passthrough() {
        assert_eq!(
            interpolate("plain text", &HashMap::new()).unwrap(),
            "plain text"
        );
    }

    #[test]
    fn single_string_var() {
        let vars = v(&[("host", json!("example.com"))]);
        assert_eq!(
            interpolate("http://{{host}}/", &vars).unwrap(),
            "http://example.com/"
        );
    }

    #[test]
    fn multiple_vars() {
        let vars = v(&[("scheme", json!("https")), ("host", json!("example.com"))]);
        assert_eq!(
            interpolate("{{scheme}}://{{host}}", &vars).unwrap(),
            "https://example.com"
        );
    }

    #[test]
    fn number_to_string() {
        let vars = v(&[("port", json!(8080))]);
        assert_eq!(interpolate("port={{port}}", &vars).unwrap(), "port=8080");
    }

    #[test]
    fn bool_to_string() {
        let vars = v(&[("flag", json!(true))]);
        assert_eq!(interpolate("val={{flag}}", &vars).unwrap(), "val=true");
    }

    #[test]
    fn undefined_var_error() {
        let err = interpolate("{{nope}}", &HashMap::new()).unwrap_err();
        assert!(err.to_string().contains("undefined variable"));
    }

    #[test]
    fn lenient_preserves_undefined() {
        assert_eq!(interpolate_lenient("{{nope}}", &HashMap::new()), "{{nope}}");
    }

    #[test]
    fn lenient_resolves_defined() {
        let vars = v(&[("x", json!("ok"))]);
        assert_eq!(interpolate_lenient("{{x}}", &vars), "ok");
    }

    #[test]
    fn whitespace_trimmed_in_key() {
        let vars = v(&[("host", json!("example.com"))]);
        assert_eq!(interpolate("{{ host }}", &vars).unwrap(), "example.com");
    }

    #[test]
    fn dot_notation_one_level() {
        let vars = v(&[("resp", json!({"status": 200}))]);
        assert_eq!(interpolate("{{resp.status}}", &vars).unwrap(), "200");
    }

    #[test]
    fn dot_notation_two_levels() {
        let vars = v(&[("a", json!({"b": {"c": "deep"}}))]);
        assert_eq!(interpolate("{{a.b.c}}", &vars).unwrap(), "deep");
    }

    #[test]
    fn flat_key_beats_dot_traversal() {
        let mut vars = HashMap::new();
        vars.insert("a.b".to_string(), json!("flat"));
        vars.insert("a".to_string(), json!({"b": "nested"}));
        assert_eq!(interpolate("{{a.b}}", &vars).unwrap(), "flat");
    }

    #[test]
    fn dot_path_missing_child_is_error() {
        let vars = v(&[("resp", json!({"status": 200}))]);
        assert!(interpolate("{{resp.missing}}", &vars).is_err());
    }

    #[test]
    fn substituted_value_is_not_rescanned() {
        // #1970: a target-controlled value holding a later placeholder's text
        // must be inserted literally, and the later placeholder must still be
        // resolved at its own position.
        let vars = v(&[("verdict", json!({"user": "{{verdict.plen}}", "plen": 9}))]);
        assert_eq!(
            interpolate(
                "Login='{{verdict.user}}', Password=<{{verdict.plen}} characters>",
                &vars
            )
            .unwrap(),
            "Login='{{verdict.plen}}', Password=<9 characters>"
        );
    }

    #[test]
    fn value_containing_own_placeholder_is_literal() {
        let vars = v(&[("a", json!("{{a}}{{b}}")), ("b", json!("B"))]);
        assert_eq!(interpolate("{{a}}|{{b}}", &vars).unwrap(), "{{a}}{{b}}|B");
    }

    #[test]
    fn repeated_placeholder_each_position() {
        let vars = v(&[("x", json!("1"))]);
        assert_eq!(interpolate("{{x}}-{{x}}-{{ x }}", &vars).unwrap(), "1-1-1");
    }

    #[test]
    fn multibyte_text_around_placeholders() {
        let vars = v(&[("x", json!("é"))]);
        assert_eq!(interpolate("à{{x}}ü", &vars).unwrap(), "àéü");
    }

    #[test]
    fn dot_path_on_non_object_is_error() {
        let vars = v(&[("resp", json!("a string"))]);
        assert!(interpolate("{{resp.field}}", &vars).is_err());
    }
}