use super::conditional::{self, ConditionalSpec};
use super::types::{
DebugResponsePreview, IsResponse, ResponseMode, RiftResponseExtension, RiftScriptConfig,
StubResponse,
};
use crate::behaviors::{
DecorateError, Decorated, HasRepeatBehavior, RequestContext, ResponseStatus, apply_decorate,
is_javascript_decorate,
};
#[cfg(feature = "javascript")]
use crate::behaviors::is_js_function_decorate;
#[cfg(not(feature = "javascript"))]
use crate::behaviors::{is_js_config_decorate, rewrite_js_config_to_rhai};
use crate::imposter::Predicate;
use std::sync::LazyLock;
pub(crate) fn truncate_with_ellipsis(text: &str, max_len: usize) -> String {
if text.len() <= max_len {
return text.to_string();
}
let end = text.floor_char_boundary(max_len);
format!("{}...", &text[..end])
}
impl HasRepeatBehavior for StubResponse {
fn get_repeat(&self) -> Option<u32> {
self.behaviors_block()?
.as_array()?
.first()?
.get("repeat")
.and_then(serde_json::Value::as_u64)
.and_then(|r| u32::try_from(r).ok())
}
}
pub fn create_response_preview(response: &StubResponse) -> DebugResponsePreview {
match response {
StubResponse::Is { is, .. } => {
let body_preview = is.body.as_ref().map(|b| match b {
serde_json::Value::String(s) => truncate_with_ellipsis(s, 500),
other => {
let json = serde_json::to_string(other).unwrap_or_default();
truncate_with_ellipsis(&json, 500)
}
});
let headers = if is.headers.is_empty() {
None
} else {
Some(
is.headers
.iter()
.map(|(k, v)| (k.clone(), v.join(", ")))
.collect(),
)
};
DebugResponsePreview {
response_type: "is".to_string(),
status_code: is.status_text.is_none().then_some(is.status_code),
headers,
body_preview,
}
}
StubResponse::Proxy { proxy, .. } => DebugResponsePreview {
response_type: "proxy".to_string(),
status_code: None,
headers: None,
body_preview: Some(format!("Proxy to: {}", proxy.to)),
},
StubResponse::Inject { inject, .. } => DebugResponsePreview {
response_type: "inject".to_string(),
status_code: None,
headers: None,
body_preview: Some(format!(
"JavaScript inject: {}",
truncate_with_ellipsis(inject, 50)
)),
},
StubResponse::Fault { fault, .. } => DebugResponsePreview {
response_type: "fault".to_string(),
status_code: None,
headers: None,
body_preview: Some(format!("Fault: {fault}")),
},
StubResponse::RiftScript { rift, .. } => {
let script_info = if rift.script.is_some() {
"Rift script response"
} else if rift.fault.is_some() {
"Rift fault injection"
} else {
"Rift extension response"
};
DebugResponsePreview {
response_type: "_rift".to_string(),
status_code: None,
headers: None,
body_preview: Some(script_info.to_string()),
}
}
}
}
fn has_content_type(headers: &crate::imposter::Headers) -> bool {
headers
.keys()
.any(|k| k.eq_ignore_ascii_case("content-type"))
}
fn earns_json_content_type(body: Option<&serde_json::Value>) -> bool {
matches!(
body,
Some(serde_json::Value::Object(_) | serde_json::Value::Array(_))
)
}
pub(super) fn body_text(body: Option<&serde_json::Value>) -> String {
body.map(|b| match b.as_str() {
Some(text) => text.to_string(),
None => serde_json::to_string(b).unwrap_or_default(),
})
.unwrap_or_default()
}
pub(super) fn complete_from_default(
is: &IsResponse,
default: &IsResponse,
status: &mut u16,
headers: &mut crate::imposter::Headers,
body: &mut String,
mode: &mut ResponseMode,
) {
let merged = is.completed_by(default);
*status = merged.status_code;
if is.omitted.headers {
let earned = headers.shift_remove("Content-Type");
*headers = merged.headers.clone();
if let Some(values) = earned
&& !has_content_type(headers)
{
headers.insert("Content-Type".to_string(), values);
}
}
if is.omitted.body {
*body = body_text(merged.body.as_ref());
}
*mode = merged.mode.clone();
}
#[allow(clippy::type_complexity)]
pub fn execute_stub_response_with_rift(
response: &StubResponse,
) -> Option<(
u16,
crate::imposter::Headers,
String,
Option<std::sync::Arc<crate::behaviors::BehaviorProgram>>,
Option<&RiftResponseExtension>,
ResponseMode,
bool,
)> {
match response {
StubResponse::Is {
is,
behaviors_parsed,
rift,
rendered_body,
..
} => {
let mut headers = is.headers.clone();
let mode = is.mode.clone();
let body = match rendered_body {
Some(rb) => {
if earns_json_content_type(is.body.as_ref()) && !has_content_type(&headers) {
headers.insert(
"Content-Type".to_string(),
vec!["application/json".to_string()],
);
}
rb.to_string()
}
None => is
.body
.as_ref()
.map(|b| b.as_str().unwrap_or("").to_string())
.unwrap_or_default(),
};
Some((
is.status_code,
headers,
body,
behaviors_parsed.clone(),
rift.as_deref(),
mode,
false,
))
}
StubResponse::Fault { fault, .. } => Some((
0,
crate::imposter::Headers::new(),
fault.clone(),
None,
None,
ResponseMode::Text,
true,
)),
StubResponse::Proxy { .. } => None,
StubResponse::Inject { .. } => None,
StubResponse::RiftScript { rift, .. } if rift.script.is_none() => Some((
EMPTY_IS.status_code,
EMPTY_IS.headers.clone(),
String::new(),
None,
Some(rift.as_ref()),
EMPTY_IS.mode.clone(),
false,
)),
StubResponse::RiftScript { .. } => None,
}
}
static EMPTY_IS: LazyLock<IsResponse> = LazyLock::new(IsResponse::empty);
pub(crate) fn served_is(response: &StubResponse) -> Option<&IsResponse> {
match response {
StubResponse::Is { is, .. } => Some(is),
StubResponse::RiftScript { rift, .. } if rift.script.is_none() => Some(&EMPTY_IS),
StubResponse::Fault { .. }
| StubResponse::Proxy { .. }
| StubResponse::Inject { .. }
| StubResponse::RiftScript { .. } => None,
}
}
#[derive(Debug)]
pub struct PreparedResponse {
status: hyper::StatusCode,
headers: hyper::HeaderMap,
body: bytes::Bytes,
conditional: Option<PreparedConditional>,
}
#[derive(Debug)]
struct PreparedConditional {
spec: ConditionalSpec,
etag: Option<String>,
}
impl PreparedResponse {
#[must_use]
pub fn try_build(
is: &IsResponse,
rendered_body: Option<&std::sync::Arc<str>>,
rift: Option<&RiftResponseExtension>,
behaviors_present: bool,
) -> Option<PreparedResponse> {
if is.mode != ResponseMode::Text || behaviors_present || is.status_text.is_some() {
return None;
}
if let Some(r) = rift
&& (r.fault.is_some() || r.templated || r.script.is_some() || !r.state_ops.is_empty())
{
return None;
}
let body_string: String = match rendered_body {
Some(rb) => rb.to_string(),
None => is
.body
.as_ref()
.and_then(|b| b.as_str())
.unwrap_or_default()
.to_string(),
};
if crate::extensions::template::has_template_variables(&body_string)
|| is
.headers
.values()
.flatten()
.any(|v| crate::extensions::template::has_template_variables(v))
|| crate::extensions::contains_date_templates(&body_string)
{
return None;
}
let has_content_type = has_content_type(&is.headers);
let mut headers = hyper::HeaderMap::new();
for (name, values) in &is.headers {
let header_name = hyper::header::HeaderName::from_bytes(name.as_bytes()).ok()?;
for value in values {
let header_value = hyper::header::HeaderValue::from_str(value).ok()?;
headers.append(header_name.clone(), header_value);
}
}
if earns_json_content_type(is.body.as_ref()) && !has_content_type {
headers.append(
hyper::header::CONTENT_TYPE,
hyper::header::HeaderValue::from_static("application/json"),
);
}
headers.append(
hyper::header::HeaderName::from_static("x-rift-imposter"),
hyper::header::HeaderValue::from_static("true"),
);
let status = hyper::StatusCode::from_u16(is.status_code).ok()?;
let conditional = ConditionalSpec::from_config(rift.and_then(|r| r.conditional.as_ref()))
.filter(|_| status.is_success())
.map(|spec| PreparedConditional {
etag: spec
.wants_etag()
.then(|| conditional::etag_for(body_string.as_bytes())),
spec,
});
Some(PreparedResponse {
status,
headers,
body: bytes::Bytes::from(body_string),
conditional,
})
}
pub(crate) fn serve_request(
&self,
method: &str,
request_headers: &crate::util::OrderedMap<String, Vec<String>>,
loaded_at: impl FnOnce() -> chrono::DateTime<chrono::Utc>,
) -> Result<hyper::Response<http_body_util::Full<bytes::Bytes>>, hyper::http::Error> {
let Some(prepared) = self
.conditional
.as_ref()
.filter(|_| conditional::method_applies(method))
else {
return Ok(self.serve());
};
let validators = prepared.spec.validators(prepared.etag.clone(), loaded_at());
if validators.not_modified(request_headers) {
return validators.not_modified_response(
self.headers
.iter()
.filter(|(name, _)| conditional::kept_on_304(name.as_str())),
);
}
let mut response = self.serve();
let headers = response.headers_mut();
headers.remove(hyper::header::ETAG);
headers.remove(hyper::header::LAST_MODIFIED);
for (name, value) in validators.headers() {
headers.insert(name, hyper::header::HeaderValue::from_str(value)?);
}
Ok(response)
}
pub fn serve(&self) -> hyper::Response<http_body_util::Full<bytes::Bytes>> {
let (mut parts, ()) = hyper::Response::new(()).into_parts();
parts.status = self.status;
parts.headers = self.headers.clone();
hyper::Response::from_parts(parts, http_body_util::Full::new(self.body.clone()))
}
}
pub fn get_rift_script_config(response: &StubResponse) -> Option<RiftScriptConfig> {
match response {
StubResponse::RiftScript { rift, .. } => rift.script.clone(),
_ => None,
}
}
#[allow(clippy::too_many_arguments)]
pub fn create_stub_from_proxy_response(
predicates: Vec<Predicate>,
status: u16,
headers: &[(String, String)],
body: &[u8],
latency_ms: Option<u64>,
decorate_fn: Option<String>,
recorded_from: Option<String>,
response_time_ms: u64,
) -> super::types::Stub {
let response_headers: crate::imposter::Headers = {
let mut map: crate::imposter::Headers = crate::imposter::Headers::new();
for (k, v) in headers {
if crate::util::is_hop_by_hop_header(k) {
continue;
}
let existing = map
.keys()
.find(|name| name.eq_ignore_ascii_case(k))
.cloned();
let name = existing.unwrap_or_else(|| {
if k.bytes().any(|b| b.is_ascii_uppercase()) {
k.clone()
} else {
crate::behaviors::header_to_title_case(k)
}
});
map.entry(name).or_default().push(v.clone());
}
map
};
let (body_value, is_binary) = crate::util::encode_body_for_stub(body);
let body_value = body_value.or_else(|| Some(serde_json::Value::String(String::new())));
let mode = if is_binary {
ResponseMode::Binary
} else {
ResponseMode::Text
};
let mut is_response = IsResponse::new(status, response_headers, body_value, mode);
is_response.proxy_response_time = Some(serde_json::Value::from(response_time_ms));
let behaviors = if latency_ms.is_some() || decorate_fn.is_some() {
let mut behaviors_obj = serde_json::Map::new();
if let Some(ms) = latency_ms {
behaviors_obj.insert("wait".to_string(), serde_json::json!(ms));
}
if let Some(fn_str) = decorate_fn {
behaviors_obj.insert("decorate".to_string(), serde_json::json!(fn_str));
}
Some(serde_json::Value::Object(behaviors_obj))
} else {
None
};
super::types::Stub {
name: None,
id: None,
route_pattern: None,
predicates,
responses: vec![StubResponse::new_is(is_response, behaviors, None)],
scenario_name: None,
required_scenario_state: None,
new_scenario_state: None,
space: None,
recorded_from,
recorded_at: None,
verify: None,
}
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub fn apply_js_or_rhai_decorate(
script: &str,
request: &RequestContext,
body: &str,
status: &ResponseStatus,
headers: &crate::util::OrderedMap<String, String>,
scope: &crate::scripting::ScriptScope,
stub_id: Option<&str>,
files: &std::sync::Arc<crate::imposter::ScriptFileAccess>,
) -> Result<Decorated, DecorateError> {
apply_js_or_rhai_decorate_within(
script,
request,
body,
status,
headers,
scope,
stub_id,
files,
std::time::Duration::from_millis(crate::scripting::DEFAULT_SCRIPT_TIMEOUT_MS),
)
}
#[allow(clippy::too_many_arguments)]
fn apply_js_or_rhai_decorate_within(
script: &str,
request: &RequestContext,
body: &str,
status: &ResponseStatus,
headers: &crate::util::OrderedMap<String, String>,
scope: &crate::scripting::ScriptScope,
stub_id: Option<&str>,
files: &std::sync::Arc<crate::imposter::ScriptFileAccess>,
timeout: std::time::Duration,
) -> Result<Decorated, DecorateError> {
#[cfg(not(feature = "javascript"))]
let _ = (scope, stub_id, files, timeout);
if !is_javascript_decorate(script) {
return decorate_rhai(script, request, body, status, headers);
}
#[cfg(feature = "javascript")]
{
let (wrapped_script, mb_request) = js_decorate_input(script, request);
crate::scripting::execute_mountebank_decorate_within(
&wrapped_script,
&mb_request,
body,
status,
headers,
scope.clone(),
stub_id,
files,
timeout,
)
.map_err(js_decorate_error)
}
#[cfg(not(feature = "javascript"))]
{
if is_js_config_decorate(script) {
return decorate_rhai(
&rewrite_js_config_to_rhai(script),
request,
body,
status,
headers,
);
}
if script.trim().starts_with("function")
&& let Some(start) = script.find('{')
&& let Some(end) = script.rfind('}')
&& start < end
{
let rhai_script = script[start + 1..end].trim().replace('\'', "\"");
return decorate_rhai(&rhai_script, request, body, status, headers);
}
Err(DecorateError::JsParseFailure)
}
}
#[cfg(feature = "javascript")]
fn js_decorate_input(
script: &str,
request: &RequestContext,
) -> (String, crate::scripting::MountebankRequest) {
let mb_request = crate::scripting::MountebankRequest {
method: request.method.clone(),
path: request.path.clone(),
query: request.query.clone(),
headers: request.headers.clone(),
body: request.body.clone(),
body_undefined: request.body_undefined,
mode: None,
request_from: request.request_from.clone(),
ip: request.ip.clone(),
form: request.form.clone(),
is_dry_run: false,
};
let wrapped_script = if is_js_function_decorate(script) {
script.to_string()
} else {
format!("function(config) {{ {script} }}")
};
(wrapped_script, mb_request)
}
#[cfg(feature = "javascript")]
fn js_decorate_error(e: anyhow::Error) -> DecorateError {
match e.downcast_ref::<crate::scripting::ScriptTimeoutError>() {
Some(t) => DecorateError::Timeout(t.timeout_ms),
None => DecorateError::JavaScript(e.to_string()),
}
}
fn decorate_rhai(
script: &str,
request: &RequestContext,
body: &str,
status: &ResponseStatus,
headers: &crate::util::OrderedMap<String, String>,
) -> Result<Decorated, DecorateError> {
let mut headers = headers.clone();
let (body, status_code) = apply_decorate(script, request, body, status, &mut headers)?;
Ok(Decorated {
status_code,
headers,
body,
returned: None,
})
}
#[allow(clippy::too_many_arguments)]
pub async fn apply_decorate_bounded(
script: String,
request: RequestContext,
body: String,
status: ResponseStatus,
headers: crate::util::OrderedMap<String, String>,
scope: crate::scripting::ScriptScope,
stub_id: Option<String>,
files: std::sync::Arc<crate::imposter::ScriptFileAccess>,
timeout: std::time::Duration,
) -> Result<Decorated, DecorateError> {
#[cfg(feature = "javascript")]
if is_javascript_decorate(&script) {
let (wrapped_script, mb_request) = js_decorate_input(&script, &request);
return crate::scripting::execute_mountebank_decorate_bounded(
wrapped_script,
mb_request,
body,
status,
headers,
scope,
stub_id,
files,
timeout,
)
.await
.map_err(|e| {
let e = js_decorate_error(e);
if let DecorateError::Timeout(ms) = e {
tracing::warn!("decorate script timed out after {ms}ms");
}
e
});
}
let timeout_ms = u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX);
let handle = tokio::task::spawn_blocking(move || {
apply_js_or_rhai_decorate_within(
&script,
&request,
&body,
&status,
&headers,
&scope,
stub_id.as_deref(),
&files,
timeout,
)
});
match tokio::time::timeout(timeout, handle).await {
Ok(Ok(result)) => result,
Ok(Err(join_err)) => Err(DecorateError::JavaScript(format!(
"decorate task panicked: {join_err}"
))),
Err(_elapsed) => {
tracing::warn!("decorate script timed out after {timeout_ms}ms");
Err(DecorateError::Timeout(timeout_ms))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scripting::ScriptScope;
fn trusted_files() -> std::sync::Arc<crate::imposter::ScriptFileAccess> {
std::sync::Arc::new(crate::imposter::ScriptFileAccess::trusted_cwd())
}
fn test_port() -> u16 {
use std::sync::atomic::{AtomicU32, Ordering};
static NEXT: AtomicU32 = AtomicU32::new(41_100);
NEXT.fetch_add(1, Ordering::Relaxed) as u16
}
fn decorate_req() -> RequestContext {
RequestContext {
method: "GET".to_string(),
path: "/orders".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: Some("REQ-BODY".to_string()),
..Default::default()
}
}
#[test]
fn decorate_js_config_sets_body() {
let headers = crate::util::OrderedMap::default();
let Decorated {
body,
status_code: status,
..
} = apply_js_or_rhai_decorate(
"config => { config.response.body = 'hello'; }",
&decorate_req(),
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.unwrap();
assert_eq!(body, "hello");
assert_eq!(status, ResponseStatus::Code(200));
}
#[test]
fn decorate_js_config_reads_request_body() {
let headers = crate::util::OrderedMap::default();
let Decorated { body, .. } = apply_js_or_rhai_decorate(
"config => { config.response.body = config.request.body; }",
&decorate_req(),
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.unwrap();
assert_eq!(body, "REQ-BODY");
}
#[cfg(feature = "javascript")]
#[test]
fn decorate_js_config_require_routes_to_boa() {
use std::sync::atomic::{AtomicU32, Ordering};
static SEQ: AtomicU32 = AtomicU32::new(0);
let n = SEQ.fetch_add(1, Ordering::Relaxed);
let module =
std::env::temp_dir().join(format!("rift_305_route_{}_{n}.cjs", std::process::id()));
std::fs::write(
&module,
"module.exports = function (config) { config.response.body = 'REQUIRE-RAN'; };\n",
)
.unwrap();
let script = format!(
"config => {{ const s = require('{}'); s(config); }}",
module.display()
);
let headers = crate::util::OrderedMap::default();
let result = apply_js_or_rhai_decorate(
&script,
&decorate_req(),
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
);
let _ = std::fs::remove_file(&module);
let Decorated { body, .. } = result.expect("require-based config decorate should run");
assert_eq!(body, "REQUIRE-RAN");
}
#[cfg(feature = "javascript")]
#[test]
fn decorate_js_config_real_json_parse_and_mutation_runs_through_boa() {
let headers = crate::util::OrderedMap::default();
let request = RequestContext {
method: "POST".to_string(),
path: "/orders".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: Some(r#"{"order": {"id": 42, "items": ["a", "b"]}}"#.to_string()),
..Default::default()
};
let script = r#"config => {
var parsed = JSON.parse(config.request.body);
parsed.order.itemCount = parsed.order.items.length;
delete parsed.order.items;
config.response.body = JSON.stringify(parsed);
}"#;
let Decorated { body, .. } = apply_js_or_rhai_decorate(
script,
&request,
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.expect("real JS JSON.parse/stringify decorate must execute via Boa");
let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(parsed["order"]["id"], 42);
assert_eq!(parsed["order"]["itemCount"], 2);
assert!(parsed["order"].get("items").is_none());
}
#[cfg(feature = "javascript")]
#[test]
fn decorate_bare_body_with_inner_arrow_runs_through_boa() {
let headers = crate::util::OrderedMap::default();
let request = RequestContext {
method: "GET".to_string(),
path: "/orders".to_string(),
query: Default::default(),
headers: crate::util::OrderedMap::default(),
body: None,
..Default::default()
};
let script =
r#"config.response.body = JSON.stringify([{id:1},{id:2},{id:3}].map(x => x.id));"#;
let Decorated { body, .. } = apply_js_or_rhai_decorate(
script,
&request,
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.expect("bare-body decorate with an inner arrow must execute via Boa");
let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
assert_eq!(parsed, serde_json::json!([1, 2, 3]));
}
#[test]
fn decorate_js_config_sets_status() {
let headers = crate::util::OrderedMap::default();
let Decorated {
status_code: status,
..
} = apply_js_or_rhai_decorate(
"config => { config.response.statusCode = 404; }",
&decorate_req(),
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.unwrap();
assert_eq!(status, ResponseStatus::Code(404));
}
#[test]
fn decorate_js_config_function_wrapper_executes() {
let headers = crate::util::OrderedMap::default();
let Decorated { body, .. } = apply_js_or_rhai_decorate(
"function(config) { config.response.body = 'fn'; }",
&decorate_req(),
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.unwrap();
assert_eq!(body, "fn");
}
#[test]
fn decorate_js_config_no_wrapper_executes() {
let headers = crate::util::OrderedMap::default();
let Decorated { body, .. } = apply_js_or_rhai_decorate(
"config.response.body = 'bare';",
&decorate_req(),
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.unwrap();
assert_eq!(body, "bare");
}
#[test]
fn decorate_plain_rhai_still_works() {
let headers = crate::util::OrderedMap::default();
let Decorated { body, .. } = apply_js_or_rhai_decorate(
"response.body = request.path;",
&decorate_req(),
"original",
&ResponseStatus::Code(200),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.unwrap();
assert_eq!(body, "/orders", "existing Rhai decorate must be unchanged");
}
#[cfg(feature = "javascript")]
fn decorate_1567(
script: &str,
status: u16,
) -> (
String,
ResponseStatus,
crate::util::OrderedMap<String, String>,
) {
let headers = crate::util::OrderedMap::from_iter([("X-Orig".to_string(), "1".to_string())]);
let Decorated {
body,
status_code: status,
headers,
..
} = apply_js_or_rhai_decorate(
script,
&decorate_req(),
"orig",
&ResponseStatus::Code(status),
&headers,
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
)
.unwrap_or_else(|e| panic!("{script}: {e}"));
(body, status, headers)
}
#[cfg(feature = "javascript")]
#[test]
fn a_decorate_unserializable_body_fails_the_decorate() {
for script in [
"(req, res) => { const o = {}; o.self = o; res.body = o; }",
"(req, res) => ({ body: { n: 10n } })",
] {
let result = apply_js_or_rhai_decorate(
script,
&decorate_req(),
"orig",
&ResponseStatus::Code(200),
&crate::util::OrderedMap::default(),
&ScriptScope::detached(test_port()),
None,
&trusted_files(),
);
assert!(result.is_err(), "{script}");
}
}
#[cfg(feature = "javascript")]
#[test]
fn a_decorate_status_is_read_as_mountebank_reads_it() {
for (script, want) in [
(
"(req, res) => { res.statusCode = null; }",
ResponseStatus::Code(0),
),
(
"(req, res) => { res.statusCode = NaN; }",
ResponseStatus::Code(0),
),
(
"(req, res) => { delete res.statusCode; }",
ResponseStatus::Code(0),
),
(
"(req, res) => { res.statusCode = -1; }",
ResponseStatus::Text("-1".to_string()),
),
(
"(req, res) => { res.statusCode = 404; }",
ResponseStatus::Code(404),
),
] {
let (_, status, _) = decorate_1567(script, 201);
assert_eq!(status, want, "{script}");
}
}
#[cfg(feature = "javascript")]
#[test]
fn every_arrow_form_runs_as_javascript() {
for (script, want) in [
(
"(request, response) => { response.body = 'mutated ' + request.path; }",
"mutated /orders",
),
("(req, res) => { res.body = 'a'; }", "a"),
("request => { request.response.body = 'si'; }", "si"),
(
"async (request, response) => { response.body = 'as'; }",
"as",
),
("async config => { config.response.body = 'ac'; }", "ac"),
] {
let (body, status, headers) = decorate_1567(script, 200);
assert_eq!(body, want, "{script}");
assert_eq!(status, ResponseStatus::Code(200), "{script}");
assert_eq!(headers.get("X-Orig").map(String::as_str), Some("1"));
}
}
#[cfg(feature = "javascript")]
#[test]
fn a_returned_object_replaces_the_response() {
let (body, status, headers) = decorate_1567(
"function (request, response) { return { body: 'returned' }; }",
404,
);
assert_eq!(body, "returned");
assert_eq!(
status,
ResponseStatus::Code(200),
"an omitted status is 200"
);
assert!(headers.is_empty(), "the returned object has no headers");
let (body, status, _) =
decorate_1567("config => ({ statusCode: 201, body: 'cfgret' })", 200);
assert_eq!(
(body.as_str(), status),
("cfgret", ResponseStatus::Code(201))
);
let (body, status, headers) =
decorate_1567("config => ({ headers: { 'X-New': 'n' }, body: 'b' })", 404);
assert_eq!((body.as_str(), status), ("b", ResponseStatus::Code(200)));
assert_eq!(
headers,
crate::util::OrderedMap::from_iter([("X-New".to_string(), "n".to_string())])
);
}
#[cfg(feature = "javascript")]
#[test]
fn a_falsy_return_keeps_the_mutated_response() {
let (body, status, headers) =
decorate_1567("config => { config.response.body = 'mut'; return 0; }", 404);
assert_eq!((body.as_str(), status), ("mut", ResponseStatus::Code(404)));
assert_eq!(headers.get("X-Orig").map(String::as_str), Some("1"));
}
#[cfg(feature = "javascript")]
#[test]
fn a_deleted_header_is_gone_in_both_forms() {
for script in [
"config => { delete config.response.headers['X-Orig']; config.response.body = 'd'; }",
"function (request, response) { delete response.headers['X-Orig']; response.body = 'd'; }",
"(request, response) => { delete response.headers['X-Orig']; response.body = 'd'; }",
] {
let (body, _, headers) = decorate_1567(script, 200);
assert_eq!(body, "d", "{script}");
assert!(!headers.contains_key("X-Orig"), "{script}: {headers:?}");
}
}
#[test]
fn test_create_stub_preserves_multi_valued_headers() {
let headers = vec![
("Set-Cookie".to_string(), "session=abc".to_string()),
("Set-Cookie".to_string(), "theme=dark".to_string()),
("Content-Type".to_string(), "text/html".to_string()),
];
let stub =
create_stub_from_proxy_response(vec![], 200, &headers, b"OK", None, None, None, 0);
match &stub.responses[0] {
StubResponse::Is { is, .. } => {
let cookies = is.headers.get("Set-Cookie").unwrap();
assert_eq!(
cookies,
&vec!["session=abc".to_string(), "theme=dark".to_string()],
"Multi-valued Set-Cookie headers are preserved as separate values"
);
assert_eq!(
is.headers.get("Content-Type").unwrap(),
&vec!["text/html".to_string()]
);
}
_ => panic!("Expected StubResponse::Is"),
}
}
fn recorded_headers(headers: &[(&str, &str)]) -> crate::imposter::Headers {
let headers: Vec<(String, String)> = headers
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let stub =
create_stub_from_proxy_response(vec![], 200, &headers, b"OK", None, None, None, 0);
match &stub.responses[0] {
StubResponse::Is { is, .. } => is.headers.clone(),
_ => panic!("Expected StubResponse::Is"),
}
}
#[test]
fn recorded_stub_title_cases_upstream_header_names() {
let headers = recorded_headers(&[
("content-type", "application/json"),
("x-request-id", "7"),
("X-DECORATED", "d"),
]);
let mut names: Vec<&str> = headers.keys().map(String::as_str).collect();
names.sort_unstable();
assert_eq!(names, ["Content-Type", "X-DECORATED", "X-Request-Id"]);
}
#[test]
fn recorded_stub_merges_case_variants_upstream_first() {
let headers = recorded_headers(&[("set-cookie", "a"), ("Set-Cookie", "b")]);
assert_eq!(headers.len(), 1, "{headers:?}");
assert_eq!(headers["Set-Cookie"], ["a", "b"]);
}
#[test]
fn test_create_stub_hop_by_hop_headers_filtered() {
let headers = vec![
("Content-Type".to_string(), "text/html".to_string()),
("Transfer-Encoding".to_string(), "chunked".to_string()),
("Connection".to_string(), "keep-alive".to_string()),
("Keep-Alive".to_string(), "timeout=5".to_string()),
];
let stub =
create_stub_from_proxy_response(vec![], 200, &headers, b"OK", None, None, None, 0);
match &stub.responses[0] {
StubResponse::Is { is, .. } => {
assert!(is.headers.contains_key("Content-Type"));
assert!(
!is.headers.contains_key("Transfer-Encoding"),
"Transfer-Encoding should be filtered"
);
assert!(
!is.headers.contains_key("Connection"),
"Connection should be filtered"
);
assert!(
!is.headers.contains_key("Keep-Alive"),
"Keep-Alive should be filtered"
);
}
_ => panic!("Expected StubResponse::Is"),
}
}
#[test]
fn test_create_stub_binary_body_base64_encoded() {
let binary_body: Vec<u8> = vec![0x00, 0xFF, 0xFE, 0xFD, 0x89, 0x50, 0x4E, 0x47];
let stub =
create_stub_from_proxy_response(vec![], 200, &[], &binary_body, None, None, None, 0);
match &stub.responses[0] {
StubResponse::Is { is, .. } => {
assert_eq!(is.mode, ResponseMode::Binary, "Binary body should set mode");
use base64::Engine;
let expected_b64 = base64::engine::general_purpose::STANDARD.encode(&binary_body);
assert_eq!(
is.body.as_ref().unwrap().as_str().unwrap(),
expected_b64,
"Binary body should be base64-encoded"
);
}
_ => panic!("Expected StubResponse::Is"),
}
}
#[test]
fn test_create_stub_text_body_not_base64() {
let stub = create_stub_from_proxy_response(
vec![],
200,
&[],
b"Hello, World!",
None,
None,
None,
0,
);
match &stub.responses[0] {
StubResponse::Is { is, .. } => {
assert_eq!(
is.mode,
ResponseMode::Text,
"Text body should use text mode"
);
assert_eq!(is.body.as_ref().unwrap().as_str().unwrap(), "Hello, World!");
}
_ => panic!("Expected StubResponse::Is"),
}
}
#[test]
fn test_create_stub_json_body_parsed() {
let stub = create_stub_from_proxy_response(
vec![],
200,
&[],
br#"{"key": "value"}"#,
None,
None,
None,
0,
);
match &stub.responses[0] {
StubResponse::Is { is, .. } => {
assert_eq!(is.mode, ResponseMode::Text);
let body = is.body.as_ref().unwrap();
assert!(body.is_object(), "JSON body should be parsed as object");
assert_eq!(body["key"], "value");
}
_ => panic!("Expected StubResponse::Is"),
}
}
#[test]
fn test_create_stub_empty_body() {
let stub = create_stub_from_proxy_response(vec![], 204, &[], b"", None, None, None, 0);
match &stub.responses[0] {
StubResponse::Is { is, .. } => {
assert_eq!(is.mode, ResponseMode::Text);
assert_eq!(
is.body,
Some(serde_json::json!("")),
"an empty body is a written body, so a defaultResponse never fills it (#1369)"
);
}
_ => panic!("Expected StubResponse::Is"),
}
}
#[test]
fn test_create_stub_with_latency_and_decorate() {
let stub = create_stub_from_proxy_response(
vec![],
200,
&[],
b"OK",
Some(150),
Some("function(request, response) {}".to_string()),
None,
0,
);
match &stub.responses[0] {
StubResponse::Is { behaviors, .. } => {
assert_eq!(
behaviors.as_ref().unwrap(),
&serde_json::json!([
{"wait": 150},
{"decorate": "function(request, response) {}"}
])
);
}
_ => panic!("Expected StubResponse::Is"),
}
}
#[test]
fn test_truncate_with_ellipsis_short_string() {
assert_eq!(truncate_with_ellipsis("hello", 10), "hello");
}
#[test]
fn test_truncate_with_ellipsis_exact_length() {
assert_eq!(truncate_with_ellipsis("hello", 5), "hello");
}
#[test]
fn test_truncate_with_ellipsis_long_string() {
assert_eq!(truncate_with_ellipsis("hello world", 5), "hello...");
}
#[test]
fn test_truncate_with_ellipsis_unicode_safe() {
let text = "日本語";
assert_eq!(text.len(), 9);
assert_eq!(truncate_with_ellipsis(text, 5), "日...");
}
#[test]
fn test_truncate_with_ellipsis_emoji() {
let text = "👋🌍🎉";
assert_eq!(truncate_with_ellipsis(text, 5), "👋...");
}
#[test]
fn test_truncate_with_ellipsis_mixed_content() {
let text = "Hello 世界!";
assert_eq!(truncate_with_ellipsis(text, 8), "Hello ...");
}
#[test]
fn test_truncate_with_ellipsis_empty_string() {
assert_eq!(truncate_with_ellipsis("", 10), "");
}
#[test]
fn test_truncate_with_ellipsis_zero_max_len() {
assert_eq!(truncate_with_ellipsis("hello", 0), "...");
}
#[test]
fn test_create_stub_recorded_from_populated() {
let stub = create_stub_from_proxy_response(
vec![],
200,
&[],
b"OK",
None,
None,
Some("http://upstream:8080".to_string()),
42,
);
assert_eq!(stub.recorded_from.as_deref(), Some("http://upstream:8080"));
}
#[test]
fn a_recorded_response_carries_its_proxy_response_time() {
let stub = create_stub_from_proxy_response(vec![], 200, &[], b"OK", None, None, None, 42);
assert!(stub.responses[0].is_recorded());
assert_eq!(
serde_json::to_value(&stub.responses[0]).expect("prints")["is"]["_proxyResponseTime"],
42
);
}
#[test]
fn test_create_stub_recorded_from_none_when_not_provided() {
let stub = create_stub_from_proxy_response(vec![], 200, &[], b"OK", None, None, None, 0);
assert!(stub.recorded_from.is_none());
}
#[cfg(feature = "javascript")]
#[tokio::test]
async fn mb_decorate_bounded_applies() {
let Decorated {
body,
status_code: status,
..
} = apply_decorate_bounded(
"function (request, response) { response.body = response.body + '-decorated'; }"
.to_string(),
decorate_req(),
"orig".to_string(),
ResponseStatus::Code(200),
crate::util::OrderedMap::default(),
ScriptScope::detached(test_port()),
None,
trusted_files(),
std::time::Duration::from_millis(60_000),
)
.await
.expect("fast decorate");
assert_eq!(body, "orig-decorated");
assert_eq!(status, ResponseStatus::Code(200));
}
#[cfg(feature = "javascript")]
#[tokio::test]
async fn mb_decorate_bounded_times_out() {
let start = std::time::Instant::now();
let res = apply_decorate_bounded(
"function (request, response) { var i = 0; while (i < 100000000) { i += 1; } }"
.to_string(),
decorate_req(),
"orig".to_string(),
ResponseStatus::Code(200),
crate::util::OrderedMap::default(),
ScriptScope::detached(test_port()),
None,
trusted_files(),
std::time::Duration::from_millis(25),
)
.await;
match res {
Err(DecorateError::Timeout(ms)) => assert_eq!(ms, 25),
other => panic!("expected DecorateError::Timeout, got {other:?}"),
}
assert!(
start.elapsed() < std::time::Duration::from_secs(3),
"must return near the configured deadline, not after the loop cap"
);
}
#[cfg(feature = "javascript")]
#[tokio::test]
async fn mb_decorate_bounded_timer_past_the_deadline_times_out() {
let res = apply_decorate_bounded(
"async config => { await new Promise(r => setTimeout(r, 10000)); }".to_string(),
decorate_req(),
"orig".to_string(),
ResponseStatus::Code(200),
crate::util::OrderedMap::default(),
ScriptScope::detached(test_port()),
None,
trusted_files(),
std::time::Duration::from_millis(100),
)
.await;
match res {
Err(DecorateError::Timeout(ms)) => assert_eq!(ms, 100),
other => panic!("expected DecorateError::Timeout, got {other:?}"),
}
}
}
#[cfg(test)]
mod prepared_response_tests {
use super::*;
use crate::imposter::types::{IsResponse, ResponseMode, StubResponse};
use serde_json::json;
fn is_response(
status: u16,
headers: &[(&str, &str)],
body: Option<serde_json::Value>,
) -> IsResponse {
let mut map: crate::imposter::Headers = crate::imposter::Headers::new();
for (k, v) in headers {
map.entry((*k).to_string())
.or_default()
.push((*v).to_string());
}
IsResponse::new(status, map, body, ResponseMode::Text)
}
fn prepared_of(resp: &StubResponse) -> Option<&PreparedResponse> {
match resp {
StubResponse::Is { prepared, .. } => prepared.as_deref(),
_ => None,
}
}
fn header_multiset(pairs: impl IntoIterator<Item = (String, String)>) -> Vec<(String, String)> {
let mut v: Vec<(String, String)> = pairs
.into_iter()
.map(|(k, val)| (k.to_lowercase(), val))
.collect();
v.sort();
v
}
fn legacy_serve(resp: &StubResponse) -> (u16, Vec<(String, String)>, Vec<u8>) {
let (status, headers, body, _behaviors, _rift, mode, _fault) =
execute_stub_response_with_rift(resp).expect("static is executes");
assert_eq!(mode, ResponseMode::Text, "corpus is text-only");
let mut pairs: Vec<(String, String)> = Vec::new();
for (k, values) in &headers {
for v in values {
pairs.push((k.clone(), v.clone()));
}
}
pairs.push(("x-rift-imposter".to_string(), "true".to_string()));
let body_bytes = crate::extensions::apply_date_templates(&body).into_bytes();
(status, header_multiset(pairs), body_bytes)
}
fn prepared_serve(prep: &PreparedResponse) -> (u16, Vec<(String, String)>, Vec<u8>) {
(
prep.status.as_u16(),
header_multiset(
prep.headers
.iter()
.map(|(k, v)| (k.as_str().to_string(), v.to_str().unwrap().to_string())),
),
prep.body.to_vec(),
)
}
#[test]
fn prepared_matches_legacy_for_static_corpus() {
let corpus = vec![
StubResponse::new_is(
is_response(200, &[], Some(json!("plain string body"))),
None,
None,
),
StubResponse::new_is(
is_response(201, &[], Some(json!({"id": 1, "name": "x"}))),
None,
None,
),
StubResponse::new_is(is_response(204, &[], None), None, None),
StubResponse::new_is(
is_response(
200,
&[("Content-Type", "text/plain"), ("X-A", "1")],
Some(json!("ok")),
),
None,
None,
),
StubResponse::new_is(
is_response(
200,
&[("Set-Cookie", "a=1"), ("Set-Cookie", "b=2")],
Some(json!("multi")),
),
None,
None,
),
StubResponse::new_is(is_response(200, &[], Some(json!({"k": "v"}))), None, None),
StubResponse::new_is(
is_response(
200,
&[("CONTENT-TYPE", "application/xml")],
Some(json!({"k": "v"})),
),
None,
None,
),
StubResponse::new_is(is_response(200, &[], Some(json!([1, 2, 3]))), None, None),
StubResponse::new_is(is_response(200, &[], Some(json!(42))), None, None),
];
for resp in &corpus {
let prep = prepared_of(resp).expect("static response must be prepared");
assert_eq!(
prepared_serve(prep),
legacy_serve(resp),
"fast path diverged from legacy"
);
}
}
#[test]
fn a_scalar_json_body_earns_no_content_type() {
for body in [json!(42), json!(true)] {
let resp = StubResponse::new_is(is_response(200, &[], Some(body.clone())), None, None);
let (_s, prepared, b) = prepared_serve(prepared_of(&resp).unwrap());
assert_eq!(b, body.to_string().into_bytes());
assert!(
!prepared
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("content-type")),
"{body}: {prepared:?}"
);
let (_s, legacy, _b) = legacy_serve(&resp);
assert!(
!legacy
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("content-type")),
"{body}: {legacy:?}"
);
}
}
#[test]
fn content_type_default_and_marker_present_for_json_body() {
let resp = StubResponse::new_is(is_response(200, &[], Some(json!({"k": "v"}))), None, None);
let (_s, headers, _b) = prepared_serve(prepared_of(&resp).unwrap());
assert!(headers.contains(&("content-type".to_string(), "application/json".to_string())));
assert!(headers.contains(&("x-rift-imposter".to_string(), "true".to_string())));
}
#[test]
fn explicit_content_type_is_not_overridden() {
let resp = StubResponse::new_is(
is_response(
200,
&[("content-type", "application/xml")],
Some(json!({"k": "v"})),
),
None,
None,
);
let (_s, headers, _b) = prepared_serve(prepared_of(&resp).unwrap());
let cts: Vec<_> = headers
.iter()
.filter(|(k, _)| k == "content-type")
.collect();
assert_eq!(
cts.len(),
1,
"no duplicate Content-Type when one is configured"
);
assert_eq!(cts[0].1, "application/xml");
}
#[test]
fn oddly_cased_content_type_not_duplicated() {
let resp = StubResponse::new_is(
is_response(
200,
&[("CONTENT-TYPE", "application/xml")],
Some(json!({"k": "v"})),
),
None,
None,
);
for (label, served) in [
("execute", legacy_serve(&resp)),
("prepared", prepared_serve(prepared_of(&resp).unwrap())),
] {
let cts: Vec<_> = served
.1
.iter()
.filter(|(k, _)| k == "content-type")
.collect();
assert_eq!(
cts.len(),
1,
"{label}: no duplicate Content-Type for an oddly-cased config header"
);
assert_eq!(
cts[0].1, "application/xml",
"{label}: keeps the configured value"
);
}
}
#[test]
fn behaviors_force_slow_path() {
let resp = StubResponse::new_is(
is_response(200, &[], Some(json!("x"))),
Some(json!({"wait": 5})),
None,
);
assert!(
prepared_of(&resp).is_none(),
"_behaviors must not be prepared"
);
}
#[test]
fn rift_templated_and_fault_force_slow_path() {
let templated = RiftResponseExtension {
dataset: None,
templated: true,
..Default::default()
};
let resp = StubResponse::new_is(
is_response(200, &[], Some(json!("x"))),
None,
Some(Box::new(templated)),
);
assert!(
prepared_of(&resp).is_none(),
"_rift.templated must not be prepared"
);
let faulted = RiftResponseExtension {
dataset: None,
fault: Some(crate::imposter::types::RiftFaultConfig::default()),
..Default::default()
};
let resp = StubResponse::new_is(
is_response(200, &[], Some(json!("x"))),
None,
Some(Box::new(faulted)),
);
assert!(
prepared_of(&resp).is_none(),
"_rift.fault must not be prepared"
);
let scripted = RiftResponseExtension {
dataset: None,
script: Some(crate::imposter::types::RiftScriptConfig::default()),
..Default::default()
};
let resp = StubResponse::new_is(
is_response(200, &[], Some(json!("x"))),
None,
Some(Box::new(scripted)),
);
assert!(
prepared_of(&resp).is_none(),
"_rift.script must not be prepared"
);
}
#[test]
fn request_templates_in_body_or_header_force_slow_path() {
let body_tpl = StubResponse::new_is(
is_response(200, &[], Some(json!("hello ${request.path}"))),
None,
None,
);
assert!(
prepared_of(&body_tpl).is_none(),
"${{request.*}} body must not be prepared"
);
let header_tpl = StubResponse::new_is(
is_response(200, &[("X-Echo", "${request.query.q}")], Some(json!("x"))),
None,
None,
);
assert!(
prepared_of(&header_tpl).is_none(),
"${{request.*}} header must not be prepared"
);
}
#[test]
fn date_templates_force_slow_path() {
let resp = StubResponse::new_is(
is_response(200, &[], Some(json!("expires {{DAYS+7}} at {{NOW}}"))),
None,
None,
);
assert!(
prepared_of(&resp).is_none(),
"date-token body must not be prepared"
);
}
#[test]
fn binary_mode_forces_slow_path() {
let mut is = is_response(200, &[], Some(json!("aGVsbG8=")));
is.mode = ResponseMode::Binary;
let resp = StubResponse::new_is(is, None, None);
assert!(
prepared_of(&resp).is_none(),
"binary mode must not be prepared"
);
}
#[test]
fn reconstruction_recomputes_prepared() {
let stat = StubResponse::new_is(is_response(200, &[], Some(json!("x"))), None, None);
assert!(prepared_of(&stat).is_some());
let dynamic = StubResponse::new_is(
is_response(200, &[], Some(json!("${request.path}"))),
None,
None,
);
assert!(prepared_of(&dynamic).is_none());
}
}
#[cfg(test)]
mod rift_only_tests {
use super::*;
use serde_json::json;
fn rift_only(rift: serde_json::Value) -> StubResponse {
StubResponse::RiftScript {
rift: Box::new(serde_json::from_value(rift).expect("_rift parses")),
ignored_behaviors: Some(json!({ "wait": 10 })),
}
}
#[test]
fn script_less_rift_executes_as_empty_is() {
let response = rift_only(json!({ "fault": { "tcp": "malformed" } }));
let (status, headers, body, behaviors, rift, mode, is_fault) =
execute_stub_response_with_rift(&response).expect("served as `is: {}`");
assert_eq!(status, 200);
assert!(headers.is_empty(), "{headers:?}");
assert_eq!(body, "");
assert!(
behaviors.is_none(),
"behaviors other than repeat stay ignored"
);
assert!(
rift.is_some_and(|r| r.fault.is_some()),
"its `_rift` rides along"
);
assert_eq!(mode, ResponseMode::Text);
assert!(!is_fault);
let served = served_is(&response).expect("served as `is: {}`");
assert!(
served.omitted.status_code && served.omitted.body,
"every field omitted"
);
}
#[test]
fn scripted_rift_still_executes_as_none() {
let response = rift_only(json!({ "script": { "code": "response.body = 'x';" } }));
assert!(execute_stub_response_with_rift(&response).is_none());
assert!(served_is(&response).is_none());
}
}