use super::*;
use crate::imposter::behavior_pipeline::{BehaviorOutcome, BehaviorRun, ServedParts};
use crate::imposter::probe::{Point, fire};
use crate::imposter::types::{UpstreamTarget, upstream_url};
use crate::recording::{
ClaimToken, ProxyStoreError, RecordedClaim, StubPlacement, StubPublication,
};
use rift_types::PREDICATE_GENERATOR_KEYS as GENERATOR_KEYS;
use std::hash::BuildHasher;
type ForwardedResponse = (
u16,
Vec<(String, String)>,
crate::imposter::body_limits::CollectedBody,
u64,
);
#[derive(Debug, Clone, Copy)]
pub(crate) struct ProxyBody<'a> {
pub raw: &'a bytes::Bytes,
pub text: Option<&'a str>,
}
#[derive(Debug)]
pub(crate) struct ProxiedResponse {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
pub latency_ms: Option<u64>,
}
#[derive(Debug)]
#[must_use]
pub(crate) enum ProxyOutcome {
Served(ProxiedResponse),
StrictFailure(hyper::Response<http_body_util::Full<bytes::Bytes>>),
}
enum Transformed {
Applied(u16, Vec<(String, String)>, bytes::Bytes),
Degraded(u16, Vec<(String, String)>, bytes::Bytes),
StrictFailure(hyper::Response<http_body_util::Full<bytes::Bytes>>),
}
struct HeldClaim<'a> {
store: &'a dyn ProxyRecordingStore,
port: u16,
signature: &'a RequestSignature,
token: Option<ClaimToken>,
}
impl<'a> HeldClaim<'a> {
fn new(
store: &'a dyn ProxyRecordingStore,
port: u16,
signature: &'a RequestSignature,
token: ClaimToken,
) -> Self {
Self {
store,
port,
signature,
token: Some(token),
}
}
fn settle(
mut self,
resp: RecordedResponse,
publication: Option<&StubPublication<'_>>,
) -> Option<ClaimToken> {
let token = self.token.take()?;
let (path, settled) = match publication {
Some(publication) => (
"complete",
self.store
.complete(self.port, self.signature.clone(), token, resp, publication),
),
None => (
"record",
self.store
.record(self.port, self.signature.clone(), token, resp),
),
};
match settled {
Ok(()) => Some(token),
Err(ProxyStoreError::StaleClaim) => {
debug!("Stale proxy claim at {path}(); this request recorded nothing");
None
}
Err(e) => {
warn!(
"Failed to settle proxy recording via {path}(), releasing claim so it stays \
retryable: {e}"
);
self.store.release_claim(self.port, self.signature, token);
None
}
}
}
}
impl Drop for HeldClaim<'_> {
fn drop(&mut self) {
if let Some(token) = self.token.take() {
self.store.release_claim(self.port, self.signature, token);
}
}
}
async fn transform_upstream<SH: BuildHasher>(
run: &BehaviorRun<'_, SH>,
status: u16,
headers: Vec<(String, String)>,
body: bytes::Bytes,
) -> Transformed {
let (text, binary) = match String::from_utf8(body.to_vec()) {
Ok(text) => (text, false),
Err(_) => {
use base64::Engine;
(
base64::engine::general_purpose::STANDARD.encode(&body),
true,
)
}
};
let mut grouped: crate::imposter::Headers = crate::imposter::Headers::new();
for (k, v) in headers {
grouped.entry(k).or_default().push(v);
}
let (parts, mut degraded) = match run
.apply(ServedParts {
status,
status_text: None,
headers: crate::behaviors::authored_headers(grouped),
body: crate::behaviors::Spliced::authored(text),
typed_body: None,
})
.await
{
BehaviorOutcome::Applied { parts, degraded } => (parts, degraded),
BehaviorOutcome::StrictFailure(response) => return Transformed::StrictFailure(response),
};
let status = match crate::imposter::status::resolve(
parts.status,
parts
.status_text
.as_ref()
.map(crate::behaviors::Spliced::as_str),
run.default_response,
) {
Ok(status) => status.as_u16(),
Err(value) => {
return Transformed::StrictFailure(crate::imposter::status::invalid_status_response(
&value,
));
}
};
let mut headers: Vec<(String, String)> = parts
.headers
.into_iter()
.filter(|(k, _)| !k.eq_ignore_ascii_case("content-length"))
.flat_map(|(k, values)| {
let k = k.into_text();
values.into_iter().map(move |v| (k.clone(), v.into_text()))
})
.collect();
let body = if binary {
match crate::imposter::handler::decode_binary_body(parts.body.into_text(), run.strict) {
Ok(crate::imposter::handler::BinaryBody::Decoded(bytes)) => bytes,
Ok(crate::imposter::handler::BinaryBody::RawFallback(bytes)) => {
headers.push(("x-rift-binary-error".to_string(), "true".to_string()));
degraded = true;
bytes
}
Err(strict_failure) => return Transformed::StrictFailure(*strict_failure),
}
} else {
bytes::Bytes::from(parts.body.into_text())
};
if degraded {
Transformed::Degraded(status, headers, body)
} else {
Transformed::Applied(status, headers, body)
}
}
pub(crate) fn unread_generator_keys(generator: &serde_json::Value) -> Vec<String> {
let mut keys: Vec<String> = generator
.as_object()
.map(|generator| {
generator
.keys()
.filter(|key| !GENERATOR_KEYS.contains(&key.as_str()))
.cloned()
.collect()
})
.unwrap_or_default();
keys.sort_unstable();
keys
}
fn generator_selector(
generator: &serde_json::Map<String, serde_json::Value>,
) -> Option<crate::imposter::PredicateSelector> {
use crate::behaviors::{validate_jsonpath_selector, validate_xpath_selector};
use crate::imposter::PredicateSelector;
let (key, value) = generator
.get_key_value("jsonpath")
.or_else(|| generator.get_key_value("xpath"))?;
let selector: PredicateSelector =
match serde_json::from_value(serde_json::json!({ key: value })) {
Ok(selector) => selector,
Err(e) => {
tracing::warn!(
"predicateGenerator `{key}` is malformed ({e}); the body is captured whole"
);
return None;
}
};
let compiles = match &selector {
PredicateSelector::JsonPath { selector } => validate_jsonpath_selector(selector),
PredicateSelector::XPath { selector, .. } => validate_xpath_selector(selector),
};
match compiles {
Ok(()) => Some(selector),
Err(e) => {
tracing::warn!(
"predicateGenerator `{key}` selector does not compile ({e}); the body is captured whole"
);
None
}
}
}
fn selected_body(
selector: &crate::imposter::PredicateSelector,
body: &str,
) -> Result<serde_json::Value, crate::behaviors::XPathSelectorError> {
use crate::behaviors::{Selection, jsonpath_selection, xpath_selection_in};
use crate::imposter::PredicateSelector;
let selection = match selector {
PredicateSelector::JsonPath { selector } => serde_json::from_str(body)
.ok()
.and_then(|json| jsonpath_selection(&json, selector)),
PredicateSelector::XPath {
selector,
namespaces,
} => xpath_selection_in(body, selector, namespaces.as_ref())?,
};
Ok(match selection.unwrap_or(Selection::One(String::new())) {
Selection::One(value) => serde_json::Value::String(value),
Selection::Many(values) => {
serde_json::Value::Array(values.into_iter().map(serde_json::Value::String).collect())
}
})
}
fn remove_ignored(
captured: &mut serde_json::Map<String, serde_json::Value>,
filter: &serde_json::Value,
) {
match filter {
serde_json::Value::String(key) => {
captured.remove(key);
}
serde_json::Value::Array(keys) => {
for key in keys.iter().filter_map(serde_json::Value::as_str) {
captured.remove(key);
}
}
_ => {}
}
}
#[cfg(test)]
const TEST_PEER: std::net::SocketAddr =
std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 50000);
struct GeneratorRequest<'a, SH> {
method: &'a str,
path: &'a str,
headers: &'a indexmap::IndexMap<String, Vec<String>, SH>,
body: Option<&'a str>,
query: Option<&'a str>,
client_addr: std::net::SocketAddr,
}
impl<SH: BuildHasher> GeneratorRequest<'_, SH> {
fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case(name))
.and_then(|(_, values)| values.first())
.map(String::as_str)
}
fn query(&self) -> serde_json::Map<String, serde_json::Value> {
self.query
.map(crate::imposter::parse_query_string)
.unwrap_or_default()
.iter()
.map(|(k, v)| (k.clone(), crate::util::values_as_json(v)))
.collect()
}
fn form(&self) -> Option<serde_json::Map<String, serde_json::Value>> {
crate::imposter::Imposter::request_form(self.headers, self.body).map(|form| {
form.iter()
.map(|(k, v)| (k.clone(), crate::util::values_as_json(v)))
.collect()
})
}
fn headers(&self) -> serde_json::Map<String, serde_json::Value> {
self.headers
.iter()
.filter_map(|(k, values)| {
values
.first()
.map(|first| (k.clone(), serde_json::Value::String(first.clone())))
})
.collect()
}
}
enum Captured {
Scalar(serde_json::Value),
Whole {
fields: serde_json::Map<String, serde_json::Value>,
filtered: bool,
},
Listed(serde_json::Map<String, serde_json::Value>),
}
fn capture<SH: BuildHasher>(
field: &str,
matcher: &serde_json::Value,
request: &GeneratorRequest<'_, SH>,
selector: Option<&crate::imposter::PredicateSelector>,
ignore: Option<&serde_json::Value>,
) -> Result<Option<Captured>, crate::behaviors::XPathSelectorError> {
let whole = matcher.as_bool() == Some(true);
Ok(match field {
"method" | "path" | "body" if whole => {
let value = match field {
"method" => serde_json::Value::String(request.method.to_string()),
"path" => serde_json::Value::String(request.path.to_string()),
_ => {
let body = request.body.unwrap_or("");
match selector {
Some(selector) => selected_body(selector, body)?,
None => serde_json::Value::String(body.to_string()),
}
}
};
Some(Captured::Scalar(value))
}
"requestFrom" if whole => Some(Captured::Scalar(serde_json::Value::String(
request.client_addr.to_string(),
))),
"ip" if whole => Some(Captured::Scalar(serde_json::Value::String(
request.client_addr.ip().to_string(),
))),
"query" | "headers" | "form" => {
let form = if field == "form" {
let Some(form) = request.form() else {
return Ok(None);
};
Some(form)
} else {
None
};
let mut fields = if whole {
match field {
"query" => request.query(),
"form" => form.unwrap_or_default(),
_ => request.headers(),
}
} else {
let Some(listed) = matcher.as_object() else {
return Ok(None);
};
let keyed = match field {
"query" => Some(request.query()),
"form" => form,
_ => None,
};
listed
.keys()
.filter_map(|key| {
let value = match &keyed {
Some(map) => map.get(key).cloned(),
None => request
.header(key)
.map(|v| serde_json::Value::String(v.to_string())),
};
value.map(|value| (key.clone(), value))
})
.collect()
};
if let Some(filter) = ignore {
remove_ignored(&mut fields, filter);
}
Some(if whole {
Captured::Whole {
fields,
filtered: ignore.is_some(),
}
} else {
Captured::Listed(fields)
})
}
_ => None,
})
}
fn predicates_for_matcher<SH: BuildHasher>(
generator: &serde_json::Map<String, serde_json::Value>,
matches: &serde_json::Map<String, serde_json::Value>,
request: &GeneratorRequest<'_, SH>,
) -> Result<Vec<serde_json::Value>, crate::behaviors::XPathSelectorError> {
let operator = generator.get("predicateOperator").and_then(|p| p.as_str());
let selector = generator_selector(generator);
let capture_selector = selector.as_ref().filter(|_| operator != Some("exists"));
let mut parameters = serde_json::Map::new();
if let Some(case_sensitive) = generator.get("caseSensitive").filter(|c| c.is_boolean()) {
parameters.insert("caseSensitive".to_string(), case_sensitive.clone());
}
if let Some(except) = generator.get("except").filter(|e| e.is_string()) {
parameters.insert("except".to_string(), except.clone());
}
let mut predicates = Vec::new();
for field in rift_types::GENERATOR_MATCH_FIELDS {
let Some(matcher) = matches.get(field) else {
continue;
};
let ignore = generator.get("ignore").and_then(|ignore| ignore.get(field));
let Some(captured) = capture(field, matcher, request, capture_selector, ignore)? else {
continue;
};
let (operator, value) = match (operator, captured) {
(Some("exists"), Captured::Scalar(_)) => ("exists", serde_json::Value::Bool(true)),
(Some("exists"), Captured::Whole { fields, .. } | Captured::Listed(fields)) => (
"exists",
serde_json::Value::Object(
fields
.into_iter()
.map(|(key, _)| (key, serde_json::Value::Bool(true)))
.collect(),
),
),
(Some(operator), Captured::Scalar(value)) => (operator, value),
(Some(operator), Captured::Whole { fields, .. } | Captured::Listed(fields)) => {
(operator, serde_json::Value::Object(fields))
}
(None, Captured::Scalar(value)) => ("deepEquals", value),
(
None,
Captured::Whole {
fields,
filtered: false,
},
) => ("deepEquals", serde_json::Value::Object(fields)),
(None, Captured::Whole { fields, .. } | Captured::Listed(fields)) => {
("equals", serde_json::Value::Object(fields))
}
};
let mut predicate = serde_json::Map::new();
predicate.insert(
operator.to_string(),
serde_json::Value::Object(serde_json::Map::from_iter([(field.to_string(), value)])),
);
if field == "body"
&& let Some(serde_json::Value::Object(selector)) =
selector.as_ref().and_then(|s| serde_json::to_value(s).ok())
{
predicate.extend(selector);
}
predicate.extend(parameters.clone());
predicates.push(serde_json::Value::Object(predicate));
}
Ok(predicates)
}
#[derive(Debug, Default)]
pub(crate) struct GeneratedPredicates {
raw: Vec<serde_json::Value>,
typed: Vec<rift_types::Predicate>,
}
#[derive(Debug)]
struct GeneratorFailure {
inject: Option<String>,
error: crate::scripting::PredicateGeneratorError,
}
impl From<crate::scripting::PredicateGeneratorError> for GeneratorFailure {
fn from(error: crate::scripting::PredicateGeneratorError) -> Self {
Self {
inject: None,
error,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GeneratorDryRun {
Refused {
source: String,
data: Option<String>,
},
Unavailable(String),
}
impl std::fmt::Display for GeneratorDryRun {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Refused {
data: Some(data), ..
} => write!(f, "invalid predicateGenerator injection: {data}"),
Self::Refused { data: None, .. } => {
write!(f, "invalid predicateGenerator injection")
}
Self::Unavailable(detail) => {
write!(
f,
"could not dry-run a predicateGenerator injection: {detail}"
)
}
}
}
}
impl std::error::Error for GeneratorDryRun {}
const DRY_RUN_PEER: std::net::SocketAddr =
std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0);
fn has_inject_generator(generators: &[serde_json::Value]) -> bool {
generators
.iter()
.any(|g| g.as_object().is_some_and(|o| o.contains_key("inject")))
}
pub async fn dry_run_predicate_generators(
stubs: &[Stub],
timeout: Duration,
script_files: Arc<crate::imposter::ScriptFileAccess>,
) -> Result<(), GeneratorDryRun> {
let lists: Vec<Vec<serde_json::Value>> = stubs
.iter()
.flat_map(|stub| &stub.responses)
.filter_map(|response| match response {
StubResponse::Proxy { proxy, .. }
if has_inject_generator(&proxy.predicate_generators) =>
{
Some(proxy.predicate_generators.clone())
}
_ => None,
})
.collect();
for generators in lists {
let first_inject = generators
.iter()
.find_map(|g| g.get("inject").and_then(serde_json::Value::as_str))
.map(str::to_owned);
let files = Arc::clone(&script_files);
let handle = tokio::task::spawn_blocking(move || {
Imposter::run_generators(
&generators,
"GET",
"/",
&crate::imposter::Headers::new(),
Some(""),
None,
DRY_RUN_PEER,
&files,
true,
)
});
let failure = match tokio::time::timeout(timeout, handle).await {
Ok(Ok(Ok(_))) => continue,
Ok(Ok(Err(failure))) => failure,
Ok(Err(join_err)) => {
return Err(GeneratorDryRun::Unavailable(format!(
"generator task panicked: {join_err}"
)));
}
Err(_elapsed) => {
return Err(GeneratorDryRun::Refused {
source: injection_source(first_inject.as_deref()),
data: Some(format!("timed out after {}ms", timeout.as_millis())),
});
}
};
use crate::scripting::PredicateGeneratorError as E;
let data = match failure.error {
E::Threw { message, .. } => message,
E::Script(message) | E::Output(message) => Some(message),
E::Pool(message) => return Err(GeneratorDryRun::Unavailable(message)),
E::Invalid(_) | E::Selector(_) => continue,
};
return Err(GeneratorDryRun::Refused {
source: injection_source(failure.inject.as_deref()),
data,
});
}
Ok(())
}
#[derive(Debug)]
enum GenerationFailed {
Runtime(RuntimeFailure),
Invalid { token: &'static str, detail: String },
}
#[derive(Debug)]
enum RuntimeFailure {
Selector(crate::behaviors::XPathSelectorError),
Injection {
token: &'static str,
source: String,
data: Option<String>,
detail: String,
},
Unavailable { token: &'static str, detail: String },
}
impl RuntimeFailure {
fn response(self) -> hyper::Response<http_body_util::Full<bytes::Bytes>> {
match self {
Self::Selector(e) => crate::imposter::handler::xpath_selector_error_response(&e),
Self::Injection {
token,
source,
data,
detail,
} => {
warn!("predicateGenerators injection failed ({detail}); nothing is recorded");
crate::imposter::handler::generator_injection_error_response(
&source,
data.as_deref(),
token,
)
}
Self::Unavailable { token, detail } => {
error!(
"could not run a predicateGenerators injection ({detail}); nothing is recorded"
);
crate::imposter::handler::generator_unavailable_response(token)
}
}
}
}
impl From<GeneratorFailure> for GenerationFailed {
fn from(failure: GeneratorFailure) -> Self {
use crate::scripting::PredicateGeneratorError as E;
let token = failure.error.kind();
let detail = failure.error.to_string();
let source = injection_source(failure.inject.as_deref());
let injection = |data: Option<String>| {
Self::Runtime(RuntimeFailure::Injection {
token,
source: source.clone(),
data,
detail: detail.clone(),
})
};
match failure.error {
E::Selector(e) => Self::Runtime(RuntimeFailure::Selector(e)),
E::Threw { message, .. } => injection(message),
E::Script(message) | E::Output(message) => injection(Some(message)),
E::Pool(_) => Self::Runtime(RuntimeFailure::Unavailable { token, detail }),
E::Invalid(_) => Self::Invalid { token, detail },
}
}
}
fn injection_source(inject: Option<&str>) -> String {
inject.map_or_else(String::new, |f| format!("({f})(config);"))
}
impl Imposter {
#[cfg(test)]
pub(crate) fn generate_predicates_from_request<SH: BuildHasher>(
&self,
generators: &[serde_json::Value],
method: &str,
path: &str,
headers: &indexmap::IndexMap<String, Vec<String>, SH>,
body: Option<&str>,
query: Option<&str>,
) -> Result<Vec<serde_json::Value>, crate::scripting::PredicateGeneratorError> {
Self::run_generators(
generators,
method,
path,
headers,
body,
query,
TEST_PEER,
&self.script_file_access(),
false,
)
.map(|generated| generated.raw)
.map_err(|failure| failure.error)
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
fn generate_predicates_impl<SH: BuildHasher>(
generators: &[serde_json::Value],
method: &str,
path: &str,
headers: &indexmap::IndexMap<String, Vec<String>, SH>,
body: Option<&str>,
query: Option<&str>,
client_addr: std::net::SocketAddr,
script_files: &std::sync::Arc<crate::imposter::ScriptFileAccess>,
) -> Result<GeneratedPredicates, crate::scripting::PredicateGeneratorError> {
Self::run_generators(
generators,
method,
path,
headers,
body,
query,
client_addr,
script_files,
false,
)
.map_err(|failure| failure.error)
}
#[allow(clippy::too_many_arguments)]
fn run_generators<SH: BuildHasher>(
generators: &[serde_json::Value],
method: &str,
path: &str,
headers: &indexmap::IndexMap<String, Vec<String>, SH>,
body: Option<&str>,
query: Option<&str>,
client_addr: std::net::SocketAddr,
script_files: &std::sync::Arc<crate::imposter::ScriptFileAccess>,
dry_run: bool,
) -> Result<GeneratedPredicates, GeneratorFailure> {
let mut predicates = Vec::new();
let invalid = crate::scripting::PredicateGeneratorError::Invalid;
for (i, r#gen) in generators.iter().enumerate() {
if let Some(refusal) = rift_types::generator_shape_error(i, r#gen)
.or_else(|| crate::imposter::types::generator_operator_error(i, r#gen))
{
return Err(invalid(refusal).into());
}
let Some(gen_obj) = r#gen.as_object() else {
return Err(invalid(format!("predicateGenerators[{i}] must be an object")).into());
};
if let Some(inject_fn) = gen_obj.get("inject").and_then(|v| v.as_str()) {
#[cfg(feature = "javascript")]
{
use crate::scripting::{MountebankRequest, execute_predicate_generator_inject};
let query_map = query
.map(crate::imposter::parse_query_string)
.unwrap_or_default();
let mb_request = MountebankRequest {
method: method.to_string(),
path: path.to_string(),
query: query_map,
headers: headers
.iter()
.filter(|(_, v)| !v.is_empty())
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
body: body.map(|b| b.to_string()),
body_undefined: false,
mode: None,
request_from: Some(if dry_run {
String::new()
} else {
client_addr.to_string()
}),
ip: (!dry_run).then(|| client_addr.ip().to_string()),
form: if dry_run {
Some(crate::util::OrderedMap::default())
} else {
crate::imposter::Imposter::request_form(headers, body)
},
is_dry_run: dry_run,
};
let inject_preds = execute_predicate_generator_inject(
inject_fn,
&mb_request,
&predicates,
script_files,
)
.map_err(|error| GeneratorFailure {
inject: Some(inject_fn.to_owned()),
error,
})?;
predicates.extend(inject_preds);
continue;
}
#[cfg(not(feature = "javascript"))]
{
let _ = (script_files, dry_run);
return Err(GeneratorFailure {
inject: Some(inject_fn.to_owned()),
error: crate::scripting::PredicateGeneratorError::Script(
"predicateGenerator inject requires the 'javascript' feature"
.to_string(),
),
});
}
}
let Some(matches) = gen_obj.get("matches").and_then(|m| m.as_object()) else {
return Err(invalid(format!(
"predicateGenerators[{i}] needs `matches` or `inject`"
))
.into());
};
let request = GeneratorRequest {
method,
path,
headers,
body,
query,
client_addr,
};
predicates.extend(
predicates_for_matcher(gen_obj, matches, &request)
.map_err(crate::scripting::PredicateGeneratorError::from)?,
);
}
let typed = predicates
.iter()
.map(|value| {
serde_json::from_value::<rift_types::Predicate>(value.clone())
.map_err(|e| invalid(format!("{value}: {e}")))
})
.collect::<Result<Vec<_>, _>>()?;
crate::imposter::types::validate_predicates(&typed).map_err(invalid)?;
Ok(GeneratedPredicates {
raw: predicates,
typed,
})
}
fn placement_for_mode(proxy_mode: &str) -> StubPlacement {
if ProxyMode::parse(proxy_mode).unwrap_or_default() == ProxyMode::ProxyAlways {
StubPlacement::AfterProxyMerging
} else {
StubPlacement::BeforeProxy
}
}
fn shadowed_recordings(
&self,
answering: Option<u64>,
sig: &RequestSignature,
) -> Vec<ClaimToken> {
if self.proxy_store.publishes_stubs() {
return Vec::new();
}
let Some(slot) = answering else {
return Vec::new();
};
let snapshot = self.snapshot();
let stubs = snapshot.stubs();
let Some(at) = stubs.iter().position(|s| s.slot == slot) else {
return Vec::new();
};
let carriers = || {
stubs.iter().enumerate().filter_map(|(i, s)| {
s.recorded_claim
.as_deref()
.filter(|claim| claim.signature == *sig)
.map(|claim| (i, claim.token))
})
};
if carriers().next().is_none_or(|(first, _)| first <= at) {
return Vec::new();
}
carriers().map(|(_, token)| token).collect()
}
pub fn insert_or_append_proxy_stub(
&self,
stub: Stub,
proxy_to: &str,
proxy_mode: &str,
answering: Option<u64>,
claim: Option<RecordedClaim>,
) {
let placement = Self::placement_for_mode(proxy_mode);
self.mutate_stubs(|stubs| {
let anchor = answering
.and_then(|slot| stubs.iter().position(|s| s.slot == slot))
.or_else(|| stubs.iter().position(|s| proxies_to(&s.stub, proxy_to)));
if placement == StubPlacement::AfterProxyMerging {
let from = anchor.map_or(0, |a| a + 1);
let matching = stubs
.iter()
.skip(from)
.position(|existing| existing.stub.predicates == stub.predicates)
.map(|p| p + from);
if let Some(idx) = matching {
let merged = self.appended(&stubs[idx], stub.responses);
let total = merged.stub.responses.len();
let at = stubs[idx].loaded_at().max(chrono::Utc::now());
stubs[idx] = Arc::new(merged.with_loaded_at(at));
debug!(
"Appended response to existing stub at index {idx} (proxyAlways mode, {total} total responses)"
);
return;
}
stubs.push(Arc::new(StubState::new(stub)));
debug!(
"Appended generated stub at index {} (proxyAlways mode)",
stubs.len() - 1
);
} else {
let index = anchor.unwrap_or(stubs.len());
let mut state = StubState::new(stub);
state.recorded_claim = claim.map(Arc::new);
stubs.insert(index, Arc::new(state));
debug!(
"Inserted generated stub at index {} before proxy (proxyOnce mode)",
index
);
}
});
}
async fn generate_stub_predicates<SH>(
&self,
proxy_config: &ProxyResponse,
method: &str,
uri: &hyper::Uri,
headers: &indexmap::IndexMap<String, Vec<String>, SH>,
body: Option<ProxyBody<'_>>,
client_addr: std::net::SocketAddr,
) -> Result<GeneratedPredicates, GenerationFailed>
where
SH: BuildHasher + Clone + Send + 'static,
{
if !has_inject_generator(&proxy_config.predicate_generators) {
return Self::run_generators(
&proxy_config.predicate_generators,
method,
uri.path(),
headers,
body.and_then(|b| b.text),
uri.query(),
client_addr,
&self.script_file_access(),
false,
)
.map_err(GenerationFailed::from);
}
let first_inject = proxy_config
.predicate_generators
.iter()
.find_map(|g| g.get("inject").and_then(serde_json::Value::as_str))
.map(str::to_owned);
let generators = proxy_config.predicate_generators.clone();
let method = method.to_string();
let path = uri.path().to_string();
let headers = headers.clone();
let body = body.and_then(|b| b.text.map(str::to_string));
let query = uri.query().map(str::to_string);
let script_files = self.script_file_access();
let timeout = std::time::Duration::from_millis(
crate::scripting::resolve_script_timeout_ms(&self.config),
);
let env = crate::scripting::env::ScriptEnv::capture();
let handle = tokio::task::spawn_blocking(move || {
env.enter(|| {
Self::run_generators(
&generators,
&method,
&path,
&headers,
body.as_deref(),
query.as_deref(),
client_addr,
&script_files,
false,
)
})
});
match tokio::time::timeout(timeout, handle).await {
Ok(Ok(Ok(preds))) => Ok(preds),
Ok(Ok(Err(failure))) => Err(GenerationFailed::from(failure)),
Ok(Err(join_err)) => Err(GenerationFailed::Runtime(RuntimeFailure::Unavailable {
token: "task-panic",
detail: format!("generator task panicked: {join_err}"),
})),
Err(_elapsed) => {
let data = format!("timed out after {}ms", timeout.as_millis());
Err(GenerationFailed::Runtime(RuntimeFailure::Injection {
token: "timeout",
source: injection_source(first_inject.as_deref()),
data: Some(data.clone()),
detail: data,
}))
}
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_proxy_request<SH>(
&self,
proxy_config: &ProxyResponse,
target: UpstreamTarget,
method: &str,
uri: &hyper::Uri,
headers: &indexmap::IndexMap<String, Vec<String>, SH>,
body: Option<ProxyBody<'_>>,
behaviors: Option<&BehaviorRun<'_, SH>>,
answering: Option<u64>,
client_addr: std::net::SocketAddr,
) -> anyhow::Result<ProxyOutcome>
where
SH: BuildHasher + Clone + Send + 'static,
{
let client = match proxy_config.client_identity_pem() {
Some((cert, key, passphrase)) => {
self.identity_clients
.client_for(cert, key, passphrase, self.upstream_client.is_some())
.await?
}
None => super::resolve_upstream_client(self.upstream_client.as_ref())?,
};
let client = &*client;
info!(
"Proxy config - addDecorateBehavior: {:?}, addWaitBehavior: {}, predicateGenerators: {:?}",
proxy_config.add_decorate_behavior,
proxy_config.add_wait_behavior,
proxy_config.predicate_generators
);
let original_path = uri.path();
let rewritten_path = if let Some(ref rewrite) = proxy_config.path_rewrite {
original_path.replacen(&rewrite.from, &rewrite.to, 1)
} else {
original_path.to_string()
};
let target_url = upstream_url(&proxy_config.to, target, &rewritten_path, uri.query())
.map_err(anyhow::Error::msg)?
.to_string();
if proxy_config.path_rewrite.is_some() {
debug!(
"Proxy request to: {} (path rewritten from '{}')",
target_url, original_path
);
} else {
debug!("Proxy request to: {}", target_url);
}
let mode = proxy_config.mode().unwrap_or_default();
let transparent = mode == ProxyMode::ProxyTransparent;
let mode_is_once = mode == ProxyMode::ProxyOnce;
let generates_stub = !transparent
&& (!proxy_config.predicate_generators.is_empty()
|| proxy_config.add_wait_behavior
|| proxy_config.add_decorate_behavior.is_some());
let generation = if !generates_stub {
None
} else if proxy_config.predicate_generators.is_empty() {
Some(Ok(GeneratedPredicates::default()))
} else {
Some(
self.generate_stub_predicates(
proxy_config,
method,
uri,
headers,
body,
client_addr,
)
.await,
)
};
let (generation, runtime_failure) = match generation {
Some(Err(GenerationFailed::Runtime(failure))) => (None, Some(failure)),
Some(Err(GenerationFailed::Invalid { token, detail })) => {
(Some(Err((token, detail))), None)
}
Some(Ok(predicates)) => (Some(Ok(predicates)), None),
None if transparent && !proxy_config.predicate_generators.is_empty() => {
match self
.generate_stub_predicates(proxy_config, method, uri, headers, body, client_addr)
.await
{
Err(GenerationFailed::Runtime(failure)) => (None, Some(failure)),
Ok(_) | Err(GenerationFailed::Invalid { .. }) => (None, None),
}
}
None => (None, None),
};
let mut signature = RequestSignature::new(method, uri.path(), uri.query(), &[]);
if proxy_config.predicate_generators.is_empty() {
signature = signature.with_body(body.map_or(&[][..], |b| b.raw.as_ref()));
} else if let Some(Ok(predicates)) = &generation {
signature = signature.with_predicates(&predicates.raw);
}
let port = self.journal_port();
let generation_failed = matches!(generation, Some(Err(_))) || runtime_failure.is_some();
let mut lost_race = false;
let claim = if transparent || generation_failed {
None
} else {
let claim_now = || {
let claimed = self.proxy_store.try_claim_as(port, &signature, mode);
if let Ok(outcome) = &claimed {
fire(
&self.probe,
Point::ProxyClaim {
port,
outcome: *outcome,
},
);
}
claimed
};
let claimed = claim_now();
let shadowed = if generates_stub
&& mode_is_once
&& matches!(claimed, Ok(ClaimOutcome::AlreadyRecorded))
{
self.shadowed_recordings(answering, &signature)
} else {
Vec::new()
};
let mut outcome = match claimed {
Ok(ClaimOutcome::AlreadyRecorded) if !shadowed.is_empty() => {
fire(&self.probe, Point::ProxyShadowed { port });
let forgotten = shadowed.iter().try_for_each(|token| {
self.proxy_store
.forget_recorded_by(port, &signature, *token)
});
match forgotten {
Ok(()) => {
fire(&self.probe, Point::ProxyShadowForgot { port });
claim_now()
}
Err(e) => {
error!(
port,
path = %signature.path,
"Failed to forget a shadowed proxy recording; replaying it: {e}"
);
Ok(ClaimOutcome::AlreadyRecorded)
}
}
}
outcome => outcome,
};
let mut claimed_again = false;
loop {
break match outcome {
Ok(ClaimOutcome::AlreadyRecorded) => {
fire(&self.probe, Point::ProxyLookingUp { port });
if let Some(recorded) = self.proxy_store.lookup(port, &signature) {
fire(&self.probe, Point::ProxyReplayed { port });
debug!("Returning recorded proxy response (proxyOnce mode)");
return Ok(ProxyOutcome::Served(ProxiedResponse {
status: recorded.status,
headers: recorded.headers,
body: recorded.body,
latency_ms: recorded.latency_ms,
}));
}
fire(&self.probe, Point::ProxyNothingToReplay { port });
if !claimed_again {
claimed_again = true;
outcome = claim_now();
continue;
}
warn!(
"Proxy store reported AlreadyRecorded twice but lookup found nothing; forwarding without a stub"
);
lost_race = true;
None
}
Ok(ClaimOutcome::InFlight) => {
lost_race = true;
None
}
Ok(ClaimOutcome::Claimed(token)) => Some(HeldClaim::new(
self.proxy_store.as_ref(),
port,
&signature,
token,
)),
Err(ProxyStoreError::Refused(cause)) => {
return Err(anyhow::Error::new(cause)
.context("proxyOnce claim refused; request not forwarded"));
}
Err(e) => {
warn!(
"Proxy recording store unavailable; forwarding with nothing recorded in the store: {e}"
);
None
}
};
}
};
fire(&self.probe, Point::ProxyForwarding { port });
let start = Instant::now();
let forwarded: anyhow::Result<ForwardedResponse> = async {
let forwarded_method = reqwest::Method::from_bytes(method.as_bytes())
.with_context(|| format!("invalid request method `{method}`"))?;
let mut request = client.request(forwarded_method, &target_url);
for (key, values) in headers {
let key_lower = key.to_lowercase();
if key_lower != "host" && key_lower != "content-length" {
for value in values {
request = request.header(key, value);
}
}
}
for (key, value) in proxy_config.inject_headers.iter() {
request = request.header(key, value);
}
if let Some(proxy_body) = body {
request = request.body(proxy_body.raw.clone());
}
let response = request
.send()
.await
.with_context(|| format!("Failed to send proxy request to {target_url}"))?;
let latency_ms = start.elapsed().as_millis() as u64;
let status = response.status().as_u16();
crate::extensions::metrics::record_upstream_duration(method, status, latency_ms as f64);
let response_headers =
crate::imposter::headers::collect_response_headers(response.headers());
let mut response = response;
let mut collector = self
.body_guard
.start_without_waiting(response.content_length())
.await
.map_err(|e| anyhow::anyhow!("Proxy response body from {target_url}: {e}"))?;
while let Some(chunk) = response
.chunk()
.await
.with_context(|| format!("Failed to read response body from {target_url}"))?
{
collector
.push(&chunk)
.map_err(|e| anyhow::anyhow!("Proxy response body from {target_url}: {e}"))?;
}
let body_bytes = collector.finish();
Ok((status, response_headers, body_bytes, latency_ms))
}
.await;
let (status, response_headers, upstream_body, latency_ms) = match forwarded {
Ok(parts) => parts,
Err(e) => return Err(e),
};
let body_bytes = upstream_body.bytes().clone();
let recorded_latency = proxy_config.add_wait_behavior.then_some(latency_ms);
let (status, mut response_headers, body_bytes) = match behaviors {
None => (status, response_headers, body_bytes),
Some(run) => {
match transform_upstream(run, status, response_headers, body_bytes).await {
Transformed::Applied(status, headers, body) => (status, headers, body),
Transformed::Degraded(status, headers, body) if runtime_failure.is_none() => {
return Ok(ProxyOutcome::Served(ProxiedResponse {
status,
headers,
body: body.to_vec(),
latency_ms: recorded_latency,
}));
}
Transformed::Degraded(status, headers, body) => (status, headers, body),
Transformed::StrictFailure(response) => {
return Ok(ProxyOutcome::StrictFailure(response));
}
}
}
};
if let Some(failure) = runtime_failure {
return Ok(ProxyOutcome::StrictFailure(failure.response()));
}
let mut recording = claim.map(|claim| {
(
claim,
RecordedResponse {
status,
headers: response_headers.clone(),
body: body_bytes.to_vec(),
latency_ms: recorded_latency,
timestamp_secs: crate::util::unix_timestamp(),
},
)
});
if let Some(generation) = generation {
match generation {
Ok(predicates) => {
let mut new_stub = create_stub_from_proxy_response(
predicates.typed,
status,
&response_headers,
&body_bytes,
recorded_latency,
proxy_config.add_decorate_behavior.clone(),
Some(proxy_config.to.clone()),
latency_ms,
);
new_stub.recorded_at = Some(crate::util::unix_timestamp());
let mode = proxy_config.mode.as_str();
let held_claim = recording.is_some();
let settled = if let Some((claim, resp)) = recording.take() {
let publication = StubPublication {
stub: &new_stub,
placement: Self::placement_for_mode(mode),
proxy_to: &proxy_config.to,
anchor_index: answering.and_then(|slot| {
self.snapshot().stubs().iter().position(|s| s.slot == slot)
}),
};
let settled = claim.settle(resp, Some(&publication));
fire(&self.probe, Point::ProxySettled { port });
settled
} else {
None
};
if self.proxy_store.publishes_stubs() {
debug!(
"Skipping local stub insertion for path {} (proxy store publishes \
stubs; handed over: {})",
uri.path(),
settled.is_some()
);
} else if lost_race {
debug!(
"Skipping local stub insertion for path {} (this request won no claim)",
uri.path()
);
} else if mode_is_once && held_claim && settled.is_none() {
debug!(
"Skipping local stub insertion for path {} (nothing was recorded)",
uri.path()
);
} else {
let claim = settled.filter(|_| mode_is_once).map(|token| RecordedClaim {
signature: signature.clone(),
token,
});
let claimed = claim.is_some();
self.insert_or_append_proxy_stub(
new_stub,
&proxy_config.to,
mode,
answering,
claim,
);
fire(&self.probe, Point::ProxyInserted { port, claimed });
}
debug!(
"Generated stub from proxy response for path {} (mode: {})",
uri.path(),
mode
);
}
Err((token, detail)) => {
warn!(
"predicate generation failed for path {} ({detail}); skipping auto-stub to \
avoid recording a match-all stub",
uri.path()
);
response_headers
.push(("x-rift-generator-error".to_string(), token.to_string()));
}
}
}
if let Some((claim, resp)) = recording {
claim.settle(resp, None);
fire(&self.probe, Point::ProxySettled { port });
}
Ok(ProxyOutcome::Served(ProxiedResponse {
status,
headers: response_headers,
body: body_bytes.to_vec(),
latency_ms: recorded_latency,
}))
}
}
fn proxies_to(stub: &Stub, to: &str) -> bool {
stub.responses
.iter()
.any(|r| matches!(r, StubResponse::Proxy { proxy, .. } if proxy.to == to))
}
#[cfg(test)]
mod proxy_dedup_tests {
use super::*;
use serde_json::json;
fn imposter_with_proxy(to: &str) -> Imposter {
let cfg = serde_json::from_value(json!({
"port": 0,
"protocol": "http",
"stubs": [{ "responses": [{ "proxy": { "to": to, "mode": "proxyAlways" } }] }],
}))
.expect("valid imposter config");
Imposter::new(cfg).expect("test imposter")
}
fn multi_key_stub(body: &str) -> Stub {
serde_json::from_value(json!({
"predicates": [{ "equals": { "method": "GET", "path": "/x", "query": { "a": "1" } } }],
"responses": [{ "is": { "statusCode": 200, "body": body } }],
}))
.expect("valid stub")
}
#[test]
fn proxy_always_merges_responses_for_equal_multi_key_predicates() {
let imposter = imposter_with_proxy("http://upstream");
imposter.insert_or_append_proxy_stub(
multi_key_stub("first"),
"http://upstream",
"proxyAlways",
None,
None,
);
imposter.insert_or_append_proxy_stub(
multi_key_stub("second"),
"http://upstream",
"proxyAlways",
None,
None,
);
let stubs = imposter.get_stubs();
assert_eq!(
stubs.len(),
2,
"equal predicate sets must merge into one recorded stub alongside the proxy stub, \
not append a duplicate"
);
assert_eq!(
stubs[1].responses.len(),
2,
"both recorded responses must land on the single matching stub"
);
}
}
#[cfg(test)]
mod held_claim_tests {
use super::*;
use crate::recording::{LocalProxyStore, ProxyMode, ProxyRecordingStore};
fn signature() -> RequestSignature {
RequestSignature::new("GET", "/p", None, &[])
}
fn recorded() -> RecordedResponse {
RecordedResponse {
status: 200,
headers: vec![],
body: b"up".to_vec(),
latency_ms: None,
timestamp_secs: 0,
}
}
fn claim(store: &LocalProxyStore, sig: &RequestSignature) -> ClaimToken {
match store.try_claim(1, sig).expect("store answers") {
ClaimOutcome::Claimed(token) => token,
other => panic!("expected a claim, got {other:?}"),
}
}
#[test]
fn dropping_a_held_claim_releases_it() {
let store = LocalProxyStore::new(ProxyMode::ProxyOnce);
let sig = signature();
let held = HeldClaim::new(&store, 1, &sig, claim(&store, &sig));
assert_eq!(
store.try_claim(1, &sig).expect("answers"),
ClaimOutcome::InFlight
);
drop(held);
assert!(
matches!(
store.try_claim(1, &sig).expect("answers"),
ClaimOutcome::Claimed(_)
),
"a dropped claim must be free to take again"
);
}
#[test]
fn settling_a_held_claim_records_it_and_releases_nothing() {
let store = LocalProxyStore::new(ProxyMode::ProxyOnce);
let sig = signature();
HeldClaim::new(&store, 1, &sig, claim(&store, &sig)).settle(recorded(), None);
assert_eq!(
store.try_claim(1, &sig).expect("answers"),
ClaimOutcome::AlreadyRecorded
);
assert_eq!(store.lookup(1, &sig).map(|r| r.body), Some(b"up".to_vec()));
}
#[test]
fn a_stale_guard_does_not_release_a_newer_claim() {
let store = LocalProxyStore::new(ProxyMode::ProxyOnce);
let sig = signature();
let stale = claim(&store, &sig);
store.release_claim(1, &sig, stale);
let _current = claim(&store, &sig);
drop(HeldClaim::new(&store, 1, &sig, stale));
assert_eq!(
store.try_claim(1, &sig).expect("answers"),
ClaimOutcome::InFlight
);
}
}
#[cfg(test)]
mod predicate_generator_selector_tests {
use super::*;
use serde_json::json;
fn generate(
generator: serde_json::Value,
body: Option<&str>,
query: Option<&str>,
headers: &[(&str, &str)],
) -> Vec<serde_json::Value> {
let headers: crate::imposter::Headers = headers
.iter()
.map(|(k, v)| ((*k).to_string(), vec![(*v).to_string()]))
.collect();
Imposter::generate_predicates_impl(
&[generator],
"POST",
"/orders",
&headers,
body,
query,
TEST_PEER,
&std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
)
.expect("predicate generation succeeds")
.raw
}
#[test]
fn jsonpath_captures_the_selected_value_and_scopes_the_predicate() {
let predicates = generate(
json!({ "matches": { "body": true }, "jsonpath": { "selector": "$.id" } }),
Some(r#"{"id": 42, "ts": "2026-10-08T10:00:00Z"}"#),
None,
&[],
);
assert_eq!(
predicates,
vec![json!({
"deepEquals": { "body": "42" },
"jsonpath": { "selector": "$.id" }
})]
);
}
#[test]
fn jsonpath_with_several_matches_captures_an_array() {
let predicates = generate(
json!({ "matches": { "body": true }, "jsonpath": { "selector": "$.items[*].sku" } }),
Some(r#"{"items": [{"sku": "a"}, {"sku": "b"}]}"#),
None,
&[],
);
assert_eq!(predicates[0]["deepEquals"], json!({ "body": ["a", "b"] }));
}
#[test]
fn jsonpath_selecting_nothing_captures_the_empty_string() {
let predicates = generate(
json!({ "matches": { "body": true }, "jsonpath": { "selector": "$.missing" } }),
Some(r#"{"id": 1}"#),
None,
&[],
);
assert_eq!(predicates[0]["deepEquals"], json!({ "body": "" }));
assert_eq!(
predicates[0]["jsonpath"],
json!({ "selector": "$.missing" })
);
}
#[test]
fn xpath_with_ns_captures_the_selected_value() {
let predicates = generate(
json!({
"matches": { "body": true },
"xpath": { "selector": "//a:id", "ns": { "a": "urn:a" } },
"caseSensitive": false
}),
Some(r#"<a:order xmlns:a="urn:a"><a:id>7</a:id><a:ts>now</a:ts></a:order>"#),
None,
&[],
);
assert_eq!(
predicates,
vec![json!({
"deepEquals": { "body": "7" },
"xpath": { "selector": "//a:id", "ns": { "a": "urn:a" } },
"caseSensitive": false
})]
);
}
#[test]
fn an_xpath_that_fails_to_evaluate_fails_the_generation() {
let headers = crate::imposter::Headers::new();
let run = |generator: serde_json::Value, body: &str| {
Imposter::generate_predicates_impl(
&[generator],
"POST",
"/orders",
&headers,
Some(body),
None,
TEST_PEER,
&std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
)
};
for selector in ["//x:id", "nosuchfn(//a)"] {
let generator =
json!({ "matches": { "body": true }, "xpath": { "selector": selector } });
let failed = run(generator.clone(), "<a><id>1</id></a>");
assert!(
matches!(
&failed,
Err(crate::scripting::PredicateGeneratorError::Selector(e)) if e.selector == selector
),
"{selector}: {failed:?}"
);
let plain = run(generator, "plain")
.expect("a non-XML body generates")
.raw;
assert_eq!(plain[0]["deepEquals"]["body"], "", "{selector}");
}
let exists = json!({
"matches": { "body": true },
"xpath": { "selector": "//x:id" },
"predicateOperator": "exists"
});
run(exists, "<a><id>1</id></a>").expect("`exists` never evaluates the selector");
}
#[test]
fn except_is_carried_beside_a_selected_scalar() {
let predicates = generate(
json!({ "matches": { "body": true }, "jsonpath": { "selector": "$.ref" }, "except": "-\\d+$" }),
Some(r#"{"ref": "order-123"}"#),
None,
&[],
);
assert_eq!(
predicates,
vec![json!({
"deepEquals": { "body": "order-123" },
"jsonpath": { "selector": "$.ref" },
"except": "-\\d+$"
})]
);
}
#[test]
fn a_selector_that_does_not_compile_is_not_carried() {
let predicates = generate(
json!({ "matches": { "body": true }, "jsonpath": { "selector": "$[[[bad" } }),
Some(r#"{"id": 1}"#),
None,
&[],
);
assert_eq!(
predicates,
vec![json!({ "deepEquals": { "body": r#"{"id": 1}"# } })]
);
}
#[test]
fn ignore_drops_query_keys_in_every_form() {
for ignore in [json!("ts"), json!(["ts", "nonce"])] {
let predicates = generate(
json!({ "matches": { "query": true }, "ignore": { "query": ignore } }),
None,
Some("a=1&ts=99&nonce=x"),
&[],
);
let expected = if ignore.is_string() {
json!({ "query": { "a": "1", "nonce": "x" } })
} else {
json!({ "query": { "a": "1" } })
};
assert_eq!(predicates[0]["equals"], expected, "ignore {ignore}");
assert!(predicates[0].get("ignore").is_none());
}
}
#[test]
fn ignore_drops_a_header() {
let predicates = generate(
json!({
"matches": { "headers": { "X-Tenant": true, "X-Request-Id": true } },
"ignore": { "headers": "X-Request-Id" }
}),
None,
None,
&[("X-Tenant", "acme"), ("X-Request-Id", "r-1")],
);
assert_eq!(
predicates[0]["equals"],
json!({ "headers": { "X-Tenant": "acme" } })
);
}
#[test]
fn ignore_object_form_recurses_only_into_objects() {
let predicates = generate(
json!({ "matches": { "query": true }, "ignore": { "query": { "a": "x" } } }),
None,
Some("a=1&b=2"),
&[],
);
assert_eq!(
predicates[0]["equals"],
json!({ "query": { "a": "1", "b": "2" } })
);
}
#[test]
fn unread_generator_keys_are_listed() {
assert_eq!(
unread_generator_keys(
&json!({ "matchs": { "path": true }, "matches": {}, "keyCaseSensitive": true })
),
vec!["keyCaseSensitive", "matchs"]
);
assert!(
unread_generator_keys(&json!({
"matches": {}, "caseSensitive": true, "predicateOperator": "equals",
"except": "x", "jsonpath": {}, "xpath": {}, "ignore": {}, "inject": "f"
}))
.is_empty()
);
}
}
#[cfg(test)]
mod predicate_generator_shape_tests {
use super::*;
use serde_json::json;
fn generate(
generator: serde_json::Value,
body: Option<&str>,
query: Option<&str>,
headers: &[(&str, &str)],
) -> Vec<serde_json::Value> {
let headers: crate::imposter::Headers = headers
.iter()
.map(|(k, v)| ((*k).to_string(), vec![(*v).to_string()]))
.collect();
Imposter::generate_predicates_impl(
&[generator],
"POST",
"/orders",
&headers,
body,
query,
TEST_PEER,
&std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
)
.expect("predicate generation succeeds")
.raw
}
fn generation_error(generators: serde_json::Value) -> String {
let generators = generators.as_array().expect("a generator list").clone();
match Imposter::generate_predicates_impl(
&generators,
"POST",
"/orders",
&crate::imposter::Headers::new(),
None,
None,
TEST_PEER,
&std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
) {
Err(crate::scripting::PredicateGeneratorError::Invalid(message)) => message,
other => panic!("expected an invalid-predicate failure, got {other:?}"),
}
}
#[test]
fn an_unreadable_generator_fails_the_generation_instead_of_being_skipped() {
let cases = [
(json!(["x"]), "predicateGenerators[0] must be an object"),
(
json!([{"matches": {"path": true}}, {}]),
"predicateGenerators[1] needs `matches` or `inject`",
),
(
json!([{"inject": 42}]),
"predicateGenerators[0].inject must be a function string",
),
(
json!([{"matches": true}]),
"predicateGenerators[0].matches must be an object of request fields",
),
(
json!([{"matches": {"path": true}, "caseSensitive": "yes"}]),
"predicateGenerators[0].caseSensitive must be a boolean",
),
(
json!([{"matches": {"path": true}, "except": 5}]),
"predicateGenerators[0].except must be a string",
),
(
json!([{"matches": {"pathh": true}}]),
"predicateGenerators[0].matches field `pathh` is not a request field",
),
(
json!([{"matches": {"path": true}, "predicateOperator": 5}]),
"predicateGenerators[0].predicateOperator `5` is not a predicate operator",
),
];
for (generators, message) in cases {
let error = generation_error(generators.clone());
assert!(error.starts_with(message), "{generators}: {error}");
}
}
#[test]
fn requestfrom_and_ip_are_recorded_from_the_client_address() {
assert_eq!(
generate(json!({"matches": {"ip": true}}), None, None, &[]),
vec![json!({ "deepEquals": { "ip": "127.0.0.1" } })]
);
assert_eq!(
generate(json!({"matches": {"requestFrom": true}}), None, None, &[]),
vec![json!({ "deepEquals": { "requestFrom": "127.0.0.1:50000" } })]
);
assert_eq!(
generate(
json!({"matches": {"ip": true}, "predicateOperator": "exists"}),
None,
None,
&[]
),
vec![json!({ "exists": { "ip": true } })]
);
}
const FORM: (&str, &str) = ("Content-Type", "application/x-www-form-urlencoded");
#[test]
fn a_form_is_recorded_whole_or_by_listed_keys() {
assert_eq!(
generate(
json!({"matches": {"form": true}}),
Some("a=1&b=2"),
None,
&[FORM]
),
vec![json!({ "deepEquals": { "form": { "a": "1", "b": "2" } } })]
);
assert_eq!(
generate(
json!({"matches": {"form": {"a": true, "missing": true}}}),
Some("a=1&b=2"),
None,
&[FORM]
),
vec![json!({ "equals": { "form": { "a": "1" } } })]
);
assert_eq!(
generate(
json!({"matches": {"form": true}, "ignore": {"form": "b"}}),
Some("a=1&b=2"),
None,
&[FORM]
),
vec![json!({ "equals": { "form": { "a": "1" } } })]
);
}
#[test]
fn a_request_without_a_form_records_no_form_predicate() {
assert_eq!(
generate(
json!({"matches": {"form": true, "path": true}}),
Some(r#"{"a":1}"#),
None,
&[("Content-Type", "application/json")]
),
vec![json!({ "deepEquals": { "path": "/orders" } })]
);
assert_eq!(
generate(
json!({"matches": {"form": {"a": true}}}),
Some(""),
None,
&[FORM]
),
Vec::<serde_json::Value>::new(),
"an empty urlencoded body has no form either"
);
}
#[test]
fn every_request_field_is_recorded_in_a_fixed_order() {
let fields: Vec<String> = generate(
json!({"matches": {
"form": true, "ip": true, "requestFrom": true, "body": true,
"headers": true, "query": true, "path": true, "method": true
}}),
Some("a=1"),
Some("q=1"),
&[FORM],
)
.iter()
.map(|p| {
p["deepEquals"]
.as_object()
.and_then(|o| o.keys().next().cloned())
.expect("one field per predicate")
})
.collect();
assert_eq!(
fields,
[
"method",
"path",
"query",
"headers",
"body",
"requestFrom",
"ip",
"form"
]
);
}
#[test]
fn an_uncaptured_field_opted_out_with_false_records_the_rest() {
assert_eq!(
generate(
json!({"matches": {"path": true, "ip": false}}),
None,
None,
&[]
),
vec![json!({ "deepEquals": { "path": "/orders" } })]
);
}
#[test]
fn fields_are_emitted_in_a_fixed_order_with_parameters_on_each() {
let predicates = generate(
json!({
"matches": {
"body": true,
"headers": { "X-Tenant": true },
"query": true,
"path": true,
"method": true
},
"caseSensitive": true,
"except": "\\d+"
}),
Some("b1"),
Some("a=1"),
&[("x-tenant", "acme")],
);
assert_eq!(
predicates,
vec![
json!({ "deepEquals": { "method": "POST" }, "caseSensitive": true, "except": "\\d+" }),
json!({ "deepEquals": { "path": "/orders" }, "caseSensitive": true, "except": "\\d+" }),
json!({ "deepEquals": { "query": { "a": "1" } }, "caseSensitive": true, "except": "\\d+" }),
json!({ "equals": { "headers": { "X-Tenant": "acme" } }, "caseSensitive": true, "except": "\\d+" }),
json!({ "deepEquals": { "body": "b1" }, "caseSensitive": true, "except": "\\d+" }),
]
);
}
#[test]
fn a_query_sub_key_matcher_records_equals_over_the_listed_keys_only() {
let predicates = generate(
json!({ "matches": { "query": { "a": true, "missing": true } } }),
None,
Some("a=1&b=2"),
&[],
);
assert_eq!(
predicates,
vec![json!({ "equals": { "query": { "a": "1" } } })]
);
}
#[test]
fn a_listed_key_is_recorded_whatever_its_matcher_value() {
let predicates = generate(
json!({ "matches": { "query": { "q": "mountebank", "b": false } } }),
None,
Some("q=rift&b=2&c=3"),
&[],
);
assert_eq!(
predicates,
vec![json!({ "equals": { "query": { "q": "rift", "b": "2" } } })]
);
}
#[test]
fn a_whole_field_matcher_records_an_absent_field_as_empty() {
let predicates = generate(
json!({ "matches": { "query": true, "body": true } }),
None,
None,
&[],
);
assert_eq!(
predicates,
vec![
json!({ "deepEquals": { "query": {} } }),
json!({ "deepEquals": { "body": "" } }),
]
);
}
#[test]
fn whole_headers_are_recorded_with_deep_equals() {
let predicates = generate(
json!({ "matches": { "headers": true } }),
None,
None,
&[("x-tenant", "acme")],
);
assert_eq!(
predicates,
vec![json!({ "deepEquals": { "headers": { "x-tenant": "acme" } } })]
);
}
#[test]
fn exists_records_presence_per_field() {
let predicates = generate(
json!({
"matches": { "path": true, "query": true, "headers": { "X-Tenant": true } },
"predicateOperator": "exists"
}),
None,
Some("a=1&b=2"),
&[("x-tenant", "acme")],
);
assert_eq!(
predicates,
vec![
json!({ "exists": { "path": true } }),
json!({ "exists": { "query": { "a": true, "b": true } } }),
json!({ "exists": { "headers": { "X-Tenant": true } } }),
]
);
}
#[test]
fn an_explicit_operator_records_each_field_under_it() {
let predicates = generate(
json!({ "matches": { "path": true, "method": true }, "predicateOperator": "contains" }),
None,
None,
&[],
);
assert_eq!(
predicates,
vec![
json!({ "contains": { "method": "POST" } }),
json!({ "contains": { "path": "/orders" } }),
]
);
}
#[test]
fn an_explicit_equals_is_not_promoted_to_deep_equals() {
let predicates = generate(
json!({ "matches": { "query": true, "headers": { "X-Absent": true } },
"predicateOperator": "equals" }),
None,
Some("a=1"),
&[],
);
assert_eq!(
predicates,
vec![
json!({ "equals": { "query": { "a": "1" } } }),
json!({ "equals": { "headers": {} } }),
]
);
}
#[test]
fn a_selector_scopes_only_the_body_predicate() {
let predicates = generate(
json!({ "matches": { "path": true, "body": true }, "jsonpath": { "selector": "$.id" } }),
Some(r#"{"id": 42}"#),
None,
&[],
);
assert_eq!(
predicates,
vec![
json!({ "deepEquals": { "path": "/orders" } }),
json!({ "deepEquals": { "body": "42" }, "jsonpath": { "selector": "$.id" } }),
]
);
}
#[test]
fn a_false_matcher_records_nothing() {
let predicates = generate(
json!({ "matches": { "path": false, "method": true } }),
None,
None,
&[],
);
assert_eq!(
predicates,
vec![json!({ "deepEquals": { "method": "POST" } })]
);
}
#[test]
fn proxy_always_groups_recordings_by_their_predicate_list() {
let imposter = Imposter::new(
serde_json::from_value(json!({
"port": 0,
"protocol": "http",
"stubs": [{ "responses": [{ "proxy": { "to": "http://up", "mode": "proxyAlways" } }] }],
}))
.expect("valid imposter config"),
)
.expect("test imposter");
let record = |path: &str, body: &str| {
let headers: crate::imposter::Headers = crate::imposter::Headers::new();
let predicates = Imposter::generate_predicates_impl(
&[json!({ "matches": { "method": true, "path": true } })],
"GET",
path,
&headers,
None,
None,
TEST_PEER,
&std::sync::Arc::new(crate::imposter::ScriptFileAccess::Refused),
)
.expect("generates")
.raw;
let stub: Stub = serde_json::from_value(json!({
"predicates": predicates,
"responses": [{ "is": { "statusCode": 200, "body": body } }],
}))
.expect("valid stub");
imposter.insert_or_append_proxy_stub(stub, "http://up", "proxyAlways", None, None);
};
record("/a", "1");
record("/b", "2");
record("/a", "3");
let stubs = imposter.get_stubs();
let groups: Vec<(serde_json::Value, usize)> = stubs[1..]
.iter()
.map(|s| {
(
serde_json::to_value(&s.predicates).expect("serializes"),
s.responses.len(),
)
})
.collect();
assert_eq!(
groups,
vec![
(
json!([{ "deepEquals": { "method": "GET" } }, { "deepEquals": { "path": "/a" } }]),
2
),
(
json!([{ "deepEquals": { "method": "GET" } }, { "deepEquals": { "path": "/b" } }]),
1
),
]
);
}
}
#[cfg(test)]
mod placement_tests {
use super::*;
use serde_json::{Value, json};
fn imposter(stubs: Value) -> Imposter {
Imposter::new(
serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": stubs }))
.expect("valid imposter config"),
)
.expect("test imposter")
}
fn proxy(path: &str, mode: &str) -> Value {
json!({
"predicates": [{ "equals": { "path": path } }],
"responses": [{ "proxy": { "to": "http://up", "mode": mode } }],
})
}
fn is(body: &str) -> Value {
json!({ "responses": [{ "is": { "body": body } }] })
}
fn recording(path: &str, body: &str) -> Stub {
serde_json::from_value(json!({
"predicates": [{ "deepEquals": { "path": path } }],
"responses": [{ "is": { "statusCode": 200, "body": body } }],
}))
.expect("valid stub")
}
fn slot_at(imposter: &Imposter, index: usize) -> u64 {
imposter.snapshot().stubs()[index].slot
}
fn layout(imposter: &Imposter) -> Vec<String> {
imposter
.get_stubs()
.iter()
.map(|s| {
let v = serde_json::to_value(s).expect("serializes");
let bodies: Vec<String> = v["responses"]
.as_array()
.expect("responses")
.iter()
.map(|r| match r.get("proxy") {
Some(_) => "proxy".to_string(),
None => r["is"]["body"].as_str().expect("body").to_string(),
})
.collect();
bodies.join("+")
})
.collect()
}
#[test]
fn a_proxy_once_recording_goes_in_front_of_the_proxy_that_answered() {
let imp = imposter(json!([
proxy("/b", "proxyOnce"),
is("authored"),
proxy("/a", "proxyOnce")
]));
let answering = slot_at(&imp, 2);
imp.insert_or_append_proxy_stub(
recording("/a", "rec"),
"http://up",
"proxyOnce",
Some(answering),
None,
);
assert_eq!(layout(&imp), ["proxy", "authored", "rec", "proxy"]);
}
#[test]
fn a_proxy_always_recording_is_appended_after_every_later_stub() {
let imp = imposter(json!([proxy("/a", "proxyAlways"), is("authored")]));
let answering = slot_at(&imp, 0);
imp.insert_or_append_proxy_stub(
recording("/a", "rec"),
"http://up",
"proxyAlways",
Some(answering),
None,
);
assert_eq!(layout(&imp), ["proxy", "authored", "rec"]);
}
#[test]
fn a_proxy_always_recording_merges_only_into_a_stub_after_the_proxy_that_answered() {
let imp = imposter(json!([
proxy("/b", "proxyAlways"),
proxy("/a", "proxyAlways")
]));
imp.insert_or_append_proxy_stub(
recording("/a", "early"),
"http://up",
"proxyAlways",
Some(slot_at(&imp, 0)),
None,
);
assert_eq!(layout(&imp), ["proxy", "proxy", "early"]);
imp.insert_or_append_proxy_stub(
recording("/a", "second"),
"http://up",
"proxyAlways",
Some(slot_at(&imp, 1)),
None,
);
assert_eq!(layout(&imp), ["proxy", "proxy", "early+second"]);
}
#[test]
fn a_proxy_always_recording_does_not_merge_into_an_equal_stub_ahead_of_the_proxy() {
let imp = imposter(json!([
{ "predicates": [{ "deepEquals": { "path": "/a" } }], "responses": [{ "is": { "body": "ahead" } }] },
proxy("/a", "proxyAlways"),
]));
let answering = slot_at(&imp, 1);
imp.insert_or_append_proxy_stub(
recording("/a", "rec"),
"http://up",
"proxyAlways",
Some(answering),
None,
);
assert_eq!(layout(&imp), ["ahead", "proxy", "rec"]);
}
#[test]
fn proxy_always_recordings_with_no_predicates_merge_into_one_stub() {
let imp = imposter(json!([proxy("/a", "proxyAlways")]));
let answering = slot_at(&imp, 0);
for body in ["1", "2", "3"] {
let stub: Stub = serde_json::from_value(json!({
"predicates": [],
"responses": [{ "is": { "statusCode": 200, "body": body } }],
}))
.expect("valid stub");
imp.insert_or_append_proxy_stub(
stub,
"http://up",
"proxyAlways",
Some(answering),
None,
);
}
assert_eq!(layout(&imp), ["proxy", "1+2+3"]);
}
#[test]
fn a_vanished_anchor_falls_back_to_the_first_proxy_to_the_upstream() {
let imp = imposter(json!([
is("authored"),
proxy("/b", "proxyOnce"),
proxy("/a", "proxyOnce")
]));
let answering = slot_at(&imp, 2);
imp.delete_stub(2).expect("delete");
imp.insert_or_append_proxy_stub(
recording("/a", "rec"),
"http://up",
"proxyOnce",
Some(answering),
None,
);
assert_eq!(layout(&imp), ["authored", "rec", "proxy"]);
}
#[test]
fn a_vanished_proxy_always_anchor_merges_after_the_first_proxy_to_the_upstream() {
let imp = imposter(json!([
proxy("/b", "proxyAlways"),
proxy("/a", "proxyAlways")
]));
let answering = slot_at(&imp, 1);
imp.insert_or_append_proxy_stub(
recording("/a", "first"),
"http://up",
"proxyAlways",
Some(answering),
None,
);
imp.delete_stub(1).expect("delete");
imp.insert_or_append_proxy_stub(
recording("/a", "second"),
"http://up",
"proxyAlways",
Some(answering),
None,
);
imp.insert_or_append_proxy_stub(
recording("/c", "third"),
"http://up",
"proxyAlways",
Some(answering),
None,
);
assert_eq!(layout(&imp), ["proxy", "first+second", "third"]);
}
#[test]
fn with_no_anchor_and_no_proxy_stub_a_recording_goes_last() {
let imp = imposter(json!([is("authored")]));
imp.insert_or_append_proxy_stub(
recording("/a", "rec"),
"http://up",
"proxyOnce",
None,
None,
);
assert_eq!(layout(&imp), ["authored", "rec"]);
}
}
#[cfg(test)]
mod claim_tests {
use super::*;
use serde_json::json;
fn imposter() -> Imposter {
Imposter::new(
serde_json::from_value(json!({
"port": 0,
"protocol": "http",
"stubs": [{ "responses": [{ "proxy": { "to": "http://up", "mode": "proxyOnce" } }] }],
}))
.expect("valid imposter config"),
)
.expect("test imposter")
}
fn stub(body: &str) -> Stub {
serde_json::from_value(json!({
"predicates": [{ "deepEquals": { "path": "/a" } }],
"responses": [{ "is": { "statusCode": 200, "body": body } }],
}))
.expect("valid stub")
}
fn record(imp: &Imposter) -> RequestSignature {
let sig = RequestSignature::new("POST", "/a", None, &[]);
let port = imp.journal_port();
let token = match imp
.proxy_store
.try_claim_as(port, &sig, ProxyMode::ProxyOnce)
.expect("claim")
{
ClaimOutcome::Claimed(token) => token,
other => panic!("expected a claim, got {other:?}"),
};
imp.proxy_store
.record(
port,
sig.clone(),
token,
crate::recording::RecordedResponse {
status: 200,
headers: Vec::new(),
body: b"up".to_vec(),
latency_ms: None,
timestamp_secs: 0,
},
)
.expect("record");
imp.insert_or_append_proxy_stub(
stub("up"),
"http://up",
"proxyOnce",
None,
Some(RecordedClaim {
signature: sig.clone(),
token,
}),
);
sig
}
fn recorded(imp: &Imposter, sig: &RequestSignature) -> bool {
imp.proxy_store
.try_claim_as(imp.journal_port(), sig, ProxyMode::ProxyOnce)
.expect("claim")
== ClaimOutcome::AlreadyRecorded
}
#[test]
fn replacing_a_recording_with_new_content_forgets_its_claim() {
let imp = imposter();
let sig = record(&imp);
imp.replace_stub(0, stub("edited")).expect("replace");
assert!(!recorded(&imp, &sig));
}
#[test]
fn replacing_a_recording_with_identical_content_keeps_its_claim() {
let imp = imposter();
let sig = record(&imp);
imp.replace_stub(0, stub("up")).expect("replace");
assert!(recorded(&imp, &sig));
}
#[test]
fn moving_a_recording_keeps_its_claim() {
let imp = imposter();
let sig = record(&imp);
imp.move_stub(0, 1).expect("move");
assert!(recorded(&imp, &sig));
}
#[test]
fn deleting_a_recording_forgets_its_claim() {
let imp = imposter();
let sig = record(&imp);
imp.delete_stub(0).expect("delete");
assert!(!recorded(&imp, &sig));
}
fn slot_at(imp: &Imposter, index: usize) -> u64 {
imp.snapshot().stubs()[index].slot
}
#[test]
fn a_recording_is_shadowed_only_when_every_carrier_is_behind_the_answering_stub() {
let imp = imposter();
let sig = record(&imp);
let proxy = slot_at(&imp, 1);
assert!(
imp.shadowed_recordings(Some(proxy), &sig).is_empty(),
"carrier in front"
);
imp.move_stub(0, 1)
.expect("move the recording behind the proxy");
assert!(
!imp.shadowed_recordings(Some(proxy), &sig).is_empty(),
"carrier behind"
);
let other = RequestSignature::new("GET", "/elsewhere", None, &[]);
assert!(
imp.shadowed_recordings(Some(proxy), &other).is_empty(),
"no carrier"
);
assert!(
imp.shadowed_recordings(None, &sig).is_empty(),
"no answering stub"
);
assert!(
imp.shadowed_recordings(Some(u64::MAX), &sig).is_empty(),
"the answering stub is gone"
);
}
#[test]
fn deleting_another_stub_keeps_the_claim() {
let imp = imposter();
let sig = record(&imp);
imp.delete_stub(1).expect("delete the proxy stub");
assert!(recorded(&imp, &sig));
}
}
#[cfg(all(test, feature = "javascript"))]
mod dry_run_tests {
use super::*;
use serde_json::json;
fn stubs_with(mode: &str, generators: serde_json::Value) -> Vec<Stub> {
vec![
serde_json::from_value(json!({
"responses": [{ "proxy": {
"to": "http://up", "mode": mode, "predicateGenerators": generators,
} }],
}))
.expect("valid stub"),
]
}
fn inject(script: &str) -> Vec<Stub> {
stubs_with("proxyOnce", json!([{ "inject": script }]))
}
async fn dry_run(stubs: &[Stub], timeout: Duration) -> Result<(), GeneratorDryRun> {
let files = Arc::new(crate::imposter::ScriptFileAccess::network(None));
dry_run_predicate_generators(stubs, timeout, files).await
}
const TIMEOUT: Duration = Duration::from_secs(10);
#[tokio::test]
async fn a_throwing_inject_is_refused_with_its_source_and_message() {
let script = "function (config) { throw new Error('boom'); }";
let refusal = dry_run(&inject(script), TIMEOUT).await.unwrap_err();
let GeneratorDryRun::Refused { source, data } = refusal else {
panic!("expected a refusal, got {refusal:?}");
};
assert_eq!(source, format!("({script})(config);"));
assert_eq!(data.as_deref(), Some("boom"));
}
#[tokio::test]
async fn an_inject_returning_undefined_is_refused() {
let refusal = dry_run(&inject("function (config) {}"), TIMEOUT).await;
assert!(
matches!(refusal, Err(GeneratorDryRun::Refused { .. })),
"{refusal:?}"
);
}
#[tokio::test]
async fn an_inject_returning_an_empty_array_is_admitted() {
let admitted = dry_run(&inject("function (config) { return []; }"), TIMEOUT).await;
assert_eq!(admitted, Ok(()));
}
#[tokio::test]
async fn an_inject_guarded_on_is_dry_run_is_admitted() {
let script = "function (config) { if (config.request.isDryRun) { return []; } \
return [{ equals: JSON.parse(config.request.body) }]; }";
assert_eq!(dry_run(&inject(script), TIMEOUT).await, Ok(()));
let unguarded =
"function (config) { return [{ equals: JSON.parse(config.request.body) }]; }";
assert!(dry_run(&inject(unguarded), TIMEOUT).await.is_err());
}
#[tokio::test]
async fn the_inject_sees_mountebanks_synthetic_request() {
let script = "function (config) { var r = config.request; \
if (r.method !== 'GET' || r.path !== '/' || r.body !== '' || r.requestFrom !== '' \
|| 'ip' in r || Object.keys(r.query).length || Object.keys(r.headers).length \
|| Object.keys(r.form).length || r.isDryRun !== true) { throw new Error(JSON.stringify(r)); } \
return []; }";
assert_eq!(dry_run(&inject(script), TIMEOUT).await, Ok(()));
}
#[tokio::test]
async fn a_matches_only_list_never_reaches_the_script_pool() {
let stubs = stubs_with("proxyOnce", json!([{ "matches": { "path": true } }]));
assert_eq!(dry_run(&stubs, Duration::ZERO).await, Ok(()));
}
#[tokio::test]
async fn a_generated_predicate_the_engine_would_refuse_is_not_a_create_time_refusal() {
let script = "function (config) { return [{ notAnOperator: {} }]; }";
assert_eq!(dry_run(&inject(script), TIMEOUT).await, Ok(()));
}
#[tokio::test]
async fn an_inject_past_the_script_timeout_is_refused() {
let script = "function (config) { var end = Date.now() + 2000; while (Date.now() < end) {} return []; }";
let refusal = dry_run(&inject(script), Duration::from_millis(50)).await;
let Err(GeneratorDryRun::Refused { data, .. }) = refusal else {
panic!("expected a refusal, got {refusal:?}");
};
assert_eq!(data.as_deref(), Some("timed out after 50ms"));
}
#[tokio::test]
async fn every_proxy_mode_is_checked_proxy_transparent_included() {
let throwing = json!([{ "inject": "function () { throw new Error('boom'); }" }]);
for mode in ["proxyOnce", "proxyAlways", "proxyTransparent"] {
let refusal = dry_run(&stubs_with(mode, throwing.clone()), TIMEOUT).await;
assert!(refusal.is_err(), "{mode}: {refusal:?}");
}
}
#[tokio::test]
async fn response_and_predicate_injects_are_not_dry_run() {
let stubs: Vec<Stub> = vec![
serde_json::from_value(json!({
"predicates": [{ "inject": "function () { throw new Error('p'); }" }],
"responses": [{ "inject": "function () { throw new Error('r'); }" }],
}))
.expect("valid stub"),
];
assert_eq!(dry_run(&stubs, Duration::ZERO).await, Ok(()));
}
}
#[cfg(test)]
mod generation_failed_tests {
use super::*;
use crate::scripting::PredicateGeneratorError as E;
fn classify(error: E) -> GenerationFailed {
GenerationFailed::from(GeneratorFailure {
inject: Some("function (config) { return 1; }".to_string()),
error,
})
}
#[test]
fn each_generator_failure_is_classified_as_the_request_answers_it() {
let source = "(function (config) { return 1; })(config);";
let injection = |error: E, token: &str, data: Option<&str>| match classify(error) {
GenerationFailed::Runtime(RuntimeFailure::Injection {
token: t,
source: s,
data: d,
..
}) => {
assert_eq!(t, token);
assert_eq!(s, source);
assert_eq!(d.as_deref(), data);
}
other => panic!("expected an injection failure, got {other:?}"),
};
injection(
E::Threw {
message: Some("boom".into()),
detail: "Error: boom at 1:1".into(),
},
"script-error",
Some("boom"),
);
injection(
E::Threw {
message: None,
detail: "text".into(),
},
"script-error",
None,
);
injection(
E::Script("no context".into()),
"script-error",
Some("no context"),
);
injection(
E::Output("not an array".into()),
"invalid-output",
Some("not an array"),
);
assert!(matches!(
classify(E::Pool("gone".into())),
GenerationFailed::Runtime(RuntimeFailure::Unavailable {
token: "pool-failure",
..
})
));
assert!(matches!(
classify(E::Invalid("equal".into())),
GenerationFailed::Invalid {
token: "invalid-predicate",
..
}
));
}
}