rift-mock-core 0.25.0

Rift core engine: imposter lifecycle, matching, behaviors, scripting and flow-state — usable in-process without the CLI or admin server.
Documentation
//! Static entrypoint/arity checking for `rift script check` (issue #360 Item 1).
//!
//! Complements the per-response syntax-only checks in `stub_validator.rs`/`rift-lint`: this
//! module answers "does the script actually define the entrypoint the given hook will call at
//! request time?" — issue #357 already added detection for exactly this ("script defines
//! function(s) but none is the `respond` entrypoint...") inside each engine's runtime dispatch
//! (`run_entrypoint` in `rhai_engine.rs`, and its JS equivalent in `js_engine.rs`), but only as
//! a request-time error. This module exposes the same
//! function-name-based detection statically, so `rift script check` can catch a misnamed
//! entrypoint (e.g. `fn respnod(ctx)`) before any request ever exercises it.
//!
//! "Static" here means never calling the entrypoint function itself. Rhai needs no evaluation at
//! all — `rhai::AST::iter_functions()` lists declared functions straight from the parsed AST.
//! JS has no cheap public AST walk, so it compiles the script (syntax check, WITHOUT running),
//! then evaluates its top level ONCE to discover which functions it declared, by diffing the
//! global object before and after — the same technique the runtime path uses to spot a
//! misnamed entrypoint. Crucially that top-level eval binds the SAME host globals the real
//! execution path binds (`ctx`/`http`/`pass`/`delay`/`reset`) under the engine's runtime limits
//! (a JS loop-iteration cap) — so a legitimate #357 bare-expression response script
//! (`http(503, "boom")`) is neither mis-flagged as an unbound-global error nor able to hang the
//! check with a top-level `while(true){}`. That binding-and-budgeting lives in the engine itself
//! (`js_engine::declared_functions_js`), reusing its real ctx/result-constructor setup.

/// Which entrypoint contract a script satisfies for the checked hook.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntrypointMatch {
    /// A v2 function declared with exactly the hook's name (`respond`).
    Named,
    /// No functions declared at all — a legal v2 bare-expression script.
    Bare,
}

/// Why a script failed the entrypoint/arity check.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum EntrypointCheckError {
    #[error("Unknown script engine type: '{0}'")]
    UnknownEngine(String),
    #[error("{engine} engine is not enabled (requires the '{feature}' feature)")]
    EngineDisabled { engine: String, feature: String },
    #[error(
        "the {0} scripting engine was removed (issue #450); use engine \"rhai\" or \"javascript\""
    )]
    EngineRemoved(String),
    #[error("Syntax error: {0}")]
    Syntax(String),
    #[error(
        "script defines function(s) ({declared}) but none is the `{hook}` entrypoint (and \
         there is no bare expression to evaluate); did you mean `{hook}`?"
    )]
    Mismatch { hook: String, declared: String },
    #[error(
        "`{hook}` is not a dispatchable entrypoint: only `respond` is wired end-to-end across \
         both engines. Predicate scripting uses Mountebank `inject`, and response rewriting uses \
         the `decorate`/`shellTransform` behaviors."
    )]
    UnsupportedHook { hook: String },
    /// An `engine: "wasm"` component Rift would refuse (issue #1751): not a component, an import
    /// Rift does not provide, or no `rift:mock/handler` export. A string, as the reason's type exists
    /// only in a build with the `wasm` feature.
    #[error("{0}")]
    Component(String),
}

/// Statically check whether `script` (for `engine_type`) defines a valid entrypoint for `hook`.
///
/// `hook` must be `"respond"` — the only entrypoint either engine dispatches (issue #1001).
/// This is a whitelist rather than a list of the three names #1001 removed, so a misspelled or
/// future hook fails closed too: validating a hook the runtime will never call is the defect
/// #1001 exists to remove, and a blacklist would let a narrower version of it back in.
///
/// `Err` covers an unsupported hook, a compile/syntax error, and an entrypoint mismatch — see
/// [`EntrypointCheckError`]'s variants.
pub fn check_entrypoint(
    engine_type: &str,
    script: &str,
    hook: &str,
) -> Result<EntrypointMatch, EntrypointCheckError> {
    if hook != super::entrypoints::RESPOND {
        return Err(EntrypointCheckError::UnsupportedHook {
            hook: hook.to_string(),
        });
    }
    // A component's entrypoint is its `rift:mock/handler` or `wasi:http/incoming-handler` export,
    // which admission checks.
    #[cfg(feature = "wasm")]
    if super::ScriptEngineKind::is_wasm(engine_type) {
        return super::wasm::admit(script, None)
            .map(|()| EntrypointMatch::Named)
            .map_err(|e| EntrypointCheckError::Component(e.to_string()));
    }
    let declared = declared_functions(engine_type, script)?;
    decide(&declared, hook)
}

/// Apply the same has-named/has-any-function decision `run_entrypoint` (issue #357) makes at
/// request time, given the set of top-level function names a script declares.
fn decide(declared: &[String], hook: &str) -> Result<EntrypointMatch, EntrypointCheckError> {
    if declared.iter().any(|n| n == hook) {
        return Ok(EntrypointMatch::Named);
    }
    if declared.is_empty() {
        return Ok(EntrypointMatch::Bare);
    }
    Err(EntrypointCheckError::Mismatch {
        hook: hook.to_string(),
        declared: declared.join(", "),
    })
}

/// The top-level function names `script` declares, for `engine_type`. Empty means the script has
/// no function declarations at all (a bare expression).
fn declared_functions(
    engine_type: &str,
    script: &str,
) -> Result<Vec<String>, EntrypointCheckError> {
    use super::{EngineNameError, ScriptEngineKind};
    match ScriptEngineKind::parse(engine_type) {
        Ok(ScriptEngineKind::Rhai) => rhai_declared_functions(script),
        #[cfg(feature = "javascript")]
        Ok(ScriptEngineKind::JavaScript) => super::js_engine::declared_functions_js(script)
            .map_err(|e| EntrypointCheckError::Syntax(e.to_string())),
        #[cfg(not(feature = "javascript"))]
        Ok(ScriptEngineKind::JavaScript) => Err(EntrypointCheckError::EngineDisabled {
            engine: "javascript".to_string(),
            feature: "javascript".to_string(),
        }),
        Ok(ScriptEngineKind::Wasm) => Err(EntrypointCheckError::EngineDisabled {
            engine: "wasm".to_string(),
            feature: "wasm".to_string(),
        }),
        Err(EngineNameError::Removed) => {
            Err(EntrypointCheckError::EngineRemoved("Lua".to_string()))
        }
        Err(EngineNameError::Unknown(other)) => Err(EntrypointCheckError::UnknownEngine(other)),
    }
}

/// Pure AST introspection — `compile` only parses, it never runs top-level statements, so this
/// has zero execution side effects (unlike the JS path, which has no public AST walk).
fn rhai_declared_functions(script: &str) -> Result<Vec<String>, EntrypointCheckError> {
    let engine = crate::scripting::rift_rhai_engine();
    let ast = engine
        .compile(script)
        .map_err(|e| EntrypointCheckError::Syntax(e.to_string()))?;
    Ok(ast.iter_functions().map(|f| f.name.to_string()).collect())
}

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

    #[test]
    fn rhai_respond_named_matches() {
        let script = "fn respond(ctx) { pass() }";
        assert_eq!(
            check_entrypoint("rhai", script, "respond"),
            Ok(EntrypointMatch::Named)
        );
    }

    // Issue #453: v1 `should_inject` was removed — a script defining only `should_inject` is now
    // just a script whose entrypoint isn't the requested one (the standard misnamed-entrypoint
    // error), not a special v1 detection.
    #[test]
    fn rhai_should_inject_only_is_misnamed_entrypoint() {
        let script = "fn should_inject(request, flow_store) { #{ inject: false } }";
        let err = check_entrypoint("rhai", script, "respond").unwrap_err();
        match err {
            EntrypointCheckError::Mismatch { hook, declared } => {
                assert_eq!(hook, "respond");
                assert_eq!(declared, "should_inject");
            }
            other => panic!("expected Mismatch, got {other:?}"),
        }
    }

    #[test]
    fn rhai_bare_expression_is_ok() {
        assert_eq!(
            check_entrypoint("rhai", "pass()", "respond"),
            Ok(EntrypointMatch::Bare)
        );
    }

    // AC (issue #360): a syntax-valid script whose only function is misnamed fails naming the
    // expected entrypoint.
    #[test]
    fn rhai_misnamed_entrypoint_fails_naming_respond() {
        let script = "fn respnod(ctx) { pass() }";
        let err = check_entrypoint("rhai", script, "respond").unwrap_err();
        match err {
            EntrypointCheckError::Mismatch { hook, declared } => {
                assert_eq!(hook, "respond");
                assert_eq!(declared, "respnod");
            }
            other => panic!("expected Mismatch, got {other:?}"),
        }
    }

    #[test]
    fn rhai_syntax_error_is_syntax_variant() {
        let script = "fn respond(ctx { pass() }";
        let err = check_entrypoint("rhai", script, "respond").unwrap_err();
        assert!(matches!(err, EntrypointCheckError::Syntax(_)));
    }

    /// Flipped in #1001. This test used to assert that `matches` was a checkable hook; the
    /// property reversed when #1001 established that `respond` is the only entrypoint the runtime
    /// dispatches, so the assertion is inverted rather than deleted — otherwise nothing would
    /// state which way round it is.
    #[test]
    fn rhai_matches_hook_is_rejected_as_undispatchable() {
        for hook in ["matches", "transform", "delay"] {
            let err = check_entrypoint("rhai", "fn matches(ctx) { true }", hook).unwrap_err();
            assert!(
                matches!(&err, EntrypointCheckError::UnsupportedHook { hook: h } if h == hook),
                "hook `{hook}` must be refused as undispatchable, got {err:?}"
            );
        }
    }

    /// The guard is a whitelist, not a blacklist of the three names #1001 removed: an unknown or
    /// misspelled hook must fail closed too. A blacklist would pass `bogus` through to `decide()`,
    /// which would "validate" it and report a Mismatch as if the hook were real — reintroducing a
    /// narrower version of the exact defect this issue removes.
    #[test]
    fn an_unknown_hook_is_rejected_rather_than_validated() {
        let err = check_entrypoint("rhai", "fn bogus(ctx) { true }", "bogus").unwrap_err();
        assert!(
            matches!(&err, EntrypointCheckError::UnsupportedHook { hook } if hook == "bogus"),
            "an unknown hook must be refused, not validated, got {err:?}"
        );
    }

    #[test]
    fn unknown_engine_errors() {
        let err = check_entrypoint("cobol", "whatever", "respond").unwrap_err();
        assert!(matches!(err, EntrypointCheckError::UnknownEngine(e) if e == "cobol"));
    }

    #[cfg(feature = "javascript")]
    #[test]
    fn js_respond_named_matches() {
        let script = "function respond(ctx) { return pass(); }";
        assert_eq!(
            check_entrypoint("javascript", script, "respond"),
            Ok(EntrypointMatch::Named)
        );
    }

    // Issue #453 JS variant: a script defining only `should_inject` is now just a misnamed
    // entrypoint, not a special v1 detection.
    #[cfg(feature = "javascript")]
    #[test]
    fn js_should_inject_only_is_misnamed_entrypoint() {
        let script = "function should_inject(request, flow_store) { return {inject: false}; }";
        let err = check_entrypoint("javascript", script, "respond").unwrap_err();
        match err {
            EntrypointCheckError::Mismatch { hook, declared } => {
                assert_eq!(hook, "respond");
                assert_eq!(declared, "should_inject");
            }
            other => panic!("expected Mismatch, got {other:?}"),
        }
    }

    // AC (issue #360), JS variant: misnamed entrypoint fails naming `respond`.
    #[cfg(feature = "javascript")]
    #[test]
    fn js_misnamed_entrypoint_fails_naming_respond() {
        let script = "function respnod(ctx) { return pass(); }";
        let err = check_entrypoint("javascript", script, "respond").unwrap_err();
        match err {
            EntrypointCheckError::Mismatch { hook, declared } => {
                assert_eq!(hook, "respond");
                assert_eq!(declared, "respnod");
            }
            other => panic!("expected Mismatch, got {other:?}"),
        }
    }

    #[cfg(feature = "javascript")]
    #[test]
    fn js_syntax_error_is_syntax_variant() {
        let err = check_entrypoint("javascript", "function respond(ctx {", "respond").unwrap_err();
        assert!(matches!(err, EntrypointCheckError::Syntax(_)));
    }

    // B1 regression (issue #360): a legitimate #357 bare-expression JS response script must NOT
    // false-fail — the top-level `http(...)`/`ctx.*` references resolve against the bound host
    // globals, exactly as at request time.
    #[cfg(feature = "javascript")]
    #[test]
    fn js_bare_expression_calling_http_is_ok() {
        assert_eq!(
            check_entrypoint("javascript", r#"http(503, "boom")"#, "respond"),
            Ok(EntrypointMatch::Bare)
        );
    }

    #[cfg(feature = "javascript")]
    #[test]
    fn js_bare_expression_reading_ctx_request_is_ok() {
        let script = r#"(ctx.request.method === "POST") ? http(503, {error:"x"}) : pass()"#;
        assert_eq!(
            check_entrypoint("javascript", script, "respond"),
            Ok(EntrypointMatch::Bare)
        );
    }

    // B1 regression: a top-level `while(true){}` must TERMINATE the check (via the loop-iteration
    // cap), not hang. It surfaces as OK/Bare here (no functions declared) — the point is it
    // returns at all.
    #[cfg(feature = "javascript")]
    #[test]
    fn js_top_level_infinite_loop_terminates() {
        let script = "while (true) {}";
        // Returns (bounded) rather than hanging; the exact classification is immaterial.
        let _ = check_entrypoint("javascript", script, "respond");
    }
}