#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EntrypointMatch {
Named,
Bare,
}
#[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 },
#[error("{0}")]
Component(String),
}
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(),
});
}
#[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)
}
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(", "),
})
}
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)),
}
}
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)
);
}
#[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)
);
}
#[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(_)));
}
#[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:?}"
);
}
}
#[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)
);
}
#[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:?}"),
}
}
#[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(_)));
}
#[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)
);
}
#[cfg(feature = "javascript")]
#[test]
fn js_top_level_infinite_loop_terminates() {
let script = "while (true) {}";
let _ = check_entrypoint("javascript", script, "respond");
}
}