use super::behavior_pipeline::{BehaviorOutcome, BehaviorRun, ServedParts, aborted_response};
use super::conditional::{self, ConditionalSpec};
use super::core::Imposter;
use super::core::{ProxiedResponse, ProxyBody, ProxyOutcome};
use super::headers::sanitize_header_value;
use super::predicates::parse_query_string;
use super::response::{
body_text, complete_from_default, execute_stub_response_with_rift, get_rift_script_config,
served_is,
};
use super::status::{invalid_status_response, resolve as resolve_status};
use super::types::{
DebugMatchResult, DebugRequest, DebugResponse, IsResponse, ProxyResponse, RecordedRequest,
ResponseMode, StubResponse, UpstreamTarget,
};
use crate::behaviors::{
CsvCache, LookupLoadError, Spliced, SplicedHeaders, authored_headers, header_to_title_case,
plain_headers,
};
use crate::extensions::decorate::{
ResponseDecorator, ResponsePhase, backend_error_response, with_annotation_scope,
};
use crate::extensions::exchange_inspector::{InspectRequest, InspectResponse, InspectVerdict};
use crate::extensions::no_match::{NoMatchContext, NoMatchDirective};
use crate::extensions::template::{RequestData, has_template_variables, process_template_spliced};
use crate::scripting::{
FaultDecision, ScriptCtxExtras, ScriptRequest, ScriptStubContext, resolve_script_timeout_ms,
should_inject_bounded_with_ctx, should_inject_bounded_with_ctx_traced,
};
#[cfg(feature = "javascript")]
use crate::scripting::{MountebankRequest, execute_mountebank_inject_bounded};
use crate::util::build_response_with_headers;
use base64::Engine;
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::body::Incoming;
use hyper::{Request, Response, StatusCode};
use rand::RngExt;
use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{debug, trace, warn};
use super::body_limits::{BodyReadError, CollectedBody};
use super::content_encoding::{Coding, Decoded};
fn proxy_body<'a>(raw: Option<&'a Bytes>, text: Option<&'a str>) -> Option<ProxyBody<'a>> {
raw.map(|raw| ProxyBody { raw, text })
}
async fn decode_request_body(
imposter: &Imposter,
coding: Coding,
raw: Bytes,
) -> Result<Result<Decoded, BodyReadError>, tokio::task::JoinError> {
let out = match imposter.body_guard.start(None).await {
Ok(out) => out,
Err(e) => return Ok(Err(e)),
};
tokio::task::spawn_blocking(move || super::content_encoding::decode(coding, &raw, out)).await
}
fn decode_failed_response(e: &tokio::task::JoinError) -> Response<Full<Bytes>> {
tracing::error!("request body decoding task failed: {e}");
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body(
StatusCode::INTERNAL_SERVER_ERROR,
"Request body decoding failed",
),
)
}
fn body_refused_response(e: &BodyReadError) -> Response<Full<Bytes>> {
let status = match e {
BodyReadError::BudgetExhausted => {
warn!("refused a request body: {e}");
StatusCode::SERVICE_UNAVAILABLE
}
_ => StatusCode::PAYLOAD_TOO_LARGE,
};
let mut response = limits_response(status, &e.to_string(), true);
response
.extensions_mut()
.insert(super::fault_io::LingerOnClose);
response
}
pub(crate) fn lookup_budget_response(e: &LookupLoadError) -> Response<Full<Bytes>> {
warn!("refused a lookup: {e}");
limits_response(StatusCode::SERVICE_UNAVAILABLE, &e.to_string(), false)
}
fn limits_response(status: StatusCode, message: &str, close: bool) -> Response<Full<Bytes>> {
let mut response = build_response_with_headers(
status,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body(status, message),
);
if close {
response.headers_mut().insert(
hyper::header::CONNECTION,
hyper::header::HeaderValue::from_static("close"),
);
}
if status == StatusCode::SERVICE_UNAVAILABLE {
response.headers_mut().insert(
hyper::header::RETRY_AFTER,
hyper::header::HeaderValue::from_static("1"),
);
}
response
}
fn body_read_error_response(e: &dyn std::error::Error) -> Response<Full<Bytes>> {
warn!("failed to read request body: {e}");
build_response_with_headers(
StatusCode::BAD_REQUEST,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body(StatusCode::BAD_REQUEST, "Failed to read request body"),
)
}
fn csv_cache() -> &'static CsvCache {
static CSV_CACHE: std::sync::OnceLock<CsvCache> = std::sync::OnceLock::new();
CSV_CACHE.get_or_init(CsvCache::new)
}
pub(super) const SCRIPT_TIMEOUT_HEADER: &str = "x-rift-script-timeout";
fn inject_timeout_response(
kind: crate::response::ErrorKind,
message: &str,
) -> Response<Full<Bytes>> {
let body = serde_json::json!({
"errors": [{ "code": kind.slug(), "type": kind.slug(), "message": message }]
})
.to_string();
build_response_with_headers(
StatusCode::GATEWAY_TIMEOUT,
[
("x-rift-imposter", "true"),
("x-rift-inject-error", "true"),
(SCRIPT_TIMEOUT_HEADER, "true"),
("content-type", "application/json"),
],
body,
)
}
fn template_error_response(e: &str) -> Response<Full<Bytes>> {
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-template-error", "true"),
("content-type", "application/json"),
],
crate::response::error_body(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("template rendering failed: {e}"),
),
)
}
fn state_ops_error_response(e: &str) -> Response<Full<Bytes>> {
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-state-ops-error", "true"),
("content-type", "application/json"),
],
crate::response::error_body(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("state operation failed: {e}"),
),
)
}
fn debug_matching_error_response() -> Response<Full<Bytes>> {
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body(StatusCode::INTERNAL_SERVER_ERROR, "Debug matching failed"),
)
}
fn debug_matching_timeout_response() -> Response<Full<Bytes>> {
build_response_with_headers(
StatusCode::GATEWAY_TIMEOUT,
[
("x-rift-imposter", "true"),
(SCRIPT_TIMEOUT_HEADER, "true"),
("content-type", "application/json"),
],
crate::response::error_body(StatusCode::GATEWAY_TIMEOUT, "Debug matching timed out"),
)
}
fn build_failure_response(e: &hyper::http::Error, log_context: &str) -> Response<Full<Bytes>> {
warn!("{log_context}: {e}");
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body(StatusCode::INTERNAL_SERVER_ERROR, "Response build error"),
)
}
fn invalid_header_name<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
names
.into_iter()
.find(|name| hyper::header::HeaderName::from_bytes(name.as_bytes()).is_err())
}
fn invalid_header_name_response(name: &str) -> Response<Full<Bytes>> {
let message = format!(
"Response build error: invalid header name {:?}",
super::response::truncate_with_ellipsis(name, 256)
);
warn!("stub response build failed: {message}");
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body(StatusCode::INTERNAL_SERVER_ERROR, &message),
)
}
fn strict_behaviors_for(config: &super::types::ImposterConfig) -> bool {
config.strict_behaviors || crate::util::strict_behaviors_env()
}
pub(super) enum BinaryBody {
Decoded(Bytes),
RawFallback(Bytes),
}
pub(super) fn decode_binary_body(
body: String,
strict: bool,
) -> Result<BinaryBody, Box<Response<Full<Bytes>>>> {
let decoded =
base64::engine::general_purpose::STANDARD.decode(strip_non_base64(&body).as_bytes());
match decoded {
Ok(decoded) => Ok(BinaryBody::Decoded(Bytes::from(decoded))),
Err(e) if strict => {
warn!("Failed to decode base64 body: {e}; failing loud (strictBehaviors)");
Err(Box::new(build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-binary-error", "true"),
("content-type", "application/json"),
],
crate::response::error_body_typed(
StatusCode::INTERNAL_SERVER_ERROR,
crate::response::ErrorKind::BehaviorError,
&format!("binary base64 decode failed (strictBehaviors): {e}"),
),
)))
}
Err(e) => {
warn!("Failed to decode base64 body: {e}, using raw body");
Ok(BinaryBody::RawFallback(Bytes::from(body)))
}
}
}
fn strip_non_base64(body: &str) -> std::borrow::Cow<'_, str> {
let in_alphabet = |c: char| c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=');
if body.chars().all(in_alphabet) {
std::borrow::Cow::Borrowed(body)
} else {
std::borrow::Cow::Owned(body.chars().filter(|&c| in_alphabet(c)).collect())
}
}
fn log_upstream_failure(context: &str, e: &anyhow::Error) {
warn!("{context}: {e:#}");
}
fn upstream_error_response(
e: &anyhow::Error,
log_context: &str,
marker: &'static str,
client_prefix: &str,
) -> Response<Full<Bytes>> {
log_upstream_failure(log_context, e);
build_response_with_headers(
StatusCode::BAD_GATEWAY,
[
("x-rift-imposter", "true"),
(marker, "true"),
("content-type", "application/json"),
],
crate::response::error_body(StatusCode::BAD_GATEWAY, &format!("{client_prefix}: {e}")),
)
}
fn proxy_leg_error_response(
e: &anyhow::Error,
log_context: &str,
marker: &'static str,
client_prefix: &str,
) -> Response<Full<Bytes>> {
if e.downcast_ref::<crate::extensions::decorate::BackendUnavailable>()
.is_some()
{
return backend_error_response(e);
}
upstream_error_response(e, log_context, marker, client_prefix)
}
pub(crate) fn xpath_selector_error_response(
e: &crate::behaviors::XPathSelectorError,
) -> Response<Full<Bytes>> {
tracing::warn!("{e}");
let kind = crate::response::ErrorKind::BadData.slug();
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
serde_json::json!({
"errors": [{
"code": kind,
"type": kind,
"message": "malformed xpath predicate selector",
}]
})
.to_string(),
)
}
pub(crate) fn generator_injection_error_response(
source: &str,
data: Option<&str>,
token: &str,
) -> Response<Full<Bytes>> {
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
("x-rift-generator-error", token),
],
crate::response::generator_injection_error_body(source, data),
)
}
pub(crate) fn generator_unavailable_response(token: &str) -> Response<Full<Bytes>> {
build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
("x-rift-generator-error", token),
],
crate::response::error_body_typed(
StatusCode::INTERNAL_SERVER_ERROR,
crate::response::ErrorKind::InternalError,
"could not run a predicateGenerator injection",
),
)
}
#[cfg(feature = "javascript")]
fn inject_failure_body(
kind: crate::response::ErrorKind,
message: &str,
data: Option<&str>,
) -> String {
let mut error = serde_json::json!({
"code": kind.slug(),
"type": kind.slug(),
"message": message,
});
if let Some(data) = data {
error["data"] = serde_json::Value::String(data.to_owned());
}
serde_json::json!({ "errors": [error] }).to_string()
}
fn matcher_error_response(e: &anyhow::Error) -> Response<Full<Bytes>> {
if let Some(xpath) = e.downcast_ref::<crate::behaviors::XPathSelectorError>() {
return xpath_selector_error_response(xpath);
}
if let Some(t) = e.downcast_ref::<crate::scripting::ScriptTimeoutError>() {
return inject_timeout_response(
crate::response::ErrorKind::PredicateInjectionTimeout,
&t.to_string(),
);
}
#[cfg(feature = "javascript")]
{
if let Some(pred_err) = e.downcast_ref::<crate::scripting::PredicateInjectionError>() {
let body = inject_failure_body(
crate::response::ErrorKind::InvalidPredicateInjection,
&pred_err.to_string(),
pred_err.data(),
);
return build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-inject-error", "true"),
("content-type", "application/json"),
],
body,
);
}
}
backend_error_response(e)
}
struct Inspection {
method: String,
path: String,
query: String,
headers: hyper::HeaderMap,
body: Option<String>,
mode: ResponseMode,
}
fn inspector_reject_status(status: u16) -> StatusCode {
StatusCode::from_u16(status).unwrap_or_else(|_| {
tracing::warn!(
status,
"exchange inspector rejected with an out-of-range status code; using 502"
);
StatusCode::BAD_GATEWAY
})
}
impl Inspection {
fn view(&self, port: u16) -> InspectRequest<'_> {
InspectRequest {
port,
method: &self.method,
path: &self.path,
query: &self.query,
headers: &self.headers,
body: self.body.as_deref(),
mode: &self.mode,
}
}
}
pub async fn handle_imposter_request_decorated(
req: Request<Incoming>,
imposter: Arc<Imposter>,
client_addr: SocketAddr,
port: u16,
decorator: Option<Arc<dyn ResponseDecorator>>,
) -> Result<Response<Full<Bytes>>, Infallible> {
let (response, annotations) =
with_annotation_scope(handle_imposter_request(req, imposter, client_addr)).await;
let mut response = response?;
if let Some(decorator) = decorator {
decorator.decorate(
ResponsePhase::DataPlane,
Some(port),
&annotations,
response.headers_mut(),
);
}
Ok(response)
}
pub async fn handle_imposter_request(
req: Request<Incoming>,
imposter: Arc<Imposter>,
client_addr: SocketAddr,
) -> Result<Response<Full<Bytes>>, Infallible> {
let cors_preflight = if imposter.config.allow_cors.enabled() {
CorsPreflight::of(&req)
} else {
None
};
let method = req.method().to_string();
let started = Instant::now();
let (request_now, refused) = match crate::imposter::clock::resolve_request_now(
imposter.config.clock_source(),
req.headers()
.get(crate::imposter::clock::NOW_HEADER)
.map(|v| v.to_str().unwrap_or("<not visible ASCII>")),
) {
Ok(now) => (now, None),
Err(bad) => (
None,
Some(build_response_with_headers(
StatusCode::BAD_REQUEST,
[
("x-rift-imposter", "true"),
("content-type", "application/json"),
],
crate::response::error_body_typed(
StatusCode::BAD_REQUEST,
crate::response::ErrorKind::BadData,
&bad.to_string(),
),
)),
),
};
let mut journal_index = None;
let mut inspection: Option<Inspection> = None;
let request_rng = imposter.request_rng();
let inner = Box::pin(crate::imposter::rng::with_request_rng(
request_rng,
crate::imposter::clock::with_imposter_clock(
Arc::clone(&imposter.clock),
crate::imposter::clock::with_request_override(
request_now,
handle_request_inner(
req,
Arc::clone(&imposter),
client_addr,
&mut journal_index,
&mut inspection,
),
),
),
));
let in_flight = imposter.in_flight.load_full();
let computed = match refused {
Some(refusal) => {
drop(inner);
Some(refusal)
}
None => tokio::select! {
biased;
() = in_flight.cancelled() => None,
response = inner => Some(response?),
},
};
let mut response = match computed {
Some(response) => response,
None => {
inspection = None;
aborted_response()
}
};
if let Some(inspector) = &imposter.exchange_inspector
&& let Some(seen) = inspection.as_ref()
{
let port = imposter.config.port.unwrap_or(0);
let (parts, body) = response.into_parts();
let bytes = match body.collect().await {
Ok(collected) => collected.to_bytes(),
Err(never) => match never {},
};
let resp_view = InspectResponse {
status: parts.status.as_u16(),
headers: &parts.headers,
body: &bytes,
};
response = match inspector.inspect_response(&seen.view(port), &resp_view) {
InspectVerdict::Proceed => Response::from_parts(parts, Full::new(bytes)),
InspectVerdict::Reject {
status,
content_type,
body,
} => build_response_with_headers(
inspector_reject_status(status),
[
("content-type", content_type.as_str()),
("x-rift-imposter", "true"),
],
body,
),
};
}
crate::extensions::record_request(&method, response.status().as_u16());
if let Some(index) = journal_index
&& is_served_answer(&response)
{
imposter.attach_response_outcome(
index,
response.status().as_u16(),
u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
);
}
if let Some(preflight) = cors_preflight {
preflight.apply(response.headers_mut());
}
reconcile_content_length(&mut response);
Ok(response)
}
fn reconcile_content_length(response: &mut Response<Full<Bytes>>) {
use hyper::body::Body as _;
use hyper::header::{CONTENT_LENGTH, HeaderValue, TRANSFER_ENCODING};
if !response.headers().contains_key(CONTENT_LENGTH) {
return;
}
let status = response.status();
let length = if response.headers().contains_key(TRANSFER_ENCODING)
|| status.is_informational()
|| status == StatusCode::NO_CONTENT
{
None
} else {
response.body().size_hint().exact()
};
match length {
Some(length) => {
response
.headers_mut()
.insert(CONTENT_LENGTH, HeaderValue::from(length));
}
None => {
response.headers_mut().remove(CONTENT_LENGTH);
}
}
}
#[derive(Clone, Copy, Debug)]
struct DebugReport;
fn is_served_answer<B>(response: &Response<B>) -> bool {
response.extensions().get::<DebugReport>().is_none()
&& super::fault_io::tcp_fault_carrier(response).is_none()
}
#[derive(Debug)]
struct CorsPreflight {
origin: hyper::header::HeaderValue,
method: hyper::header::HeaderValue,
headers: hyper::header::HeaderValue,
}
impl CorsPreflight {
fn of<B>(req: &Request<B>) -> Option<Self> {
use hyper::header::{
ACCESS_CONTROL_REQUEST_HEADERS, ACCESS_CONTROL_REQUEST_METHOD, HeaderName, ORIGIN,
};
if req.method() != hyper::Method::OPTIONS {
return None;
}
let present = |name: &HeaderName| {
req.headers()
.get(name)
.filter(|value| !value.is_empty())
.cloned()
};
Some(Self {
origin: present(&ORIGIN)?,
method: present(&ACCESS_CONTROL_REQUEST_METHOD)?,
headers: present(&ACCESS_CONTROL_REQUEST_HEADERS)?,
})
}
fn apply(self, headers: &mut hyper::HeaderMap) {
use hyper::header::{
ACCESS_CONTROL_ALLOW_HEADERS, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_ORIGIN,
};
headers.insert(ACCESS_CONTROL_ALLOW_HEADERS, self.headers);
headers.insert(ACCESS_CONTROL_ALLOW_METHODS, self.method);
headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, self.origin);
}
}
#[derive(Debug)]
enum TemplateRender {
Rendered {
body: Spliced,
headers: SplicedHeaders,
},
Failed(String),
}
fn render_template_parts(
imposter: &Imposter,
request_data: &RequestData,
flow_id: &str,
body: String,
headers: crate::imposter::Headers,
debug: bool,
stub: super::headers::StubRef<'_>,
) -> TemplateRender {
let template_ctx = crate::extensions::template_fn::TemplateContext {
request: request_data,
flow_id,
flow_store: imposter.flow_store.as_ref(),
previous_value: None,
};
let body = match crate::extensions::template_fn::render_templated_spliced(
&body,
&template_ctx,
debug,
|value| value,
) {
Ok(rendered) => rendered,
Err(e) => return TemplateRender::Failed(e),
};
let mut rendered_headers =
SplicedHeaders::with_capacity_and_hasher(headers.len(), Default::default());
for (name, values) in headers {
let mut rendered_values = Vec::with_capacity(values.len());
for v in values {
match crate::extensions::template_fn::render_templated_spliced(
&v,
&template_ctx,
debug,
|substituted| sanitize_header_value(&substituted, stub),
) {
Ok(rendered) => rendered_values.push(rendered),
Err(e) => return TemplateRender::Failed(e),
}
}
rendered_headers.insert(name.into(), rendered_values);
}
TemplateRender::Rendered {
body,
headers: rendered_headers,
}
}
async fn render_templated_response(
imposter: &Arc<Imposter>,
request_data: RequestData,
flow_id: String,
body: String,
headers: crate::imposter::Headers,
debug: bool,
stub: super::headers::StubRef<'_>,
) -> anyhow::Result<TemplateRender> {
let reads_state = crate::extensions::template_fn::reads_flow_state(&body)
|| headers
.values()
.flatten()
.any(|v| crate::extensions::template_fn::reads_flow_state(v));
if !reads_state {
return Ok(render_template_parts(
imposter,
&request_data,
&flow_id,
body,
headers,
debug,
stub,
));
}
let port = stub.port;
let index = stub.index;
let id = stub.id.map(str::to_string);
imposter
.run_flow_blocking(move |imp| {
let stub = super::headers::StubRef {
port,
index,
id: id.as_deref(),
};
Ok(render_template_parts(
imp,
&request_data,
&flow_id,
body,
headers,
debug,
stub,
))
})
.await
}
fn stub_ref<'a>(
imposter: &Imposter,
stub_index: usize,
stub: &'a super::types::Stub,
) -> super::headers::StubRef<'a> {
super::headers::StubRef {
port: imposter.bound_port(),
index: stub_index,
id: stub.id.as_deref(),
}
}
async fn handle_request_inner(
req: Request<Incoming>,
imposter: Arc<Imposter>,
client_addr: SocketAddr,
journal_index: &mut Option<u64>,
inspection: &mut Option<Inspection>,
) -> Result<Response<Full<Bytes>>, Infallible> {
if !imposter.is_enabled() {
return Ok(build_response_with_headers(
StatusCode::SERVICE_UNAVAILABLE,
[
("x-rift-imposter-disabled", "true"),
("content-type", "application/json"),
],
crate::response::error_body_typed(
StatusCode::SERVICE_UNAVAILABLE,
crate::response::ErrorKind::ImposterDisabled,
"Imposter is disabled",
),
));
}
imposter.increment_request_count();
let (parts, body) = req.into_parts();
let method = parts.method.to_string();
let uri = parts.uri;
let raw_headers = parts.headers;
let request_headers: crate::util::OrderedMap<String, Vec<String>> =
crate::imposter::headers::collect_request_headers(&raw_headers, header_to_title_case);
let path = uri.path().to_string();
let query_str = uri.query().unwrap_or("").to_string();
let _body_reservation: CollectedBody = match imposter.body_guard.collect(body).await {
Ok(collected) => collected,
Err(BodyReadError::Read(e)) => {
return Ok(body_read_error_response(e.as_ref()));
}
Err(e) => return Ok(body_refused_response(&e)),
};
let wire_bytes = Some(_body_reservation.bytes().clone()).filter(|bytes| !bytes.is_empty());
let (_decoded_reservation, body_undefined) = match Coding::of(&raw_headers) {
None => (None, false),
Some(coding) => {
match decode_request_body(&imposter, coding, _body_reservation.bytes().clone()).await {
Ok(Ok(Decoded::Body(decoded))) => (Some(decoded), false),
Ok(Ok(Decoded::Undefined)) => (None, true),
Ok(Err(e)) => return Ok(body_refused_response(&e)),
Err(e) => return Ok(decode_failed_response(&e)),
}
}
};
let body_bytes = match &_decoded_reservation {
Some(decoded) => Some(decoded.bytes().clone()),
None if body_undefined => None,
None => wire_bytes.clone(),
}
.filter(|bytes| !bytes.is_empty());
let (body_string, body_mode): (Option<std::borrow::Cow<'_, str>>, ResponseMode) =
match body_bytes.as_deref() {
None => (None, ResponseMode::Text),
Some(bytes) => match std::str::from_utf8(bytes) {
Ok(text) => (Some(std::borrow::Cow::Borrowed(text)), ResponseMode::Text),
Err(_) => (
Some(std::borrow::Cow::Owned(
base64::engine::general_purpose::STANDARD.encode(bytes),
)),
ResponseMode::Binary,
),
},
};
*journal_index = if imposter.config.record_requests {
let arrived_at = crate::imposter::clock::recorded_instant(&imposter.clock);
let recorded = RecordedRequest {
body_omitted: false,
request_from: client_addr.to_string(),
method: method.clone(),
path: path.clone(),
query: parse_query_string(&query_str).into_iter().collect(),
headers: request_headers
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect(),
body: (!body_undefined).then(|| body_string.as_deref().unwrap_or_default().to_string()),
mode: body_mode.clone(),
timestamp: super::types::journal_timestamp(chrono::Utc::now()),
clock_ms: arrived_at.map(|(ms, _)| ms),
clock_source: arrived_at.map(|(_, source)| source),
match_outcome: None,
status: None,
latency_ms: None,
node: None,
};
imposter.record_request(recorded)
} else {
None
};
if let Some(inspector) = &imposter.exchange_inspector {
let port = imposter.config.port.unwrap_or(0);
let req_view = InspectRequest {
port,
method: &method,
path: &path,
query: &query_str,
headers: &raw_headers,
body: body_string.as_deref(),
mode: &body_mode,
};
match inspector.inspect_request(&req_view) {
InspectVerdict::Reject {
status,
content_type,
body,
} => {
return Ok(build_response_with_headers(
inspector_reject_status(status),
[
("content-type", content_type.as_str()),
("x-rift-imposter", "true"),
],
body,
));
}
InspectVerdict::Proceed => {
*inspection = Some(Inspection {
method: method.clone(),
path: path.clone(),
query: query_str.clone(),
headers: raw_headers.clone(),
body: body_string.as_deref().map(str::to_string),
mode: body_mode.clone(),
});
}
}
}
rekey_request_stream(
&imposter,
&method,
&path,
&request_headers,
&query_str,
body_string.as_deref(),
);
let method_str = method.as_str();
let path_str = path.as_str();
let query_opt = if query_str.is_empty() {
None
} else {
Some(query_str.as_str())
};
let is_debug_mode = request_headers
.get("X-Rift-Debug")
.or_else(|| request_headers.get("x-rift-debug"))
.and_then(|v| v.first())
.map(|v| v.eq_ignore_ascii_case("true") || v == "1")
.unwrap_or(false);
let script_timeout = std::time::Duration::from_millis(
crate::scripting::resolve_script_timeout_ms(&imposter.config),
);
if is_debug_mode {
let debug_imposter = Arc::clone(&imposter);
let (dbg_method, dbg_path, dbg_query) = (method.clone(), path.clone(), query_str.clone());
let dbg_headers = request_headers.clone();
let dbg_body = body_string.as_deref().map(str::to_string);
let handle = crate::extensions::decorate::spawn_blocking_annotated(move || {
handle_debug_request(
&debug_imposter,
&dbg_method,
&dbg_path,
&dbg_query,
&dbg_headers,
&dbg_body,
client_addr,
)
});
let mut report = match tokio::time::timeout(script_timeout, handle).await {
Ok(Ok((response, annotations))) => {
crate::extensions::decorate::replay_annotations(annotations);
response?
}
Ok(Err(join_err)) => {
warn!("debug matching task panicked: {join_err}");
debug_matching_error_response()
}
Err(_elapsed) => {
warn!(
"debug matching timed out after {}ms",
script_timeout.as_millis()
);
debug_matching_timeout_response()
}
};
report.extensions_mut().insert(DebugReport);
return Ok(report);
}
let request_from = client_addr.to_string();
let client_ip = client_addr.ip().to_string();
let want_trace = journal_index.is_some();
let scenario_transitions = imposter.scenario_transitions();
let script_scope = imposter.script_scope();
let (mut matched, mut trace) = match imposter
.find_matching_stub_with_client_bounded_inner(
method_str,
path_str,
&request_headers,
query_opt,
body_string.as_deref(),
Some(&request_from),
Some(&client_ip),
script_timeout,
want_trace,
script_scope.clone(),
)
.await
{
Ok(traced) => traced,
Err(e) => return Ok(matcher_error_response(&e)),
};
if matched.is_none()
&& let Some(interceptor) = &imposter.no_match_interceptor
{
let ctx = NoMatchContext {
port: imposter.config.port.unwrap_or(0),
method: method_str,
path: path_str,
};
if interceptor.on_no_match(ctx).await == NoMatchDirective::RetryMatch {
(matched, trace) = match imposter
.find_matching_stub_with_client_bounded_inner(
method_str,
path_str,
&request_headers,
query_opt,
body_string.as_deref(),
Some(&request_from),
Some(&client_ip),
script_timeout,
want_trace,
script_scope.clone(),
)
.await
{
Ok(traced) => traced,
Err(e) => return Ok(matcher_error_response(&e)),
};
}
}
if let (Some(index), Some(trace)) = (*journal_index, trace) {
let winner = matched.as_ref().map(|(state, i)| (&state.stub, *i));
imposter.attach_match_outcome(index, trace.into_outcome(winner));
}
if let Some((stub_state, stub_index)) = matched {
let scenario_flow_id = imposter.resolve_flow_id(&request_headers);
if stub_state.stub.new_scenario_state.is_some() {
let transition = {
let flow_id = scenario_flow_id.clone();
let stub_state = Arc::clone(&stub_state);
imposter
.run_flow_blocking(move |imp| {
imp.apply_scenario_transition(&flow_id, &stub_state.stub)
})
.await
};
if let Err(e) = transition {
return Ok(backend_error_response(&e));
}
}
let response: Option<&StubResponse> = match imposter.next_stub_response(&stub_state) {
Ok(r) => r,
Err(e) => return Ok(backend_error_response(&e)),
};
if let Some(StubResponse::Proxy {
proxy: proxy_config,
behaviors_parsed,
..
}) = response
{
let run = behaviors_parsed
.as_deref()
.filter(|parsed| parsed.transforms_response())
.map(|parsed| BehaviorRun {
behaviors: parsed,
method: &method,
uri: &uri,
request_headers: &request_headers,
request_body: body_string.as_deref(),
request_body_undefined: body_undefined,
client_addr: Some(client_addr),
script_scope: script_scope.clone(),
script_files: imposter.script_file_access(),
stub: stub_ref(&imposter, stub_index, &stub_state.stub),
csv_cache: csv_cache(),
body_guard: &imposter.body_guard,
script_timeout,
strict: strict_behaviors_for(&imposter.config),
default_response: imposter.config.default_response.as_ref(),
});
trace!("Handling proxy request to {}", proxy_config.to);
match imposter
.handle_proxy_request(
proxy_config,
UpstreamTarget::Origin,
method_str,
&uri,
&request_headers,
proxy_body(wire_bytes.as_ref(), body_string.as_deref()),
run.as_ref(),
Some(stub_state.slot),
client_addr,
)
.await
{
Ok(ProxyOutcome::StrictFailure(response)) => return Ok(response),
Ok(ProxyOutcome::Served(ProxiedResponse {
status,
headers: response_headers,
body,
latency_ms: latency,
})) => {
let mut response = Response::builder().status(status);
for (k, v) in &response_headers {
if !crate::util::is_hop_by_hop_header(k) {
response = response.header(k, v);
}
}
response = response.header("x-rift-imposter", "true");
response = response.header("x-rift-proxy", "true");
if let Some(ms) = latency {
response = response.header("x-rift-proxy-latency", ms.to_string());
}
return Ok(response
.body(Full::new(Bytes::from(body)))
.unwrap_or_else(|e| {
build_failure_response(
&e,
"proxy response build failed (bad upstream header?)",
)
}));
}
Err(e) => {
return Ok(proxy_leg_error_response(
&e,
"Proxy request failed",
"x-rift-proxy-error",
"Proxy error",
));
}
}
}
#[cfg(feature = "javascript")]
if let Some(StubResponse::Inject {
inject: inject_fn,
behaviors_parsed,
..
}) = response
{
trace!("Handling inject response");
let mb_request = MountebankRequest {
method: method.clone(),
path: path.clone(),
query: parse_query_string(&query_str),
headers: request_headers.clone(),
body: body_string.as_deref().map(str::to_string),
body_undefined,
mode: Some(body_mode.clone()),
request_from: Some(client_addr.to_string()),
ip: Some(client_addr.ip().to_string()),
form: Imposter::request_form(&request_headers, body_string.as_deref()),
is_dry_run: false,
};
match execute_mountebank_inject_bounded(
inject_fn.clone(),
mb_request,
script_scope.clone(),
stub_state.stub.id.clone(),
imposter.script_file_access(),
script_timeout,
)
.await
{
Ok(inject_response) => {
let authored = IsResponse::decoded(
inject_response.status_code.map(|status| match status {
crate::behaviors::ResponseStatus::Code(code) => {
super::types::StatusValue::Code(code)
}
crate::behaviors::ResponseStatus::Text(text) => {
super::types::StatusValue::from_text(text)
}
}),
inject_response.headers.map(|headers| {
headers.into_iter().map(|(k, v)| (k, vec![v])).collect()
}),
inject_response.body.map(serde_json::Value::String),
None,
);
let mut parts = ServedParts::completed(
&authored,
imposter.config.default_response.as_ref(),
);
if let Some(parsed_behaviors) = behaviors_parsed {
let run = BehaviorRun {
behaviors: parsed_behaviors,
method: &method,
uri: &uri,
request_headers: &request_headers,
request_body: body_string.as_deref(),
request_body_undefined: body_undefined,
client_addr: Some(client_addr),
script_scope: script_scope.clone(),
script_files: imposter.script_file_access(),
stub: stub_ref(&imposter, stub_index, &stub_state.stub),
csv_cache: csv_cache(),
body_guard: &imposter.body_guard,
script_timeout,
strict: strict_behaviors_for(&imposter.config),
default_response: imposter.config.default_response.as_ref(),
};
match run.apply(parts).await {
BehaviorOutcome::Applied { parts: applied, .. } => parts = applied,
BehaviorOutcome::StrictFailure(response) => return Ok(response),
}
}
let served = match resolve_status(
parts.status,
parts.status_text.as_ref().map(Spliced::as_str),
imposter.config.default_response.as_ref(),
) {
Ok(served) => served,
Err(value) => return Ok(invalid_status_response(&value)),
};
let mut response = Response::builder().status(served);
for (k, values) in &parts.headers {
for v in values {
response = response.header(k.as_str(), v.as_str());
}
}
response = response.header("x-rift-imposter", "true");
response = response.header("x-rift-inject", "true");
return Ok(response
.body(Full::new(Bytes::from(parts.body.into_text())))
.unwrap_or_else(|e| {
match invalid_header_name(parts.headers.keys().map(|k| k.as_str())) {
Some(name) => invalid_header_name_response(name),
None => build_failure_response(
&e,
"inject response build failed (bad injected header?)",
),
}
}));
}
Err(e) => {
log_upstream_failure("Inject function failed", &e);
if let Some(t) = e.downcast_ref::<crate::scripting::ScriptTimeoutError>() {
return Ok(inject_timeout_response(
crate::response::ErrorKind::InjectionTimeout,
&t.to_string(),
));
}
let data = e
.downcast_ref::<crate::scripting::InjectionFailure>()
.and_then(|f| f.data.as_deref());
let body = inject_failure_body(
crate::response::ErrorKind::InvalidInjection,
&format!("{e}"),
data,
);
return Ok(build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-inject-error", "true"),
("content-type", "application/json"),
],
body,
));
}
}
}
if let Some(script_config) = response.and_then(get_rift_script_config) {
let held_component = match script_config.component.as_deref() {
None => None,
Some(reference) => {
let entry = reference
.parse::<crate::imposter::components::ComponentId>()
.ok()
.and_then(|id| imposter.components.get(&id));
match entry {
Some(entry) => Some(entry),
None => {
return Ok(build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-script-error", "true"),
("content-type", "application/json"),
],
crate::response::error_body(
StatusCode::INTERNAL_SERVER_ERROR,
&format!(
"Script error: unknown component {reference}; upload it with POST /components"
),
),
));
}
}
}
};
let code = held_component
.as_ref()
.map(|entry| &*entry.code)
.or(script_config.code.as_deref());
let Some(code) = code else {
return Ok(build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-script-error", "true"),
("content-type", "application/json"),
],
crate::response::error_body(
StatusCode::INTERNAL_SERVER_ERROR,
"script not resolved: `file:`/`ref:` sources must be resolved before serving",
),
));
};
let engine = match (&script_config.engine, &held_component) {
(Some(engine), _) => engine.clone(),
(None, Some(_)) => "wasm".to_owned(),
(None, None) => imposter.config.default_script_engine().to_owned(),
};
if held_component.is_some() && !crate::scripting::ScriptEngineKind::is_wasm(&engine) {
return Ok(build_response_with_headers(
StatusCode::INTERNAL_SERVER_ERROR,
[
("x-rift-imposter", "true"),
("x-rift-script-error", "true"),
("content-type", "application/json"),
],
crate::response::error_body(
StatusCode::INTERNAL_SERVER_ERROR,
&format!(
"Script error: `component` is a wasm component; engine must be \"wasm\", not \"{engine}\""
),
),
));
}
trace!("Handling Rift script response (engine: {})", engine);
let script_request = ScriptRequest {
raw_body: Some(body_string.as_deref().unwrap_or_default().to_string()),
mode: body_mode.clone(),
method: method.clone(),
path: path.clone(),
headers: request_headers
.iter()
.filter(|(_, v)| !v.is_empty())
.map(|(k, v)| (k.to_ascii_lowercase(), v.clone()))
.collect(),
body: body_string
.as_deref()
.and_then(|s| serde_json::from_str(s).ok())
.unwrap_or(serde_json::Value::Null),
query: parse_query_string(&query_str),
path_params: stub_state
.stub
.route_pattern
.as_deref()
.map(|pattern| {
crate::extensions::template::extract_path_params(pattern, &path)
.into_iter()
.collect()
})
.unwrap_or_default(),
};
let timeout_ms = resolve_script_timeout_ms(&imposter.config);
let flow_store: Arc<dyn crate::extensions::flow_state::FlowStore> = Arc::new(
super::core::ScenarioStampingStore::new(Arc::clone(&imposter)),
);
let scenario_state = match &stub_state.stub.scenario_name {
Some(name) => {
let flow_id = scenario_flow_id.clone();
let name = name.clone();
match imposter
.run_flow_blocking(move |imp| imp.scenario_state(&flow_id, &name))
.await
{
Ok(s) => Some(s),
Err(e) => return Ok(backend_error_response(&e)),
}
}
None => None,
};
let ctx_extra = ScriptCtxExtras {
flow_id: Some(scenario_flow_id.clone()),
stub: ScriptStubContext {
scenario_name: stub_state.stub.scenario_name.clone(),
scenario_state,
stub_id: stub_state.stub.id.clone(),
},
port: imposter.config.port.unwrap_or(0),
raw_query: Some(query_str.clone()),
https: imposter.config.protocol.eq_ignore_ascii_case("https"),
};
let script_started = std::time::Instant::now();
let script_duration_ms: u64;
let mut wasm_http: Option<crate::scripting::WasmResponse> = None;
let (script_result, trace_header): (Result<FaultDecision, anyhow::Error>, _) =
if crate::scripting::ScriptEngineKind::is_wasm(&engine) {
let script_clock = match crate::imposter::clock::request_override() {
Some(ms) => crate::scripting::ScriptClock::Fixed(ms),
None => {
crate::scripting::ScriptClock::Imposter(Arc::clone(&imposter.clock))
}
};
let script = crate::scripting::WasmScript {
code,
export: script_config.export.as_deref(),
knobs: script_config.knobs.as_ref(),
limits: imposter.config.wasm_limits(),
clock: Some(&script_clock),
instance: script_config.instance.as_deref(),
instances: Some(&imposter.wasm_instances),
};
let rule_id = format!("rift_script_{stub_index}");
let timeout = Duration::from_millis(timeout_ms);
let flow_store: Arc<dyn crate::extensions::flow_state::FlowStore> =
Arc::new(crate::extensions::flow_state::CutOffStore::new(
flow_store,
imposter.in_flight.load_full(),
));
let (result, header) = if crate::util::rift_debug_env() {
let (result, mut entry) = crate::scripting::should_inject_wasm_traced(
script,
&rule_id,
&script_request,
flow_store,
timeout,
&ctx_extra,
)
.await;
entry.logs = crate::scripting::cap_trace_logs(entry.logs);
let header = serde_json::to_string(&[entry])
.inspect_err(|e| {
warn!("failed to serialize x-rift-script-trace: {}", e)
})
.ok();
(result, header)
} else {
let result = crate::scripting::should_inject_wasm(
script,
&rule_id,
&script_request,
flow_store,
timeout,
&ctx_extra,
)
.await;
(result, None)
};
script_duration_ms =
u64::try_from(script_started.elapsed().as_millis()).unwrap_or(u64::MAX);
let result = match result {
Ok(crate::scripting::WasmAnswer::Decision(decision)) => Ok(decision),
Ok(crate::scripting::WasmAnswer::Response(response)) => {
let status = response.status;
wasm_http = Some(response);
Ok(FaultDecision::Error {
status,
body: String::new(),
rule_id,
headers: std::collections::HashMap::new(),
})
}
Err(e) => Err(e),
};
(result, header)
} else if crate::util::rift_debug_env() {
let (result, mut entry) = should_inject_bounded_with_ctx_traced(
engine.clone(),
code.to_owned(),
format!("rift_script_{stub_index}"),
script_request,
flow_store,
Duration::from_millis(timeout_ms),
ctx_extra,
)
.await;
entry.logs = crate::scripting::cap_trace_logs(entry.logs);
let traced_ms = entry.duration_ms;
let header = serde_json::to_string(&[entry])
.inspect_err(|e| warn!("failed to serialize x-rift-script-trace: {}", e))
.ok();
script_duration_ms = traced_ms;
(result, header)
} else {
let result = should_inject_bounded_with_ctx(
engine.clone(),
code.to_owned(),
format!("rift_script_{stub_index}"),
script_request,
flow_store,
Duration::from_millis(timeout_ms),
ctx_extra,
)
.await;
script_duration_ms =
u64::try_from(script_started.elapsed().as_millis()).unwrap_or(u64::MAX);
(result, None)
};
{
let rule_id = imposter.bound_port().to_string();
let outcome = match &script_result {
Ok(FaultDecision::None) => "pass",
Ok(_) => "fault",
Err(_) => "error",
};
crate::extensions::metrics::record_script_execution(
&rule_id,
script_duration_ms as f64,
outcome,
);
match &script_result {
Ok(FaultDecision::Error { .. }) => {
crate::extensions::metrics::record_script_fault("error", &rule_id, None);
}
Ok(FaultDecision::Latency { duration_ms, .. }) => {
crate::extensions::metrics::record_script_fault(
"latency",
&rule_id,
Some(*duration_ms),
);
}
Ok(FaultDecision::Reset { .. }) => {
crate::extensions::metrics::record_script_fault("tcp", &rule_id, None);
}
Ok(FaultDecision::None) => {}
Err(e) => {
let error_type = if e
.downcast_ref::<crate::scripting::ScriptTimeoutError>()
.is_some()
{
"timeout"
} else {
"runtime"
};
crate::extensions::metrics::record_script_error(&rule_id, error_type);
}
}
}
if let Some(response) = wasm_http {
return Ok(wasm_http_response(response, &engine, trace_header));
}
match script_result {
Ok(FaultDecision::Error {
status,
body,
headers,
..
}) => {
let mut response = Response::builder().status(status);
for (k, v) in &headers {
response = response.header(k, v);
}
response = response.header("x-rift-imposter", "true");
response = response.header("x-rift-script", &engine);
if let Some(trace) = &trace_header {
response = response.header("x-rift-script-trace", trace.as_str());
}
return Ok(response
.body(Full::new(Bytes::from(body)))
.unwrap_or_else(|e| {
build_failure_response(
&e,
"script response build failed (bad script header?)",
)
}));
}
Ok(FaultDecision::Latency { duration_ms, .. }) => {
tokio::time::sleep(Duration::from_millis(duration_ms)).await;
let mut headers = vec![
("x-rift-imposter".to_string(), "true".to_string()),
("x-rift-script".to_string(), engine.clone()),
("x-rift-latency-ms".to_string(), duration_ms.to_string()),
];
if let Some(trace) = trace_header {
headers.push(("x-rift-script-trace".to_string(), trace));
}
return Ok(build_response_with_headers(
StatusCode::OK,
headers,
Bytes::new(),
));
}
Ok(FaultDecision::None) => {
let mut headers = vec![
("x-rift-imposter".to_string(), "true".to_string()),
("x-rift-script".to_string(), engine.clone()),
];
if let Some(trace) = trace_header {
headers.push(("x-rift-script-trace".to_string(), trace));
}
return Ok(build_response_with_headers(
StatusCode::OK,
headers,
Bytes::new(),
));
}
Ok(FaultDecision::Reset { .. }) => {
let mut headers = vec![
("x-rift-imposter".to_string(), "true".to_string()),
("x-rift-script".to_string(), engine.clone()),
("x-rift-fault".to_string(), "reset".to_string()),
];
if let Some(trace) = trace_header {
headers.push(("x-rift-script-trace".to_string(), trace));
}
let mut response =
build_response_with_headers(StatusCode::BAD_GATEWAY, headers, Bytes::new());
response
.extensions_mut()
.insert(super::fault_io::TcpFaultKind::Reset);
return Ok(response);
}
Err(e) => {
log_upstream_failure("Rift script execution failed", &e);
let timed_out = e
.downcast_ref::<crate::scripting::ScriptTimeoutError>()
.is_some();
let mut headers = vec![
("x-rift-imposter".to_string(), "true".to_string()),
("x-rift-script-error".to_string(), "true".to_string()),
];
if timed_out {
headers.push((SCRIPT_TIMEOUT_HEADER.to_string(), "true".to_string()));
}
if let Some(trace) = trace_header {
headers.push(("x-rift-script-trace".to_string(), trace));
}
headers.push(("content-type".to_string(), "application/json".to_string()));
let (status, body) = if timed_out {
(
StatusCode::GATEWAY_TIMEOUT,
crate::response::error_body_typed(
StatusCode::GATEWAY_TIMEOUT,
crate::response::ErrorKind::ScriptTimeout,
&format!("Script timeout: {e}"),
),
)
} else {
(
StatusCode::INTERNAL_SERVER_ERROR,
crate::response::error_body_typed(
StatusCode::INTERNAL_SERVER_ERROR,
crate::response::ErrorKind::ScriptError,
&format!("Script error: {e}"),
),
)
};
return Ok(build_response_with_headers(status, headers, body));
}
}
}
if let Some(StubResponse::Is {
is,
prepared: Some(prepared),
..
}) = response
&& imposter
.config
.default_response
.as_ref()
.is_none_or(|default| !is.needs_default(default))
{
return Ok(prepared
.serve_request(&method, &request_headers, || {
imposter.served_load_stamp(&stub_state, stub_index, &scenario_transitions)
})
.unwrap_or_else(|e| {
build_failure_response(&e, "stub response build failed (bad Last-Modified?)")
}));
}
if let Some((
mut status,
mut headers,
mut body,
behaviors,
rift_ext,
mut response_mode,
is_fault,
)) = response.and_then(execute_stub_response_with_rift)
{
let mut status_text = match response {
Some(StubResponse::Is { is, .. }) => is
.status_text
.as_deref()
.map(|text| Spliced::authored(text.to_string())),
_ => None,
};
if let (Some(is), Some(default)) = (
response.and_then(served_is),
imposter.config.default_response.as_ref(),
) && is.needs_default(default)
{
if is.omitted.status_code {
status_text = default
.status_text
.as_deref()
.map(|text| Spliced::supplied(text.to_string()));
}
complete_from_default(
is,
default,
&mut status,
&mut headers,
&mut body,
&mut response_mode,
);
}
if is_fault {
return Ok(handle_fault_response(&body).unwrap_or_else(|| {
ignored_fault_response(
imposter.config.default_response.as_ref(),
strict_behaviors_for(&imposter.config),
)
}));
}
if let Some(rift) = rift_ext
&& let Some(ref fault_config) = rift.fault
&& let Some(response) =
apply_rift_fault(fault_config, &mut status, &mut body, imposter.bound_port())
.await
{
return Ok(response);
}
let strict_behaviors = strict_behaviors_for(&imposter.config);
let templated = rift_ext.is_some_and(|r| r.templated);
let reflects = has_template_variables(&body)
|| headers
.values()
.flatten()
.any(|v| has_template_variables(v));
if templated || reflects || behaviors.is_some() {
let (mut spliced_body, mut spliced_headers) = if templated {
let request_data = RequestData::new(
method_str,
path_str,
query_opt,
&request_headers,
body_string.as_deref(),
)
.with_route_pattern(stub_state.stub.route_pattern.as_deref());
let template_debug = crate::util::rift_debug_env();
match render_templated_response(
&imposter,
request_data,
scenario_flow_id.clone(),
std::mem::take(&mut body),
std::mem::take(&mut headers),
template_debug,
stub_ref(&imposter, stub_index, &stub_state.stub),
)
.await
{
Ok(TemplateRender::Rendered { body, headers }) => (body, headers),
Ok(TemplateRender::Failed(e)) => {
warn!("Response template rendering failed: {e}");
return Ok(template_error_response(&e));
}
Err(e) => return Ok(backend_error_response(&e)),
}
} else {
(
Spliced::authored(std::mem::take(&mut body)),
authored_headers(std::mem::take(&mut headers)),
)
};
let need_body = has_template_variables(spliced_body.as_str());
let need_headers = spliced_headers
.values()
.flatten()
.any(|v| has_template_variables(v.as_str()));
if need_body || need_headers {
let request_data = RequestData::new(
method_str,
path_str,
query_opt,
&request_headers,
body_string.as_deref(),
)
.with_route_pattern(stub_state.stub.route_pattern.as_deref());
if need_body {
process_template_spliced(&mut spliced_body, &request_data, |value| value);
}
let stub_ref = stub_ref(&imposter, stub_index, &stub_state.stub);
for values in spliced_headers.values_mut() {
for v in values.iter_mut() {
if has_template_variables(v.as_str()) {
process_template_spliced(v, &request_data, |substituted| {
sanitize_header_value(&substituted, stub_ref)
});
}
}
}
}
if let Some(ref parsed_behaviors) = behaviors {
let run = BehaviorRun {
behaviors: parsed_behaviors,
method: &method,
uri: &uri,
request_headers: &request_headers,
request_body: body_string.as_deref(),
request_body_undefined: body_undefined,
client_addr: Some(client_addr),
script_scope: script_scope.clone(),
script_files: imposter.script_file_access(),
stub: stub_ref(&imposter, stub_index, &stub_state.stub),
csv_cache: csv_cache(),
body_guard: &imposter.body_guard,
script_timeout,
strict: strict_behaviors,
default_response: imposter.config.default_response.as_ref(),
};
let typed_body = match response {
Some(StubResponse::Is { is, .. }) => {
ServedParts::typed_body_of(is.body.as_ref(), &response_mode)
}
_ => None,
};
match run
.apply(ServedParts {
status,
status_text: status_text.take(),
headers: spliced_headers,
body: spliced_body,
typed_body,
})
.await
{
BehaviorOutcome::Applied { parts, .. } => {
status = parts.status;
status_text = parts.status_text;
spliced_headers = parts.headers;
spliced_body = parts.body;
}
BehaviorOutcome::StrictFailure(response) => return Ok(response),
}
}
body = spliced_body.into_text();
headers = plain_headers(spliced_headers);
}
let status = match resolve_status(
status,
status_text.as_ref().map(Spliced::as_str),
imposter.config.default_response.as_ref(),
) {
Ok(status) => status,
Err(value) => return Ok(invalid_status_response(&value)),
};
let conditional =
ConditionalSpec::from_config(rift_ext.and_then(|r| r.conditional.as_ref()))
.filter(|_| conditional::applies(&method, status.as_u16()));
let mut response = Response::builder().status(status);
for (k, values) in &headers {
if conditional.is_some() && conditional::is_validator(k) {
continue;
}
for v in values {
response = response.header(k, v);
}
}
response = response.header("x-rift-imposter", "true");
let body_bytes = match response_mode {
ResponseMode::Binary => match decode_binary_body(body, strict_behaviors) {
Ok(BinaryBody::Decoded(bytes)) => bytes,
Ok(BinaryBody::RawFallback(bytes)) => {
response = response.header("x-rift-binary-error", "true");
bytes
}
Err(strict_failure) => return Ok(*strict_failure),
},
ResponseMode::Text => Bytes::from(crate::extensions::apply_date_templates(&body)),
};
if let Some(ops) = rift_ext.map(|r| &r.state_ops).filter(|ops| !ops.is_empty()) {
let request_data = RequestData::new(
method_str,
path_str,
query_opt,
&request_headers,
body_string.as_deref(),
)
.with_route_pattern(stub_state.stub.route_pattern.as_deref());
let ops = ops.clone();
let flow_id = scenario_flow_id.clone();
let state_ops_debug = crate::util::rift_debug_env();
let outcome = imposter
.run_flow_blocking(move |imp| {
crate::extensions::execute_state_ops(
&ops,
&super::core::ScenarioStampingStore::new(imp),
&flow_id,
&request_data,
state_ops_debug,
)
.map_err(|e| anyhow::anyhow!(e))
})
.await;
if let Err(e) = outcome {
let message = e.to_string();
return Ok(if state_ops_debug && message.starts_with("stateOps:") {
state_ops_error_response(&message)
} else {
backend_error_response(&e)
});
}
}
if let Some(spec) = &conditional {
let etag = spec
.wants_etag()
.then(|| conditional::etag_for(&body_bytes));
let validators = spec.validators(
etag,
imposter.served_load_stamp(&stub_state, stub_index, &scenario_transitions),
);
if validators.not_modified(&request_headers) {
let kept = headers
.iter()
.filter(|(name, _)| conditional::kept_on_304(name))
.flat_map(|(name, values)| {
values.iter().map(move |v| (name.as_str(), v.as_str()))
});
return Ok(validators.not_modified_response(kept).unwrap_or_else(|e| {
build_failure_response(&e, "304 response build failed (bad stub header?)")
}));
}
for (name, value) in validators.headers() {
response = response.header(name, value);
}
}
return Ok(response.body(Full::new(body_bytes)).unwrap_or_else(|e| {
match invalid_header_name(headers.keys().map(String::as_str)) {
Some(name) => invalid_header_name_response(name),
None => {
build_failure_response(&e, "stub response build failed (bad stub header?)")
}
}
}));
}
}
if let Some(upstream) = &imposter.config.default_forward {
let proxy_config = ProxyResponse {
to: upstream.clone(),
mode: "proxyTransparent".to_string(),
..Default::default()
};
return match imposter
.handle_proxy_request(
&proxy_config,
UpstreamTarget::Base,
method_str,
&uri,
&request_headers,
proxy_body(wire_bytes.as_ref(), body_string.as_deref()),
None,
None,
client_addr,
)
.await
{
Ok(ProxyOutcome::StrictFailure(response)) => Ok(response),
Ok(ProxyOutcome::Served(ProxiedResponse {
status,
headers: response_headers,
body,
..
})) => {
let mut response = Response::builder().status(status);
for (k, v) in &response_headers {
if !crate::util::is_hop_by_hop_header(k) {
response = response.header(k, v);
}
}
response = response.header("x-rift-imposter", "true");
response = response.header("x-rift-default-forward", "true");
Ok(response
.body(Full::new(Bytes::from(body)))
.unwrap_or_else(|e| {
build_failure_response(
&e,
"defaultForward response build failed (bad upstream header?)",
)
}))
}
Err(e) => Ok(proxy_leg_error_response(
&e,
&format!("defaultForward proxy to {upstream} failed"),
"x-rift-default-forward-error",
"defaultForward upstream error",
)),
};
}
if let Some(ref default) = imposter.config.default_response {
return Ok(build_default_completed(
default,
strict_behaviors_for(&imposter.config),
Some("x-rift-default-response"),
));
}
Ok(build_response_with_headers(
StatusCode::OK,
[("x-rift-imposter", "true"), ("x-rift-no-match", "true")],
Bytes::new(),
))
}
#[allow(clippy::too_many_arguments)]
fn handle_debug_request(
imposter: &Arc<Imposter>,
method: &str,
path: &str,
query_str: &str,
headers_clone: &crate::util::OrderedMap<String, Vec<String>>,
body_string: &Option<String>,
client_addr: SocketAddr,
) -> Result<Response<Full<Bytes>>, Infallible> {
debug!("Debug mode enabled for request {} {}", method, path);
let debug_request = DebugRequest {
method: method.to_string(),
path: path.to_string(),
query: if query_str.is_empty() {
None
} else {
Some(query_str.to_string())
},
headers: headers_clone
.iter()
.filter(|(k, _)| !k.eq_ignore_ascii_case("x-rift-debug"))
.filter_map(|(k, v)| v.first().map(|first| (k.clone(), first.clone())))
.collect(),
body: body_string.clone(),
};
let debug_imposter = imposter.get_debug_imposter_info();
let request_from = client_addr.to_string();
let client_ip = client_addr.ip().to_string();
let query_opt = if query_str.is_empty() {
None
} else {
Some(query_str)
};
let matched = match imposter.find_matching_stub_with_client(
method,
path,
headers_clone,
query_opt,
body_string.as_deref(),
Some(&request_from),
Some(&client_ip),
) {
Ok(matched) => matched,
Err(e) => return Ok(matcher_error_response(&e)),
};
let match_result = if let Some((stub_state, stub_index)) = matched {
let response_preview = match imposter.get_response_preview(&stub_state) {
Ok(preview) => preview,
Err(e) => return Ok(backend_error_response(&e)),
};
DebugMatchResult {
matched: true,
stub_index: Some(stub_index),
stub_id: stub_state.stub.id.clone(),
predicates: Some(stub_state.stub.predicates.clone()),
response_preview: Some(response_preview),
all_stubs: None,
reason: None,
}
} else {
let all_stubs = imposter.get_all_stubs_info();
let reason = if all_stubs.is_empty() {
"No stubs configured for this imposter".to_string()
} else {
"No stub predicates matched the request".to_string()
};
DebugMatchResult {
matched: false,
stub_index: None,
stub_id: None,
predicates: None,
response_preview: None,
all_stubs: Some(all_stubs),
reason: Some(reason),
}
};
let debug_response = DebugResponse {
debug: true,
request: debug_request,
imposter: debug_imposter,
match_result,
};
let (status, json_body) = debug_serialize_or_500(&debug_response);
Ok(build_response_with_headers(
status,
[
("Content-Type", "application/json"),
("X-Rift-Debug-Response", "true"),
],
json_body,
))
}
fn debug_serialize_or_500<T: serde::Serialize>(payload: &T) -> (StatusCode, String) {
match serde_json::to_string_pretty(payload) {
Ok(body) => (StatusCode::OK, body),
Err(e) => {
tracing::error!(error = %e, "failed to serialize debug response");
(
StatusCode::INTERNAL_SERVER_ERROR,
crate::response::error_body(
StatusCode::INTERNAL_SERVER_ERROR,
"Failed to serialize debug response",
),
)
}
}
}
fn handle_fault_response(fault_type: &str) -> Option<Response<Full<Bytes>>> {
let kind = super::fault_io::TcpFaultKind::parse(fault_type)?;
let mut response = build_response_with_headers(
StatusCode::BAD_GATEWAY,
[("x-rift-fault", fault_type)],
Bytes::new(),
);
response.extensions_mut().insert(kind);
Some(response)
}
fn ignored_fault_response(default: Option<&IsResponse>, strict: bool) -> Response<Full<Bytes>> {
match default {
Some(default) => build_default_completed(default, strict, None),
None => {
build_response_with_headers(StatusCode::OK, [("x-rift-imposter", "true")], Bytes::new())
}
}
}
fn build_default_completed(
default: &IsResponse,
strict: bool,
marker: Option<&'static str>,
) -> Response<Full<Bytes>> {
let empty = IsResponse::empty();
let default = empty.completed_by(default);
let body_str = body_text(default.body.as_ref());
let mut binary_decode_failed = false;
let body_bytes = match default.mode {
ResponseMode::Binary => match decode_binary_body(body_str, strict) {
Ok(BinaryBody::Decoded(bytes)) => bytes,
Ok(BinaryBody::RawFallback(bytes)) => {
binary_decode_failed = true;
bytes
}
Err(strict_failure) => {
let mut strict_failure = *strict_failure;
if let Some(marker) = marker {
strict_failure
.headers_mut()
.insert(marker, hyper::header::HeaderValue::from_static("true"));
}
return strict_failure;
}
},
ResponseMode::Text => Bytes::from(crate::extensions::apply_date_templates(&body_str)),
};
let status = match resolve_status(default.status_code, default.status_text.as_deref(), None) {
Ok(status) => status,
Err(value) => {
let mut refused = invalid_status_response(&value);
if let Some(marker) = marker {
refused
.headers_mut()
.insert(marker, hyper::header::HeaderValue::from_static("true"));
}
return refused;
}
};
let mut response = Response::builder().status(status);
if binary_decode_failed {
response = response.header("x-rift-binary-error", "true");
}
for (k, values) in &default.headers {
for v in values {
response = response.header(k, v);
}
}
response = response.header("x-rift-imposter", "true");
if let Some(marker) = marker {
response = response.header(marker, "true");
}
response.body(Full::new(body_bytes)).unwrap_or_else(|e| {
build_failure_response(&e, "defaultResponse build failed (bad default header?)")
})
}
async fn apply_rift_fault(
fault_config: &super::types::RiftFaultConfig,
_status: &mut u16,
_body: &mut String,
port: u16,
) -> Option<Response<Full<Bytes>>> {
let rule_id = port.to_string();
let mut rng =
crate::imposter::rng::current().unwrap_or_else(crate::imposter::rng::RequestRng::unseeded);
let (apply_latency, latency_delay_ms) = {
if let Some(ref latency) = fault_config.latency {
if rng.random::<f64>() < latency.probability {
let delay_ms = if let Some(fixed_ms) = latency.ms {
fixed_ms
} else if latency.max_ms > latency.min_ms {
rng.random_range(latency.min_ms..=latency.max_ms)
} else {
latency.min_ms
};
(true, delay_ms)
} else {
(false, 0)
}
} else {
(false, 0)
}
};
let apply_error = {
if let Some(ref error) = fault_config.error {
rng.random::<f64>() < error.probability
} else {
false
}
};
let apply_tcp = {
fault_config
.tcp
.as_ref()
.is_some_and(|tcp| rng.random::<f64>() < tcp.probability())
};
if apply_latency && latency_delay_ms > 0 {
debug!("Applying _rift.fault latency: {}ms", latency_delay_ms);
crate::extensions::metrics::record_latency_injection(&rule_id, latency_delay_ms, "rift");
tokio::time::sleep(Duration::from_millis(latency_delay_ms)).await;
}
if apply_tcp && let Some(ref tcp_fault) = fault_config.tcp {
if let Some(kind) = super::fault_io::TcpFaultKind::parse(tcp_fault.kind()) {
debug!("Applying _rift.fault.tcp: {:?}", kind);
if apply_error {
debug!("_rift.fault.error preempted by tcp fault (connection reset)");
}
let mut response = build_response_with_headers(
StatusCode::BAD_GATEWAY,
[("x-rift-fault", tcp_fault.kind())],
Bytes::new(),
);
response.extensions_mut().insert(kind);
crate::extensions::metrics::record_fault_injection("tcp", &rule_id, "rift");
return Some(response);
}
warn!("Unknown TCP fault type: {}", tcp_fault.kind());
}
if apply_error && let Some(ref error) = fault_config.error {
debug!("Applying _rift.fault error: status {}", error.status);
let mut response = Response::builder().status(error.status);
for (k, v) in &error.headers {
response = response.header(k, v);
}
response = response.header("x-rift-imposter", "true");
response = response.header("x-rift-fault", "error");
crate::extensions::metrics::record_error_injection(&rule_id, error.status, "rift");
let error_body = error.body.clone().unwrap_or_default();
return Some(
response
.body(Full::new(Bytes::from(error_body)))
.unwrap_or_else(|e| {
build_failure_response(
&e,
"error-fault response build failed (bad fault header?)",
)
}),
);
}
None
}
#[cfg(all(test, feature = "javascript"))]
mod matcher_error_response_tests {
use super::{inject_timeout_response, matcher_error_response};
use hyper::StatusCode;
#[tokio::test]
async fn inject_timeout_response_is_504_with_code_and_markers() {
use http_body_util::BodyExt;
let resp = inject_timeout_response(
crate::response::ErrorKind::InjectionTimeout,
"inject timed out after 1ms",
);
assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
assert!(resp.headers().contains_key("x-rift-inject-error"));
assert!(
resp.headers().contains_key("x-rift-script-timeout"),
"the timeout marker distinguishes a deadline miss from a broken inject"
);
assert_eq!(
resp.headers()["content-type"],
"application/json",
"the inject-timeout 504 serves the JSON envelope, so it must declare it"
);
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
let body = String::from_utf8(bytes.to_vec()).expect("utf8");
assert!(
body.contains("\"code\":\"injection timeout\""),
"body must carry the timeout-specific code, got: {body}"
);
assert!(
body.contains("\"type\":\"injection timeout\""),
"body must carry the matching type slug, got: {body}"
);
}
#[tokio::test]
async fn predicate_inject_timeout_response_carries_matching_code_and_type() {
use http_body_util::BodyExt;
let resp = inject_timeout_response(
crate::response::ErrorKind::PredicateInjectionTimeout,
"predicate inject timed out after 1ms",
);
assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
let body = String::from_utf8(bytes.to_vec()).expect("utf8");
assert!(
body.contains("\"code\":\"predicate injection timeout\""),
"code must stay the 0.14.0 slug, got: {body}"
);
assert!(
body.contains("\"type\":\"predicate injection timeout\""),
"type must mirror it, got: {body}"
);
}
#[test]
fn predicate_inject_error_maps_to_500() {
let err: anyhow::Error = crate::scripting::PredicateInjectionError(
"bad predicate".to_string(),
Some("bad".to_string()),
)
.into();
let resp = matcher_error_response(&err);
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert!(
resp.headers().contains_key("x-rift-inject-error"),
"a predicate-inject error must carry the inject-error marker"
);
}
#[test]
fn other_matcher_error_maps_to_5xx() {
let err = anyhow::anyhow!("scenario-state backend read failed");
let resp = matcher_error_response(&err);
assert_eq!(
resp.status(),
StatusCode::INTERNAL_SERVER_ERROR,
"a non-predicate matcher error keeps the 5xx backend mapping, not a 400"
);
assert!(
!resp.headers().contains_key("x-rift-inject-error"),
"a generic backend error is not an inject error"
);
}
#[test]
fn predicate_inject_timeout_maps_to_504() {
let err: anyhow::Error = crate::scripting::ScriptTimeoutError {
hook: "predicate inject",
timeout_ms: 50,
}
.into();
let resp = matcher_error_response(&err);
assert_eq!(resp.status(), StatusCode::GATEWAY_TIMEOUT);
assert!(
resp.headers().contains_key("x-rift-script-timeout"),
"a matching timeout must carry the script-timeout marker"
);
assert!(
resp.headers().contains_key("x-rift-inject-error"),
"a predicate-inject timeout keeps the inject-error marker"
);
}
}
#[cfg(test)]
mod template_error_tests {
use super::template_error_response;
use http_body_util::BodyExt;
use hyper::StatusCode;
#[tokio::test]
async fn template_error_response_is_500_with_marker_and_json_envelope() {
let resp = template_error_response("template error in `{{ nope }}`: unknown token");
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert!(resp.headers().contains_key("x-rift-template-error"));
assert_eq!(
resp.headers()["content-type"],
"application/json",
"the template door serves the JSON envelope, so it must declare it"
);
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
let body = String::from_utf8(bytes.to_vec()).expect("utf8");
let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
assert_eq!(v["errors"][0]["code"], "500", "envelope code is the status");
assert!(
v["errors"][0]["message"]
.as_str()
.is_some_and(|m| m.contains("template rendering failed")),
"the 500 must name the render failure, got: {body}"
);
}
}
#[cfg(test)]
mod state_ops_error_tests {
use super::state_ops_error_response;
use http_body_util::BodyExt;
use hyper::StatusCode;
#[tokio::test]
async fn state_ops_error_response_is_500_with_marker_and_json_envelope() {
let resp = state_ops_error_response("stateOps: set \"a\" failed: template error");
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert!(resp.headers().contains_key("x-rift-state-ops-error"));
assert_eq!(
resp.headers()["content-type"],
"application/json",
"the stateOps error door serves the JSON envelope, so it must declare it"
);
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
let body = String::from_utf8(bytes.to_vec()).expect("utf8");
let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
assert_eq!(v["errors"][0]["code"], "500", "envelope code is the status");
assert!(
v["errors"][0]["message"]
.as_str()
.is_some_and(|m| m.contains("set \"a\"")),
"the 500 must name the failing op, got: {body}"
);
}
}
#[cfg(test)]
mod body_collect_tests {
use super::super::body_limits::{BodyGuard, BodyLimits};
use super::{BodyReadError, body_read_error_response, body_refused_response};
use bytes::Bytes;
use http_body_util::{BodyExt, Full};
use hyper::StatusCode;
use std::pin::Pin;
use std::task::{Context, Poll};
use tracing_test::traced_test;
struct FailingBody;
impl hyper::body::Body for FailingBody {
type Data = Bytes;
type Error = std::io::Error;
fn poll_frame(
self: Pin<&mut Self>,
_: &mut Context<'_>,
) -> Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
Poll::Ready(Some(Err(std::io::Error::new(
std::io::ErrorKind::ConnectionReset,
"connection reset by peer",
))))
}
}
fn guard() -> BodyGuard {
BodyGuard::new(BodyLimits::new(4096, None).expect("valid limits"))
}
#[tokio::test]
async fn oversize_is_flagged_too_large_not_read() {
let body = Full::new(Bytes::from(vec![b'x'; 4097]));
let err = guard().collect(body).await.expect_err("over limit");
assert!(
matches!(err, BodyReadError::TooLarge { limit: 4096 }),
"a size-cap hit must be TooLarge, not a Read"
);
}
#[tokio::test]
async fn transport_failure_is_flagged_read_with_cause_preserved() {
let err = guard()
.collect(FailingBody)
.await
.expect_err("transport failure");
match err {
BodyReadError::Read(e) => assert!(
e.to_string().contains("connection reset"),
"the underlying cause must survive to the sink, got: {e}"
),
other => panic!("a transport failure is not a limit refusal: {other:?}"),
}
}
#[tokio::test]
async fn the_limit_doors_are_413_and_503_and_close_the_connection() {
let too_large = body_refused_response(&BodyReadError::TooLarge { limit: 4096 });
assert_eq!(too_large.status(), StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(too_large.headers()["connection"], "close");
assert!(!too_large.headers().contains_key("retry-after"));
assert!(
too_large
.extensions()
.get::<super::super::fault_io::LingerOnClose>()
.is_some()
);
let exhausted = body_refused_response(&BodyReadError::BudgetExhausted);
assert_eq!(exhausted.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(exhausted.headers()["connection"], "close");
assert_eq!(exhausted.headers()["retry-after"], "1");
assert!(
exhausted
.extensions()
.get::<super::super::fault_io::LingerOnClose>()
.is_some()
);
let body = exhausted
.into_body()
.collect()
.await
.expect("body")
.to_bytes();
let json: serde_json::Value = serde_json::from_slice(&body).expect("json envelope");
assert_eq!(json["errors"][0]["code"], "503", "{json}");
assert_eq!(json["errors"][0]["type"], "unavailable", "{json}");
}
#[traced_test]
#[tokio::test]
async fn read_error_door_is_400_envelope_and_logs_the_cause() {
let e = std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "truncated chunked body");
let resp = body_read_error_response(&e);
assert_eq!(
resp.status(),
StatusCode::BAD_REQUEST,
"a read failure is the client's 400, not the 413 cap door nor a 500"
);
assert_eq!(resp.headers()["content-type"], "application/json");
assert!(resp.headers().contains_key("x-rift-imposter"));
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
let v: serde_json::Value = serde_json::from_slice(&bytes).expect("valid JSON envelope");
assert_eq!(v["errors"][0]["code"], "400", "envelope code is the status");
assert!(
v["errors"][0]["message"]
.as_str()
.is_some_and(|m| m.contains("Failed to read request body")),
"got: {v}"
);
assert!(
logs_contain("truncated chunked body"),
"the previously-silent read failure must now be logged with its cause"
);
}
}
#[cfg(test)]
mod plaintext_door_tests {
use super::{
SCRIPT_TIMEOUT_HEADER, build_failure_response, debug_matching_error_response,
debug_matching_timeout_response,
};
use http_body_util::BodyExt;
use hyper::StatusCode;
use tracing_test::traced_test;
async fn envelope(
resp: hyper::Response<http_body_util::Full<bytes::Bytes>>,
) -> serde_json::Value {
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
serde_json::from_slice(&bytes).expect("body must be the canonical JSON envelope")
}
#[tokio::test]
async fn debug_matching_error_door_is_500_envelope() {
let resp = debug_matching_error_response();
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(resp.headers()["content-type"], "application/json");
assert!(resp.headers().contains_key("x-rift-imposter"));
let v = envelope(resp).await;
assert_eq!(v["errors"][0]["code"], "500");
assert!(
v["errors"][0]["message"]
.as_str()
.is_some_and(|m| m.contains("Debug matching failed")),
"got: {v}"
);
}
#[tokio::test]
async fn debug_matching_timeout_door_is_504_with_timeout_marker() {
let resp = debug_matching_timeout_response();
assert_eq!(
resp.status(),
StatusCode::GATEWAY_TIMEOUT,
"a debug-matching deadline miss is a 504, like every other script timeout"
);
assert!(
resp.headers().contains_key(SCRIPT_TIMEOUT_HEADER),
"the timeout marker distinguishes a deadline miss from a permanent failure"
);
assert_eq!(resp.headers()["content-type"], "application/json");
assert!(resp.headers().contains_key("x-rift-imposter"));
let v = envelope(resp).await;
assert_eq!(
v["errors"][0]["code"], "504",
"envelope code tracks the status"
);
assert!(
v["errors"][0]["message"]
.as_str()
.is_some_and(|m| m.contains("Debug matching timed out")),
"got: {v}"
);
}
#[traced_test]
#[tokio::test]
async fn build_failure_response_is_500_envelope_and_logs_context() {
let e = hyper::Response::builder()
.header("x-bad", "line1\nline2")
.body(())
.expect_err("an invalid header value must be a build error");
let resp = build_failure_response(&e, "stub response build failed (bad stub header?)");
assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(resp.headers()["content-type"], "application/json");
assert!(resp.headers().contains_key("x-rift-imposter"));
let v = envelope(resp).await;
assert_eq!(v["errors"][0]["code"], "500");
assert!(
v["errors"][0]["message"]
.as_str()
.is_some_and(|m| m.contains("Response build error")),
"got: {v}"
);
assert!(
logs_contain("stub response build failed"),
"the failing door's context must still be logged"
);
}
}
#[cfg(test)]
mod debug_serialize_tests {
use super::debug_serialize_or_500;
use hyper::StatusCode;
use serde::{Serialize, Serializer};
struct Unserializable;
impl Serialize for Unserializable {
fn serialize<S: Serializer>(&self, _: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom("nope"))
}
}
#[test]
fn debug_serialize_failure_maps_to_500() {
let (status, body) = debug_serialize_or_500(&Unserializable);
assert_eq!(
status,
StatusCode::INTERNAL_SERVER_ERROR,
"a serialize failure must be a 500, not a 200 carrying an error string"
);
let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
assert_eq!(v["errors"][0]["code"], "500", "envelope code is the status");
}
#[test]
fn debug_serialize_success_keeps_200_and_the_payload() {
let (status, body) = debug_serialize_or_500(&serde_json::json!({"debug": true}));
assert_eq!(status, StatusCode::OK);
let parsed: serde_json::Value = serde_json::from_str(&body).expect("valid JSON");
assert_eq!(parsed["debug"], serde_json::json!(true));
}
}
#[cfg(test)]
mod fault_precedence_tests {
use super::super::fault_io::{TcpFaultKind, tcp_fault_carrier};
use super::super::types::{RiftErrorFault, RiftFaultConfig, RiftLatencyFault, RiftTcpFault};
use super::{
Bytes, Full, Response, StatusCode, apply_rift_fault, handle_fault_response,
ignored_fault_response,
};
use std::time::Instant;
#[test]
fn top_level_fault_carries_real_tcp_fault_extension() {
let reset = handle_fault_response("CONNECTION_RESET_BY_PEER").expect("a known fault");
assert_eq!(
reset.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::Reset),
"CONNECTION_RESET_BY_PEER must carry a real TCP-reset fault, not a plain 502"
);
let random = handle_fault_response("RANDOM_DATA_THEN_CLOSE").expect("a known fault");
assert_eq!(
random.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::RandomData),
"RANDOM_DATA_THEN_CLOSE must carry a real random-data-then-close fault"
);
let empty = handle_fault_response("EMPTY_RESPONSE").expect("a known fault");
assert_eq!(
empty.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::Empty)
);
let malformed = handle_fault_response("MALFORMED_RESPONSE_CHUNK").expect("a known fault");
assert_eq!(
malformed.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::MalformedChunk)
);
assert!(handle_fault_response("NOT_A_FAULT").is_none());
}
#[test]
fn carrier_seam_maps_a_top_level_fault_alias_to_one_canonical_name() {
let alias = handle_fault_response("garbage").expect("a known fault");
assert_eq!(
alias.headers().get("x-rift-fault").unwrap(),
"garbage",
"the header still echoes the raw input — that is the thing the seam replaces"
);
assert_eq!(tcp_fault_carrier(&alias), Some("RANDOM_DATA_THEN_CLOSE"));
let canonical = handle_fault_response("RANDOM_DATA_THEN_CLOSE").expect("a known fault");
assert_eq!(
tcp_fault_carrier(&canonical),
Some("RANDOM_DATA_THEN_CLOSE")
);
}
#[test]
fn carrier_seam_rejects_an_unknown_top_level_fault() {
let unknown = ignored_fault_response(None, false);
assert_eq!(unknown.status(), StatusCode::OK);
assert!(unknown.headers().get("x-rift-fault").is_none());
assert_eq!(unknown.headers().get("x-rift-imposter").unwrap(), "true");
assert_eq!(tcp_fault_carrier(&unknown), None);
}
#[test]
fn an_ignored_fault_is_completed_by_the_default_response() {
let default: super::IsResponse = serde_json::from_value(serde_json::json!({
"statusCode": 418, "headers": { "X-D": "1" }, "body": "dflt"
}))
.expect("is");
let ignored = ignored_fault_response(Some(&default), false);
assert_eq!(ignored.status().as_u16(), 418);
assert_eq!(ignored.headers().get("x-d").unwrap(), "1");
assert!(ignored.headers().get("x-rift-default-response").is_none());
assert!(ignored.headers().get("x-rift-fault").is_none());
assert_eq!(tcp_fault_carrier(&ignored), None);
}
#[tokio::test]
async fn carrier_seam_reports_a_rift_tcp_fault() {
let config = RiftFaultConfig {
latency: None,
error: None,
tcp: Some(RiftTcpFault::Kind("garbage".to_string())),
};
let response = apply(&config).await;
assert_eq!(tcp_fault_carrier(&response), Some("RANDOM_DATA_THEN_CLOSE"));
}
#[tokio::test]
async fn carrier_seam_ignores_an_error_fault() {
let config = RiftFaultConfig {
latency: None,
error: Some(error_fault(503)),
tcp: None,
};
let response = apply(&config).await;
assert_eq!(response.headers().get("x-rift-fault").unwrap(), "error");
assert_eq!(
tcp_fault_carrier(&response),
None,
"an error fault is a framed response the client receives, never a TCP carrier"
);
}
fn error_fault(status: u16) -> RiftErrorFault {
RiftErrorFault {
probability: 1.0,
status,
body: None,
headers: Default::default(),
}
}
fn latency_fault(ms: u64) -> RiftLatencyFault {
RiftLatencyFault {
probability: 1.0,
min_ms: 0,
max_ms: 0,
ms: Some(ms),
}
}
async fn apply(config: &RiftFaultConfig) -> Response<Full<Bytes>> {
let mut status = 200;
let mut body = String::new();
apply_rift_fault(config, &mut status, &mut body, 0)
.await
.expect("a fault response")
}
#[tokio::test]
async fn tcp_takes_precedence_over_error() {
let config = RiftFaultConfig {
latency: Some(latency_fault(0)),
error: Some(error_fault(503)),
tcp: Some(RiftTcpFault::Kind("CONNECTION_RESET_BY_PEER".to_string())),
};
let response = apply(&config).await;
assert_eq!(
response.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::Reset),
"tcp carrier must drive the connection reset"
);
assert_ne!(
response.status(),
503,
"error fault must not win over the tcp fault"
);
assert_eq!(
response.headers().get("x-rift-fault").unwrap(),
"CONNECTION_RESET_BY_PEER"
);
}
#[tokio::test]
async fn error_fault_applies_when_no_tcp() {
let config = RiftFaultConfig {
latency: Some(latency_fault(0)),
error: Some(error_fault(503)),
tcp: None,
};
let response = apply(&config).await;
assert_eq!(response.status(), 503);
assert_eq!(response.headers().get("x-rift-fault").unwrap(), "error");
assert!(response.extensions().get::<TcpFaultKind>().is_none());
}
#[tokio::test]
async fn unparseable_tcp_falls_through_to_error() {
let config = RiftFaultConfig {
latency: None,
error: Some(error_fault(503)),
tcp: Some(RiftTcpFault::Kind("NONSENSE".to_string())),
};
let response = apply(&config).await;
assert_eq!(response.status(), 503);
assert_eq!(response.headers().get("x-rift-fault").unwrap(), "error");
assert!(response.extensions().get::<TcpFaultKind>().is_none());
}
#[tokio::test]
async fn tcp_fault_alone_resets() {
let config = RiftFaultConfig {
latency: None,
error: None,
tcp: Some(RiftTcpFault::Kind("CONNECTION_RESET_BY_PEER".to_string())),
};
let response = apply(&config).await;
assert_eq!(
response.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::Reset)
);
}
#[tokio::test]
async fn latency_applies_before_tcp() {
let config = RiftFaultConfig {
latency: Some(latency_fault(60)),
error: Some(error_fault(503)),
tcp: Some(RiftTcpFault::Kind("CONNECTION_RESET_BY_PEER".to_string())),
};
let start = Instant::now();
let response = apply(&config).await;
assert!(
start.elapsed().as_millis() >= 50,
"latency must be applied before the tcp reset"
);
assert_eq!(
response.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::Reset)
);
}
#[tokio::test]
async fn tcp_object_probability_zero_never_resets() {
let config = RiftFaultConfig {
latency: None,
error: None,
tcp: Some(RiftTcpFault::Probabilistic {
probability: 0.0,
kind: "CONNECTION_RESET_BY_PEER".to_string(),
}),
};
let (mut status, mut body) = (200, String::new());
for _ in 0..200 {
let response = apply_rift_fault(&config, &mut status, &mut body, 0).await;
assert!(
response.is_none(),
"probability 0.0 tcp fault must never fire"
);
}
}
#[tokio::test]
async fn tcp_object_probability_zero_falls_through_to_error() {
let config = RiftFaultConfig {
latency: None,
error: Some(error_fault(503)),
tcp: Some(RiftTcpFault::Probabilistic {
probability: 0.0,
kind: "CONNECTION_RESET_BY_PEER".to_string(),
}),
};
let response = apply(&config).await;
assert_eq!(response.status(), 503);
assert!(response.extensions().get::<TcpFaultKind>().is_none());
}
#[tokio::test]
async fn tcp_object_probability_one_matches_bare_string() {
let config = RiftFaultConfig {
latency: None,
error: Some(error_fault(503)),
tcp: Some(RiftTcpFault::Probabilistic {
probability: 1.0,
kind: "CONNECTION_RESET_BY_PEER".to_string(),
}),
};
let response = apply(&config).await;
assert_eq!(
response.extensions().get::<TcpFaultKind>().copied(),
Some(TcpFaultKind::Reset)
);
assert_ne!(response.status(), 503);
assert_eq!(
response.headers().get("x-rift-fault").unwrap(),
"CONNECTION_RESET_BY_PEER"
);
}
#[tokio::test]
async fn tcp_object_fires_at_configured_probability() {
let config = RiftFaultConfig {
latency: None,
error: None,
tcp: Some(RiftTcpFault::Probabilistic {
probability: 0.3,
kind: "CONNECTION_RESET_BY_PEER".to_string(),
}),
};
let iterations = 4000;
let mut resets = 0;
let (mut status, mut body) = (200, String::new());
for _ in 0..iterations {
if apply_rift_fault(&config, &mut status, &mut body, 0)
.await
.and_then(|r| r.extensions().get::<TcpFaultKind>().copied())
.is_some()
{
resets += 1;
}
}
let observed = f64::from(resets) / f64::from(iterations);
assert!(
(observed - 0.3).abs() < 0.05,
"expected ~0.3 reset rate, got {observed}"
);
}
}
#[cfg(test)]
mod upstream_error_tests {
use super::{log_upstream_failure, proxy_leg_error_response, upstream_error_response};
use http_body_util::BodyExt;
use hyper::StatusCode;
use tracing_test::traced_test;
fn chained_error() -> anyhow::Error {
anyhow::anyhow!("failed to lookup address information: Name does not resolve")
.context("dns error")
.context("Failed to send proxy request to https://upstream.internal/")
}
async fn body_of(response: hyper::Response<http_body_util::Full<bytes::Bytes>>) -> String {
let bytes = response
.into_body()
.collect()
.await
.expect("collect")
.to_bytes();
String::from_utf8(bytes.to_vec()).expect("utf8")
}
fn refusal_error() -> anyhow::Error {
anyhow::Error::new(crate::extensions::decorate::BackendUnavailable {
feature: "proxyOnce",
detail: "owner is isolated from the cluster".to_owned(),
})
.context("proxyOnce claim refused; request not forwarded")
}
#[tokio::test]
async fn proxy_leg_refusal_answers_503_naming_the_backend() {
let response = proxy_leg_error_response(
&refusal_error(),
"Proxy request failed",
"x-rift-proxy-error",
"Proxy error",
);
assert_eq!(
response.status(),
StatusCode::SERVICE_UNAVAILABLE,
"a refused claim is a backend outage, not an upstream failure"
);
let body = body_of(response).await;
assert!(
body.contains(crate::response::ErrorKind::BackendUnavailable.slug()),
"the #318 envelope's type slug must survive: {body}"
);
assert!(
body.contains("proxyOnce"),
"the body must name which backend refused: {body}"
);
}
#[tokio::test]
async fn proxy_leg_upstream_failure_still_answers_502() {
let response = proxy_leg_error_response(
&chained_error(),
"Proxy request failed",
"x-rift-proxy-error",
"Proxy error",
);
assert_eq!(
response.status(),
StatusCode::BAD_GATEWAY,
"a genuine upstream failure keeps the 502 it has always had"
);
}
#[traced_test]
#[tokio::test]
async fn proxy_leg_refusal_is_not_logged_as_an_upstream_failure() {
let _ = proxy_leg_error_response(
&refusal_error(),
"Proxy request failed",
"x-rift-proxy-error",
"Proxy error",
);
assert!(
!logs_contain("Proxy request failed"),
"a refused claim never reached the upstream; blaming it misdirects the operator"
);
}
#[traced_test]
#[tokio::test]
async fn log_upstream_failure_names_the_whole_chain() {
log_upstream_failure("Inject function failed", &chained_error());
assert!(
logs_contain("Inject function failed"),
"context must survive"
);
assert!(
logs_contain("dns error"),
"the log must name the CAUSE — that is the whole point of #679"
);
assert!(
logs_contain("Name does not resolve"),
"the log must reach the ROOT cause, not stop one level down"
);
}
#[traced_test]
#[tokio::test]
async fn upstream_error_response_logs_the_whole_chain() {
let _ = upstream_error_response(
&chained_error(),
"Proxy request failed",
"x-rift-proxy-error",
"Proxy error",
);
assert!(logs_contain("Proxy request failed"));
assert!(
logs_contain("Name does not resolve"),
"the 502 path must log the root cause, not just build the body"
);
}
#[tokio::test]
async fn upstream_error_body_is_the_canonical_envelope() {
let response =
upstream_error_response(&chained_error(), "l", "x-rift-proxy-error", "Proxy error");
let body = body_of(response).await;
let v: serde_json::Value = serde_json::from_str(&body).expect("body must be valid JSON");
assert_eq!(v["errors"][0]["code"], "502", "envelope code is the status");
assert!(
v["errors"][0]["message"]
.as_str()
.expect("message is a string")
.contains("Proxy error: Failed to send proxy request"),
"the client keeps the prefix and the outermost context: {body}"
);
assert!(
v.get("error").is_none(),
"the legacy {{\"error\"}} shape must be gone"
);
}
#[tokio::test]
async fn upstream_error_body_withholds_the_cause_chain() {
let response =
upstream_error_response(&chained_error(), "l", "x-rift-proxy-error", "Proxy error");
let body = body_of(response).await;
assert!(
!body.contains("dns error"),
"cause chain must not cross to the client: {body}"
);
assert!(
!body.contains("Name does not resolve"),
"root cause must not cross to the client: {body}"
);
}
#[tokio::test]
async fn a_quote_in_the_upstream_error_still_yields_valid_json() {
let e = anyhow::anyhow!("root cause")
.context(r#"Failed to send proxy request to https://x/?q="a""#);
let response = upstream_error_response(&e, "l", "x-rift-proxy-error", "Proxy error");
let body = body_of(response).await;
let v: serde_json::Value = serde_json::from_str(&body)
.unwrap_or_else(|err| panic!("a quote must not break the body: {err}\nbody: {body}"));
assert!(
v["errors"][0]["message"]
.as_str()
.expect("message is a string")
.contains(r#"?q="a""#),
"the quoted text must survive escaping, not be mangled: {body}"
);
}
#[tokio::test]
async fn upstream_error_keeps_status_and_rift_markers() {
let response = upstream_error_response(
&chained_error(),
"l",
"x-rift-default-forward-error",
"defaultForward upstream error",
);
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
assert_eq!(response.headers()["x-rift-imposter"], "true");
assert_eq!(
response.headers()["x-rift-default-forward-error"],
"true",
"the per-door marker must survive"
);
assert_eq!(response.headers()["content-type"], "application/json");
}
}
#[cfg(test)]
mod templated_offload_tests {
use super::{TemplateRender, render_templated_response, stub_ref};
use crate::extensions::flow_state::{CasOutcome, FlowStore};
use crate::extensions::template::RequestData;
use crate::imposter::core::Imposter;
use crate::imposter::headers::StubRef;
use crate::imposter::types::ImposterConfig;
use parking_lot::Mutex;
use serde_json::{Value, json};
const FIXTURE_STUB: StubRef<'static> = StubRef {
port: 0,
index: 0,
id: None,
};
use std::sync::Arc;
use std::thread::ThreadId;
struct ThreadProbeStore {
inner: crate::backends::inmemory::InMemoryFlowStore,
blocking: bool,
get_thread: Arc<Mutex<Option<ThreadId>>>,
panic_on_get: bool,
}
impl ThreadProbeStore {
fn new(blocking: bool) -> Self {
Self {
inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
blocking,
get_thread: Arc::new(Mutex::new(None)),
panic_on_get: false,
}
}
fn panicking() -> Self {
Self {
panic_on_get: true,
..Self::new(true)
}
}
}
impl FlowStore for ThreadProbeStore {
fn is_blocking(&self) -> bool {
self.blocking
}
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
assert!(!self.panic_on_get, "induced blocking-store panic");
*self.get_thread.lock() = Some(std::thread::current().id());
self.inner.get(flow_id, key)
}
fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
self.inner.set(flow_id, key, value)
}
fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
self.inner.exists(flow_id, key)
}
fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
self.inner.delete(flow_id, key)
}
fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
self.inner.increment(flow_id, key)
}
fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
self.inner.set_ttl(flow_id, ttl_seconds)
}
fn compare_and_set(
&self,
flow_id: &str,
key: &str,
expected: Option<&Value>,
new: Value,
) -> anyhow::Result<CasOutcome> {
self.inner.compare_and_set(flow_id, key, expected, new)
}
}
fn imposter_with(store: Arc<ThreadProbeStore>, seed: Option<Value>) -> Arc<Imposter> {
let cfg: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": [] }))
.expect("valid imposter config");
if let Some(seed) = seed {
store.set("flow-1", "hits", seed).expect("seed");
}
let mut imp = Imposter::new(cfg).expect("test imposter");
imp.flow_store = store;
Arc::new(imp)
}
#[test]
fn stub_ref_reads_the_port_index_and_id_from_the_right_places() {
let imp = imposter_with(Arc::new(ThreadProbeStore::new(false)), None);
let stub: crate::imposter::types::Stub =
serde_json::from_value(json!({ "id": "checkout", "responses": [{ "is": {} }] }))
.expect("valid stub");
let r = stub_ref(&imp, 7, &stub);
assert_eq!(
r.port,
imp.bound_port(),
"port is the imposter's bound port"
);
assert_eq!(r.index, 7, "index is the matched stub's index");
assert_eq!(r.id, Some("checkout"), "id is the matched stub's id");
let anonymous: crate::imposter::types::Stub =
serde_json::from_value(json!({ "responses": [{ "is": {} }] })).expect("valid stub");
assert_eq!(stub_ref(&imp, 0, &anonymous).id, None);
}
fn request() -> RequestData {
RequestData::new("GET", "/x", None, &headers(&[]), None)
}
fn headers(pairs: &[(&str, &str)]) -> crate::imposter::Headers {
pairs
.iter()
.map(|(k, v)| ((*k).to_string(), vec![(*v).to_string()]))
.collect()
}
async fn render(
imp: &Arc<Imposter>,
body: &str,
hdrs: crate::imposter::Headers,
debug: bool,
) -> anyhow::Result<TemplateRender> {
render_templated_response(
imp,
request(),
"flow-1".to_string(),
body.to_string(),
hdrs,
debug,
FIXTURE_STUB,
)
.await
}
fn rendered(outcome: TemplateRender) -> (String, crate::imposter::Headers) {
match outcome {
TemplateRender::Rendered { body, headers } => {
(body.into_text(), crate::behaviors::plain_headers(headers))
}
TemplateRender::Failed(e) => panic!("expected a rendered response, got Failed({e})"),
}
}
struct OffloadCountingStore {
inner: crate::backends::inmemory::InMemoryFlowStore,
seam_entries: Arc<std::sync::atomic::AtomicUsize>,
}
impl OffloadCountingStore {
fn new() -> Self {
Self {
inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
seam_entries: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
}
}
}
impl FlowStore for OffloadCountingStore {
fn is_blocking(&self) -> bool {
self.seam_entries
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
true
}
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
self.inner.get(flow_id, key)
}
fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
self.inner.set(flow_id, key, value)
}
fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
self.inner.exists(flow_id, key)
}
fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
self.inner.delete(flow_id, key)
}
fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
self.inner.increment(flow_id, key)
}
fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
self.inner.set_ttl(flow_id, ttl_seconds)
}
fn compare_and_set(
&self,
flow_id: &str,
key: &str,
expected: Option<&Value>,
new: Value,
) -> anyhow::Result<crate::extensions::flow_state::CasOutcome> {
self.inner.compare_and_set(flow_id, key, expected, new)
}
}
fn counting_imposter(store: Arc<OffloadCountingStore>) -> Arc<Imposter> {
let cfg: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": [] }))
.expect("valid imposter config");
let mut imp = Imposter::new(cfg).expect("test imposter");
imp.flow_store = store;
Arc::new(imp)
}
#[tokio::test]
async fn state_free_template_never_reaches_the_seam() {
let store = Arc::new(OffloadCountingStore::new());
let seam = store.seam_entries.clone();
let imp = counting_imposter(store);
let (body, hdrs) = rendered(
render_templated_response(
&imp,
request(),
"flow-1".to_string(),
"path={{ request.path }}".to_string(),
headers(&[("x-when", "{{ now }}")]),
false,
FIXTURE_STUB,
)
.await
.expect("no transport failure"),
);
assert_eq!(body, "path=/x", "the render itself must still be correct");
assert!(!hdrs["x-when"][0].is_empty(), "{{ now }} still rendered");
assert_eq!(
seam.load(std::sync::atomic::Ordering::SeqCst),
0,
"a store-free template must not consult the offload seam at all"
);
}
#[tokio::test]
async fn a_state_read_in_a_header_alone_still_offloads() {
let store = Arc::new(OffloadCountingStore::new());
let seam = store.seam_entries.clone();
store.set("flow-1", "hits", json!(9)).expect("seed");
let imp = counting_imposter(store);
let (body, hdrs) = rendered(
render_templated_response(
&imp,
request(),
"flow-1".to_string(),
"no state here".to_string(),
headers(&[("x-hits", "{{ state.hits }}")]),
false,
FIXTURE_STUB,
)
.await
.expect("no transport failure"),
);
assert_eq!(body, "no state here");
assert_eq!(hdrs["x-hits"], vec!["9".to_string()]);
assert!(
seam.load(std::sync::atomic::Ordering::SeqCst) > 0,
"a state read in a header value must still take the offload"
);
}
#[tokio::test]
async fn a_state_read_in_the_body_still_offloads() {
let store = Arc::new(OffloadCountingStore::new());
let seam = store.seam_entries.clone();
store.set("flow-1", "hits", json!(4)).expect("seed");
let imp = counting_imposter(store);
let (body, _) = rendered(
render_templated_response(
&imp,
request(),
"flow-1".to_string(),
"n={{ state.hits }}".to_string(),
crate::imposter::Headers::new(),
false,
FIXTURE_STUB,
)
.await
.expect("no transport failure"),
);
assert_eq!(body, "n=4");
assert!(seam.load(std::sync::atomic::Ordering::SeqCst) > 0);
}
#[tokio::test]
async fn blocking_store_renders_state_off_the_caller_thread() {
let store = Arc::new(ThreadProbeStore::new(true));
let probe = store.get_thread.clone();
let imp = imposter_with(store, Some(json!(7)));
let caller = std::thread::current().id();
let (body, _) = rendered(
render(
&imp,
"hits={{ state.hits }}",
crate::imposter::Headers::new(),
false,
)
.await
.expect("no transport failure"),
);
assert_eq!(body, "hits=7");
assert_ne!(
probe.lock().expect("the store must have been read"),
caller,
"a blocking backend must not read the store on the tokio worker"
);
}
#[tokio::test]
async fn non_blocking_store_renders_state_inline_on_the_caller_thread() {
let store = Arc::new(ThreadProbeStore::new(false));
let probe = store.get_thread.clone();
let imp = imposter_with(store, Some(json!(7)));
let caller = std::thread::current().id();
let (body, _) = rendered(
render(
&imp,
"hits={{ state.hits }}",
crate::imposter::Headers::new(),
false,
)
.await
.expect("no transport failure"),
);
assert_eq!(body, "hits=7");
assert_eq!(
probe.lock().expect("the store must have been read"),
caller,
"the in-memory store must stay inline — no task hop"
);
}
#[tokio::test]
async fn header_values_are_rendered() {
let store = Arc::new(ThreadProbeStore::new(true));
let imp = imposter_with(store, Some(json!(42)));
let (body, hdrs) = rendered(
render(
&imp,
"static",
headers(&[("x-hits", "{{ state.hits }}")]),
false,
)
.await
.expect("no transport failure"),
);
assert_eq!(body, "static", "an untemplated body is served verbatim");
assert_eq!(hdrs["x-hits"], vec!["42".to_string()]);
}
#[tokio::test]
async fn rendered_header_values_are_control_char_sanitized() {
let store = Arc::new(ThreadProbeStore::new(true));
let imp = imposter_with(store, Some(json!("a\r\nx-evil: injected")));
let (_, hdrs) = rendered(
render(&imp, "", headers(&[("x-echo", "{{ state.hits }}")]), false)
.await
.expect("no transport failure"),
);
let value = &hdrs["x-echo"][0];
assert!(
!value.contains('\r') && !value.contains('\n'),
"control characters must be stripped, got: {value:?}"
);
}
#[tokio::test]
async fn a_bad_token_is_a_template_failure_not_a_transport_failure() {
let store = Arc::new(ThreadProbeStore::new(true));
let imp = imposter_with(store, None);
let outcome = render(
&imp,
"{{ nope.nothing }}",
crate::imposter::Headers::new(),
true,
)
.await
.expect("a bad token must not surface as a transport failure");
assert!(
matches!(outcome, TemplateRender::Failed(_)),
"expected TemplateRender::Failed for an unknown token"
);
}
#[tokio::test]
async fn a_bad_token_in_a_header_is_reported() {
let store = Arc::new(ThreadProbeStore::new(true));
let imp = imposter_with(store, None);
let outcome = render(
&imp,
"fine",
headers(&[("x-bad", "{{ nope.nothing }}")]),
true,
)
.await
.expect("a bad token must not surface as a transport failure");
assert!(
matches!(outcome, TemplateRender::Failed(_)),
"a bad token in a header value must fail the render"
);
}
#[tokio::test]
async fn a_panicking_blocking_store_surfaces_as_a_transport_failure() {
let imp = imposter_with(Arc::new(ThreadProbeStore::panicking()), None);
let err = render(
&imp,
"{{ state.hits }}",
crate::imposter::Headers::new(),
false,
)
.await
.expect_err("a panicked blocking task must surface as Err");
assert!(
err.to_string().contains("flow-store task panicked"),
"got: {err}"
);
}
#[tokio::test]
async fn output_is_identical_on_both_paths() {
let hdrs = headers(&[("x-hits", "{{ state.hits }}"), ("x-static", "plain")]);
let blocking = imposter_with(Arc::new(ThreadProbeStore::new(true)), Some(json!(5)));
let inline = imposter_with(Arc::new(ThreadProbeStore::new(false)), Some(json!(5)));
let a = rendered(
render(&blocking, "n={{ state.hits }}", hdrs.clone(), false)
.await
.expect("no transport failure"),
);
let b = rendered(
render(&inline, "n={{ state.hits }}", hdrs, false)
.await
.expect("no transport failure"),
);
assert_eq!(a.0, "n=5");
assert_eq!(a, b, "the blocking and inline paths must agree exactly");
}
#[tokio::test]
async fn empty_body_and_no_headers_render_cleanly() {
let imp = imposter_with(Arc::new(ThreadProbeStore::new(true)), None);
let (body, hdrs) = rendered(
render(&imp, "", crate::imposter::Headers::new(), false)
.await
.expect("no transport failure"),
);
assert_eq!(body, "");
assert!(hdrs.is_empty());
}
#[tokio::test]
async fn previous_value_renders_empty_outside_state_ops() {
let imp = imposter_with(Arc::new(ThreadProbeStore::new(true)), None);
let (body, _) = rendered(
render(
&imp,
"[{{ previousValue }}]",
crate::imposter::Headers::new(),
false,
)
.await
.expect("no transport failure"),
);
assert_eq!(body, "[]");
}
}
#[cfg(test)]
mod fsm_offload_tests {
use crate::extensions::flow_state::{CasOutcome, FlowStore};
use crate::imposter::core::Imposter;
use crate::imposter::handler::handle_imposter_request;
use crate::imposter::types::ImposterConfig;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper_util::rt::TokioIo;
use serde_json::{Value, json};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
struct SeamCountingStore {
inner: crate::backends::inmemory::InMemoryFlowStore,
seam_entries: Arc<AtomicUsize>,
writes: Arc<AtomicUsize>,
}
impl SeamCountingStore {
fn new() -> Self {
Self {
inner: crate::backends::inmemory::InMemoryFlowStore::new(300),
seam_entries: Arc::new(AtomicUsize::new(0)),
writes: Arc::new(AtomicUsize::new(0)),
}
}
}
impl FlowStore for SeamCountingStore {
fn is_blocking(&self) -> bool {
self.seam_entries.fetch_add(1, Ordering::SeqCst);
true
}
fn get(&self, flow_id: &str, key: &str) -> anyhow::Result<Option<Value>> {
self.inner.get(flow_id, key)
}
fn set(&self, flow_id: &str, key: &str, value: Value) -> anyhow::Result<()> {
self.writes.fetch_add(1, Ordering::SeqCst);
self.inner.set(flow_id, key, value)
}
fn exists(&self, flow_id: &str, key: &str) -> anyhow::Result<bool> {
self.inner.exists(flow_id, key)
}
fn delete(&self, flow_id: &str, key: &str) -> anyhow::Result<()> {
self.inner.delete(flow_id, key)
}
fn increment(&self, flow_id: &str, key: &str) -> anyhow::Result<i64> {
self.inner.increment(flow_id, key)
}
fn set_ttl(&self, flow_id: &str, ttl_seconds: i64) -> anyhow::Result<()> {
self.inner.set_ttl(flow_id, ttl_seconds)
}
fn compare_and_set(
&self,
flow_id: &str,
key: &str,
expected: Option<&Value>,
new: Value,
) -> anyhow::Result<CasOutcome> {
self.writes.fetch_add(1, Ordering::SeqCst);
self.inner.compare_and_set(flow_id, key, expected, new)
}
}
async fn serve_once(stubs: Value, path: &str) -> (usize, usize, u16) {
let cfg: ImposterConfig =
serde_json::from_value(json!({ "port": 0, "protocol": "http", "stubs": stubs }))
.expect("valid imposter config");
let store = Arc::new(SeamCountingStore::new());
let seam = store.seam_entries.clone();
let writes = store.writes.clone();
let mut imp = Imposter::new(cfg).expect("test imposter");
imp.flow_store = store;
let imposter = Arc::new(imp);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let addr = listener.local_addr().expect("local addr");
let imp = imposter.clone();
tokio::spawn(async move {
let Ok((stream, peer)) = listener.accept().await else {
return;
};
let service = service_fn(move |req| {
let imp = imp.clone();
async move { handle_imposter_request(req, imp, peer).await }
});
let _ = http1::Builder::new()
.serve_connection(TokioIo::new(stream), service)
.await;
});
let resp = reqwest::get(format!("http://{addr}{path}"))
.await
.expect("request");
let status = resp.status().as_u16();
(
seam.load(Ordering::SeqCst),
writes.load(Ordering::SeqCst),
status,
)
}
#[tokio::test]
async fn a_stub_with_no_transition_never_reaches_the_seam() {
let (seam, writes, status) = serve_once(
json!([{
"predicates": [{ "equals": { "path": "/plain" } }],
"responses": [{ "is": { "statusCode": 200, "body": "ok" } }]
}]),
"/plain",
)
.await;
assert_eq!(status, 200, "the request must still be served normally");
assert_eq!(writes, 0, "a stub with no transition writes nothing");
assert_eq!(
seam, 0,
"a stub with no newScenarioState must not pay a spawn_blocking hop to run a no-op"
);
}
#[tokio::test]
async fn a_stub_with_a_transition_still_offloads_and_still_writes() {
let (seam, writes, status) = serve_once(
json!([{
"scenarioName": "order",
"newScenarioState": "Placed",
"predicates": [{ "equals": { "path": "/place" } }],
"responses": [{ "is": { "statusCode": 200, "body": "ok" } }]
}]),
"/place",
)
.await;
assert_eq!(status, 200);
assert!(
seam > 0,
"a stub with newScenarioState must still take the offload"
);
assert!(
writes > 0,
"the transition must still be applied — skipping the offload must not mean \
skipping the write"
);
}
}
#[cfg(test)]
mod decode_binary_body_tests {
use super::*;
#[test]
fn a_valid_body_decodes() {
let Ok(BinaryBody::Decoded(bytes)) = decode_binary_body("aGVsbG8=".to_string(), false)
else {
panic!("valid base64 must decode");
};
assert_eq!(bytes.as_ref(), b"hello");
}
#[test]
fn a_bad_body_is_a_raw_fallback_when_lenient() {
let Ok(BinaryBody::RawFallback(bytes)) =
decode_binary_body("not!valid!base64!".to_string(), false)
else {
panic!("an undecodable body must be a RawFallback in lenient mode");
};
assert_eq!(bytes.as_ref(), b"not!valid!base64!");
}
#[test]
fn a_bad_body_is_a_ready_made_500_when_strict() {
let Err(response) = decode_binary_body("not!valid!base64!".to_string(), true) else {
panic!("strict mode must refuse an undecodable body");
};
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(
response
.headers()
.get("x-rift-binary-error")
.and_then(|v| v.to_str().ok()),
Some("true"),
"the strict 500 still carries the #323 signal header"
);
}
#[test]
fn a_body_with_line_breaks_decodes_as_mountebank_decodes_it() {
let png = "iVBORw0KGgoAAAANSUhEUgAAAGQAAAAyBAMAAABYG2ONAAAAFVBMVEUAAAD///9/f39fX1+fn58f\nHx8/Pz8rYiDqAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAo0lEQVRIie2Qyw7CIBBFb2DwO5q+1o0L\n1w0NrrHRPQnV//8EAUl0ga1ujIs5CZAz4YYZAIZhmN/QQOkjzq3LLuv6xUrQHmTJGphcEGE9rUQ3\nY4bqqrDjAlgQoJK9Z8YBmFy8Gp8DeSeTfRSBCf2I6/JN5ORiRfrNiIfqh9S9SVPL27A1C0G4EX2e\nJR7J1iI7rbG0Vf4x0UwPW0Uh3i0bwzD/yR11mBj1DIKiVwAAAABJRU5ErkJggg==\n";
let Ok(BinaryBody::Decoded(bytes)) = decode_binary_body(png.to_string(), true) else {
panic!("a base64 body wrapped with line breaks must decode");
};
assert_eq!(bytes.len(), 274);
assert_eq!(&bytes[..4], b"\x89PNG");
}
#[test]
fn a_body_still_bad_after_the_filter_falls_back_with_its_original_text() {
let Ok(BinaryBody::RawFallback(bytes)) =
decode_binary_body("aGVsbG8\n!".to_string(), false)
else {
panic!("`aGVsbG8` (no padding) must not decode");
};
assert_eq!(bytes.as_ref(), b"aGVsbG8\n!");
}
#[test]
fn a_valid_body_decodes_under_strict_too() {
assert!(matches!(
decode_binary_body("aGVsbG8=".to_string(), true),
Ok(BinaryBody::Decoded(_))
));
}
}
#[cfg(test)]
mod served_answer_tests {
use super::super::fault_io::TcpFaultKind;
use super::*;
fn plain() -> Response<Full<Bytes>> {
build_response_with_headers(StatusCode::OK, [("x-a", "b")], Bytes::new())
}
#[test]
fn an_ordinary_response_is_the_served_answer() {
assert!(is_served_answer(&plain()));
}
#[test]
fn a_debug_report_is_not_the_served_answer() {
let mut report = plain();
report.extensions_mut().insert(DebugReport);
assert!(!is_served_answer(&report));
}
#[test]
fn a_tcp_fault_carrier_is_not_the_served_answer() {
let mut carrier = plain();
carrier.extensions_mut().insert(TcpFaultKind::Reset);
assert!(!is_served_answer(&carrier));
}
}
fn rekey_request_stream(
imposter: &Imposter,
method: &str,
path: &str,
headers: &crate::util::OrderedMap<String, Vec<String>>,
query_str: &str,
body: Option<&str>,
) {
use crate::imposter::rng::{ImposterRng, KeySource, Seed, key_digest, keyed_state};
let Some(engine) = imposter
.config
.rift
.as_ref()
.and_then(|r| r.script_engine.as_ref())
else {
return;
};
let (Some(seed), Some(key)) = (
engine.seed.as_ref().and_then(Seed::value),
engine.rng_key.as_ref(),
) else {
return;
};
let Ok(parts) = key.parts() else {
return;
};
let Some(handle) = crate::imposter::rng::current() else {
return;
};
let query = parse_query_string(query_str);
let header = |name: &str| {
headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.and_then(|(_, v)| v.first().cloned())
};
let query_value = |name: &str| query.get(name).and_then(|v| v.first().cloned());
let source = KeySource {
method,
path,
header: &header,
query: &query_value,
body,
};
let Some(digest) = key_digest(&parts, &source) else {
return;
};
let occurrence = imposter.rng.load().next_occurrence(digest);
handle.rekey(ImposterRng::new(Some(keyed_state(
seed, digest, occurrence,
))));
}
fn wasm_http_response(
answer: crate::scripting::WasmResponse,
engine: &str,
trace: Option<String>,
) -> Response<Full<Bytes>> {
use hyper::header::{CONNECTION, CONTENT_LENGTH, TRANSFER_ENCODING};
let mut builder = Response::builder().status(answer.status);
for (name, value) in &answer.headers {
if name == CONNECTION
|| name == CONTENT_LENGTH
|| name == TRANSFER_ENCODING
|| name == "keep-alive"
{
continue;
}
builder = builder.header(name, value);
}
builder = builder
.header("x-rift-imposter", "true")
.header("x-rift-script", engine);
if let Some(trace) = &trace {
builder = builder.header("x-rift-script-trace", trace.as_str());
}
builder
.body(Full::new(answer.body))
.unwrap_or_else(|e| build_failure_response(&e, "wasm http response build failed"))
}