use super::request::RequestContext;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResponseStatus {
Code(u16),
Text(String),
}
impl From<u16> for ResponseStatus {
fn from(code: u16) -> Self {
ResponseStatus::Code(code)
}
}
impl ResponseStatus {
#[must_use]
pub fn to_json(&self) -> serde_json::Value {
match self {
ResponseStatus::Code(code) => (*code).into(),
ResponseStatus::Text(text) => text.as_str().into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum DecorateError {
#[error("Decorate script error: {0}")]
Rhai(String),
#[error("JavaScript decorate error: {0}")]
JavaScript(String),
#[error("Could not parse JavaScript decorate function")]
JsParseFailure,
#[error("decorate script timed out after {0}ms")]
Timeout(u64),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decorated {
pub status_code: ResponseStatus,
pub headers: crate::util::OrderedMap<String, String>,
pub body: String,
pub returned: Option<ReturnedOmits>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ReturnedOmits {
pub status_code: bool,
pub headers: bool,
pub body: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ShellTransformError {
#[error("Could not run shell command: {0}")]
Spawn(String),
#[error("Command failed: {command}\n{stderr}")]
Failed { command: String, stderr: String },
#[error("Shell command returned invalid JSON: '{0}'")]
InvalidJson(String),
#[error("Shell command returned null, not a response")]
Null,
#[error("Shell command returned an invalid response: {0}")]
InvalidResponse(String),
}
pub const MAX_SHELL_COMMAND_LENGTH: usize = 2048;
#[must_use]
pub fn shell_request_json(request: &RequestContext) -> String {
use crate::util::{JsKeyOrder, map_values_as_json};
use serde::Serialize;
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct MbRequest<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
request_from: Option<&'a str>,
method: &'a str,
path: &'a str,
query: JsKeyOrder<'a, serde_json::Value, foldhash::fast::RandomState>,
headers: JsKeyOrder<'a, serde_json::Value, foldhash::fast::RandomState>,
#[serde(skip_serializing_if = "Option::is_none")]
body: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
ip: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
form: Option<JsKeyOrder<'a, serde_json::Value, foldhash::fast::RandomState>>,
}
let query = map_values_as_json(&request.query);
let headers = map_values_as_json(&request.headers);
let form = request.form.as_ref().map(map_values_as_json);
let mb = MbRequest {
request_from: request.request_from.as_deref(),
method: &request.method,
path: &request.path,
query: JsKeyOrder(&query),
headers: JsKeyOrder(&headers),
body: (!request.body_undefined).then(|| request.body.as_deref().unwrap_or("")),
ip: request.ip.as_deref(),
form: form.as_ref().map(JsKeyOrder),
};
serde_json::to_string(&mb).expect("strings and string-keyed string maps always serialize")
}
fn quote_for_shell(json: &str) -> String {
format!("'{}'", json.replace('\'', r"'\''"))
}
#[must_use]
pub fn shell_command_line(command: &str, request_json: &str, response_json: &str) -> String {
let utf16 = |s: &str| s.encode_utf16().count();
let mountebank_len = utf16(command) + utf16(request_json) + utf16(response_json) + 6;
if mountebank_len >= MAX_SHELL_COMMAND_LENGTH {
command.to_string()
} else {
format!(
"{command} {} {}",
quote_for_shell(request_json),
quote_for_shell(response_json)
)
}
}
pub fn apply_shell_transform(
command: &str,
request: &RequestContext,
response: &serde_json::Value,
) -> Result<serde_json::Value, ShellTransformError> {
use std::process::Command;
let request_json = shell_request_json(request);
let response_json = response.to_string();
let full_command = shell_command_line(command, &request_json, &response_json);
let output = Command::new("sh")
.arg("-c")
.arg(&full_command)
.env("MB_REQUEST", &request_json)
.env("MB_RESPONSE", &response_json)
.output()
.map_err(|e| ShellTransformError::Spawn(e.to_string()))?;
if !output.status.success() {
return Err(ShellTransformError::Failed {
command: full_command,
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
});
}
let stdout = String::from_utf8_lossy(&output.stdout);
match serde_json::from_str::<serde_json::Value>(&stdout) {
Ok(serde_json::Value::Null) => Err(ShellTransformError::Null),
Ok(value) => Ok(value),
Err(_) => Err(ShellTransformError::InvalidJson(stdout.into_owned())),
}
}
#[must_use]
pub fn is_js_function_decorate(script: &str) -> bool {
let t = script.trim_start();
if is_function_head(t) {
return true;
}
t.strip_prefix("async")
.filter(|rest| rest.starts_with(|c: char| c.is_whitespace() || c == '('))
.is_some_and(|rest| is_function_head(rest.trim_start()))
}
fn is_function_head(t: &str) -> bool {
t.starts_with("function") || is_arrow_head(t)
}
fn is_arrow_head(t: &str) -> bool {
let rest = if let Some(inner) = t.strip_prefix('(') {
match inner.find(')') {
Some(close) => &inner[close + 1..],
None => return false,
}
} else {
let is_ident = |c: char| c.is_alphanumeric() || c == '_' || c == '$';
let end = t.find(|c: char| !is_ident(c)).unwrap_or(t.len());
if end == 0 || t.starts_with(|c: char| c.is_ascii_digit()) {
return false;
}
&t[end..]
};
rest.trim_start().starts_with("=>")
}
#[must_use]
pub fn is_javascript_decorate(script: &str) -> bool {
is_js_function_decorate(script) || is_js_config_decorate(script)
}
pub fn is_js_config_decorate(script: &str) -> bool {
let t = script.trim_start();
t.starts_with("config =>")
|| t.starts_with("config=>")
|| t.starts_with("(config) =>")
|| t.starts_with("(config)=>")
|| t.starts_with("function(config)")
|| t.starts_with("function (config)")
|| t.contains("config.request.")
|| t.contains("config.response.")
}
static JSON_FN_RE: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
pub fn rewrite_js_config_to_rhai(script: &str) -> String {
let body = if script.contains("=>") || script.trim_start().starts_with("function") {
match (script.find('{'), script.rfind('}')) {
(Some(open), Some(close)) => script.get(open + 1..close).unwrap_or(script),
_ => script,
}
} else {
script
};
let mut rhai = body.trim().to_string();
rhai = rhai.replace("config.request.", "request.");
rhai = rhai.replace("config.response.", "response.");
rhai = rhai.replace("const ", "let ").replace("var ", "let ");
let json_re = JSON_FN_RE
.get_or_init(|| regex::Regex::new(r"JSON\.(?:parse|stringify)\(([^()]*)\)").unwrap());
rhai = json_re.replace_all(&rhai, "$1").to_string();
rhai.replace('\'', "\"")
}
pub fn apply_decorate(
script: &str,
request: &RequestContext,
response_body: &str,
response_status: &ResponseStatus,
response_headers: &mut crate::util::OrderedMap<String, String>,
) -> Result<(String, ResponseStatus), DecorateError> {
use rhai::{Dynamic, Map, Scope};
let engine = crate::scripting::rift_rhai_engine();
let mut scope = Scope::new();
let mut req_map = Map::new();
req_map.insert("method".into(), Dynamic::from(request.method.clone()));
req_map.insert("path".into(), Dynamic::from(request.path.clone()));
req_map.insert(
"body".into(),
Dynamic::from(request.body.clone().unwrap_or_default()),
);
let values_map = crate::scripting::values_map_to_rhai;
req_map.insert("query".into(), Dynamic::from(values_map(&request.query)));
req_map.insert(
"headers".into(),
Dynamic::from(values_map(&request.headers)),
);
let mut resp_map = Map::new();
let status = match response_status {
ResponseStatus::Code(code) => Dynamic::from(i64::from(*code)),
ResponseStatus::Text(text) => Dynamic::from(text.clone()),
};
resp_map.insert("statusCode".into(), status);
resp_map.insert("body".into(), Dynamic::from(response_body.to_string()));
let mut resp_headers_map = Map::new();
for (k, v) in response_headers.iter() {
resp_headers_map.insert(k.clone().into(), Dynamic::from(v.clone()));
}
resp_map.insert("headers".into(), Dynamic::from(resp_headers_map));
scope.push("request", req_map);
scope.push("response", resp_map);
match engine.eval_with_scope::<Dynamic>(&mut scope, script) {
Ok(_) => {
match scope.get_value::<Map>("response") {
Some(response) => {
let new_body = response
.get("body")
.and_then(|v| v.clone().try_cast::<String>())
.unwrap_or_else(|| response_body.to_string());
let new_status = response
.get("statusCode")
.and_then(|v| {
v.clone()
.try_cast::<i64>()
.map(|s| ResponseStatus::Code(s as u16))
.or_else(|| {
v.clone().try_cast::<String>().map(ResponseStatus::Text)
})
})
.unwrap_or_else(|| response_status.clone());
if let Some(headers) = response.get("headers")
&& let Some(headers_map) = headers.clone().try_cast::<Map>()
{
for (k, v) in headers_map {
if let Some(value) = v.try_cast::<String>() {
response_headers.insert(k.to_string(), value);
}
}
}
Ok((new_body, new_status))
}
_ => Ok((response_body.to_string(), response_status.clone())),
}
}
Err(e) => Err(DecorateError::Rhai(e.to_string())),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn response(body: &str) -> serde_json::Value {
serde_json::json!({ "statusCode": 200, "headers": {}, "body": body })
}
fn shell_body(command: &str, request: &RequestContext, body: &str) -> String {
let out = apply_shell_transform(command, request, &response(body)).expect("runs");
out["body"].as_str().expect("a string body").to_string()
}
#[test]
fn test_apply_shell_transform_echo() {
let request = RequestContext {
method: "POST".to_string(),
path: "/test".to_string(),
body: Some(r#"{"test": "data"}"#.to_string()),
..Default::default()
};
let result = apply_shell_transform(
r#"echo '{"body": "hello world"}' #"#,
&request,
&response("original body"),
);
assert_eq!(
result,
Ok(serde_json::json!({ "body": "hello world" })),
"stdout is the parsed JSON response"
);
}
#[test]
fn mb_request_omits_absent_client_fields() {
let request = RequestContext {
method: "GET".to_string(),
path: "/p".to_string(),
..Default::default()
};
let output = apply_shell_transform(
r#"printf '{"body":%s}' "$MB_REQUEST" #"#,
&request,
&response("b"),
)
.expect("shell transform runs");
let fields = output["body"].as_object().expect("MB_REQUEST is an object");
for key in ["requestFrom", "ip", "form"] {
assert!(!fields.contains_key(key), "{key} must be absent: {output}");
}
assert_eq!(fields.get("method"), Some(&serde_json::json!("GET")));
}
#[test]
fn mb_request_body_is_empty_string_when_absent() {
let request = RequestContext {
method: "GET".to_string(),
path: "/nobody".to_string(),
body: None,
..Default::default()
};
let out = apply_shell_transform(
r#"printf '{"body":%s}' "$MB_REQUEST" #"#,
&request,
&response("x"),
)
.expect("shell transform runs");
assert_eq!(out["body"]["body"], serde_json::json!(""));
}
#[test]
fn mb_request_keeps_mountebank_key_order() {
let query = crate::util::parse_query_string("b=1&10=x&2=y&a=3");
let form = crate::util::parse_query_string("z=1&y=2");
let request = RequestContext {
method: "POST".to_string(),
path: "/p".to_string(),
query,
headers: crate::util::OrderedMap::default(),
body: Some("z=1&y=2".to_string()),
request_from: Some("127.0.0.1:1".to_string()),
ip: Some("127.0.0.1".to_string()),
form: Some(form),
..Default::default()
};
assert_eq!(
shell_request_json(&request),
r#"{"requestFrom":"127.0.0.1:1","method":"POST","path":"/p","query":{"2":"y","10":"x","b":"1","a":"3"},"headers":{},"body":"z=1&y=2","ip":"127.0.0.1","form":{"z":"1","y":"2"}}"#
);
}
#[test]
fn mb_request_keeps_header_order() {
let request = RequestContext {
method: "GET".to_string(),
path: "/".to_string(),
headers: [("Zulu", "1"), ("Alpha", "2"), ("Mike", "3"), ("Bravo", "4")]
.into_iter()
.map(|(k, v)| (k.to_string(), vec![v.to_string()]))
.collect(),
..Default::default()
};
assert_eq!(
shell_request_json(&request),
r#"{"method":"GET","path":"/","query":{},"headers":{"Zulu":"1","Alpha":"2","Mike":"3","Bravo":"4"},"body":""}"#
);
}
#[test]
fn mb_request_has_no_body_key_when_the_body_did_not_decode() {
let request = RequestContext {
method: "POST".to_string(),
path: "/gz".to_string(),
body_undefined: true,
..Default::default()
};
let json: serde_json::Value =
serde_json::from_str(&shell_request_json(&request)).expect("json");
assert!(json.get("body").is_none(), "{json}");
assert_eq!(json["method"], serde_json::json!("POST"));
}
#[test]
fn the_appended_arguments_are_the_request_and_response_json() {
let request = RequestContext {
method: "POST".to_string(),
path: "/it's".to_string(),
body: Some("a 'quoted' $HOME `x` body".to_string()),
..Default::default()
};
let resp = serde_json::json!({
"statusCode": 201, "headers": { "X-A": "it's" }, "body": "o'k \"q\""
});
let out = apply_shell_transform(
r#"f() { printf '{"body":[%s,%s,"%s"]}' "$1" "$2" "$#"; }; f"#,
&request,
&resp,
)
.expect("runs");
let body = &out["body"];
let expected: serde_json::Value =
serde_json::from_str(&shell_request_json(&request)).expect("json");
assert_eq!(body[0], expected);
assert_eq!(body[1], resp);
assert_eq!(body[2], "2", "exactly two arguments");
}
#[test]
fn mb_response_is_the_whole_response() {
let resp = serde_json::json!({
"statusCode": "${code}", "headers": { "X-A": "1", "Set-Cookie": ["a", "b"] }, "body": "o"
});
let out = apply_shell_transform(
r#"printf '{"body":%s}' "$MB_RESPONSE" #"#,
&RequestContext::default(),
&resp,
)
.expect("runs");
assert_eq!(out["body"], resp);
}
#[test]
fn a_long_command_line_drops_the_arguments() {
let padding = format!(": {};", "x".repeat(MAX_SHELL_COMMAND_LENGTH));
let command = format!(r#"{padding} f() {{ printf '{{"body":"%s"}}' "$#"; }}; f"#);
assert_eq!(shell_body(&command, &RequestContext::default(), "b"), "0");
let short = r#"f() { printf '{"body":"%s"}' "$#"; }; f"#;
assert_eq!(shell_body(short, &RequestContext::default(), "b"), "2");
}
#[test]
fn the_length_limit_is_mountebanks() {
let (req, resp) = ("{}", "{}");
let fits = "c".repeat(MAX_SHELL_COMMAND_LENGTH - 11);
assert_eq!(
shell_command_line(&fits, req, resp),
format!("{fits} '{{}}' '{{}}'")
);
let reaches = "c".repeat(MAX_SHELL_COMMAND_LENGTH - 10);
assert_eq!(shell_command_line(&reaches, req, resp), reaches);
let astral = format!("{}\u{1F600}", "c".repeat(MAX_SHELL_COMMAND_LENGTH - 12));
assert_eq!(shell_command_line(&astral, req, resp), astral);
let with_quote = "{\"a\":\"'\"}";
assert_eq!(
shell_command_line("c", with_quote, "{}"),
r#"c '{"a":"'\''"}' '{}'"#
);
let last_fit = "c".repeat(MAX_SHELL_COMMAND_LENGTH - 1 - 6 - with_quote.len() - 2);
assert_ne!(shell_command_line(&last_fit, with_quote, "{}"), last_fit);
}
#[test]
fn each_stdout_class() {
let run = |command: &str| {
apply_shell_transform(command, &RequestContext::default(), &response("b"))
};
assert_eq!(
run(r#"printf '{"body":"x"}' #"#),
Ok(serde_json::json!({ "body": "x" }))
);
assert_eq!(run("printf ' 3\n' #"), Ok(serde_json::json!(3)));
assert_eq!(run("printf null #"), Err(ShellTransformError::Null));
assert_eq!(
run("echo hello #"),
Err(ShellTransformError::InvalidJson("hello\n".to_string()))
);
assert_eq!(
run("true"),
Err(ShellTransformError::InvalidJson(String::new()))
);
let failed = run("echo bad >&2; exit 3 #").expect_err("non-zero exit");
assert!(
matches!(&failed, ShellTransformError::Failed { stderr, .. } if stderr == "bad\n"),
"{failed:?}"
);
assert!(
failed
.to_string()
.starts_with("Command failed: echo bad >&2; exit 3 # '"),
"{failed}"
);
}
#[test]
fn test_apply_decorate_modify_body() {
let request = RequestContext {
method: "GET".to_string(),
path: "/test".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: None,
..Default::default()
};
let mut headers = crate::util::OrderedMap::default();
headers.insert("content-type".to_string(), "application/json".to_string());
let script = r#"
response.body = "modified body";
"#;
let result = apply_decorate(
script,
&request,
"original body",
&ResponseStatus::Code(200),
&mut headers,
);
assert!(result.is_ok());
let (body, status) = result.unwrap();
assert_eq!(body, "modified body");
assert_eq!(status, ResponseStatus::Code(200));
}
#[test]
fn test_apply_decorate_modify_status() {
let request = RequestContext {
method: "GET".to_string(),
path: "/test".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: None,
..Default::default()
};
let mut headers = crate::util::OrderedMap::default();
let script = r#"
response.statusCode = 201;
"#;
let result = apply_decorate(
script,
&request,
"body",
&ResponseStatus::Code(200),
&mut headers,
);
assert!(result.is_ok());
let (body, status) = result.unwrap();
assert_eq!(body, "body");
assert_eq!(status, ResponseStatus::Code(201));
}
#[test]
fn test_apply_decorate_access_request() {
let request = RequestContext {
method: "POST".to_string(),
path: "/users".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: Some(r#"{"name": "Alice"}"#.to_string()),
..Default::default()
};
let mut headers = crate::util::OrderedMap::default();
let script = r#"
response.body = "Method: " + request.method + ", Path: " + request.path;
"#;
let result = apply_decorate(
script,
&request,
"original",
&ResponseStatus::Code(200),
&mut headers,
);
assert!(result.is_ok());
let (body, _status) = result.unwrap();
assert!(body.contains("Method: POST"));
assert!(body.contains("Path: /users"));
}
#[test]
fn test_apply_decorate_modify_headers() {
let request = RequestContext {
method: "GET".to_string(),
path: "/test".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: None,
..Default::default()
};
let mut headers = crate::util::OrderedMap::default();
headers.insert("content-type".to_string(), "text/plain".to_string());
let script = r#"
response.headers["x-custom"] = "custom-value";
"#;
let result = apply_decorate(
script,
&request,
"body",
&ResponseStatus::Code(200),
&mut headers,
);
assert!(result.is_ok());
assert_eq!(headers.get("x-custom"), Some(&"custom-value".to_string()));
}
#[test]
fn test_apply_decorate_script_error() {
let request = RequestContext {
method: "GET".to_string(),
path: "/test".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: None,
..Default::default()
};
let mut headers = crate::util::OrderedMap::default();
let script = "this is not valid rhai {{{";
let result = apply_decorate(
script,
&request,
"body",
&ResponseStatus::Code(200),
&mut headers,
);
assert!(result.is_err());
assert!(
result
.unwrap_err()
.to_string()
.contains("Decorate script error")
);
}
#[test]
fn is_js_config_decorate_detects_convention() {
assert!(is_js_config_decorate(
"config => { config.response.body = 'x'; }"
));
assert!(is_js_config_decorate(
"(config) => { config.response.body = 'x'; }"
));
assert!(is_js_config_decorate(
"function(config) { config.response.body = 'x'; }"
));
assert!(is_js_config_decorate("config.response.statusCode = 404;"));
assert!(!is_js_config_decorate("response.body = request.body;"));
assert!(!is_js_config_decorate(
"function(request, response) { response.body = 'x'; }"
));
}
#[test]
fn rewrite_js_config_maps_to_rhai() {
assert_eq!(
rewrite_js_config_to_rhai("config => { config.response.body = 'hello'; }").trim(),
r#"response.body = "hello";"#
);
assert_eq!(
rewrite_js_config_to_rhai("config => { config.response.body = config.request.body; }")
.trim(),
"response.body = request.body;"
);
}
#[test]
fn rewrite_js_config_simple_json_helpers_drop_to_arg() {
assert_eq!(
rewrite_js_config_to_rhai(
"config => { config.response.body = JSON.stringify(config.request.body); }"
)
.trim(),
"response.body = request.body;"
);
}
#[test]
fn every_config_spelling_is_detected_on_its_own() {
for script in [
"config => {}",
"config=>{}",
"(config) => {}",
"(config)=>{}",
"function(config) {}",
"function (config) {}",
"var p = config.request.path;",
"config.response.body = 1;",
] {
assert!(is_js_config_decorate(script), "{script}");
}
for script in ["response.body = 1;", "function(request, response) {}"] {
assert!(!is_js_config_decorate(script), "{script}");
}
}
#[test]
fn every_function_form_is_a_javascript_function_decorate() {
for script in [
"function (request, response) {}",
"function(config) {}",
"async function (r) {}",
"(request, response) => {}",
"(req, res)=>{}",
"() => 1",
"({ response }) => {}",
"request => {}",
"$r => {}",
"_ => {}",
"async (request, response) => {}",
"async(r) => {}",
"async config => {}",
"async => 1",
" \n config => {}",
] {
assert!(is_js_function_decorate(script), "{script:?}");
assert!(is_javascript_decorate(script), "{script:?}");
}
for script in [
"",
"response.body = 1;",
"(1 + 2) * 3",
"(a = f()) => 1",
"1 => 2",
"let f = |x| x + 1;",
"switch x { 1 => () }",
"asyncfn(1)",
"async x",
"config.response.body = 'x';",
] {
assert!(!is_js_function_decorate(script), "{script:?}");
}
assert!(is_javascript_decorate("config.response.body = 'x';"));
assert!(!is_javascript_decorate("response.body = 1;"));
}
#[test]
fn a_script_whose_closing_brace_precedes_its_opening_one_is_not_stripped() {
assert_eq!(
rewrite_js_config_to_rhai("config => config.response.body = '}{';").trim(),
r#"config => response.body = "}{";"#
);
}
}