pub mod builder;
use crate::imposter::ImposterError;
use crate::response::builder::ErrorResponseBuilder;
use bytes::Bytes;
use http_body_util::Full;
use hyper::{Response, StatusCode};
use serde::Serialize;
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
pub errors: Vec<ErrorDetail>,
}
#[derive(Debug, Serialize)]
pub struct ErrorDetail {
pub code: String,
#[serde(rename = "type")]
pub error_type: String,
pub message: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
BadData,
InvalidInjection,
ResourceConflict,
InsufficientAccess,
NoSuchResource,
Unauthorized,
InvalidPredicateInjection,
InvalidWasm,
InjectionTimeout,
PredicateInjectionTimeout,
BackendUnavailable,
ScriptError,
ScriptTimeout,
BehaviorError,
ImposterDisabled,
RequestTooLarge,
UpstreamFailure,
Unavailable,
Timeout,
InternalError,
ClientError,
ServerError,
}
impl ErrorKind {
pub const ALL: [ErrorKind; 22] = [
ErrorKind::BadData,
ErrorKind::InvalidInjection,
ErrorKind::ResourceConflict,
ErrorKind::InsufficientAccess,
ErrorKind::NoSuchResource,
ErrorKind::Unauthorized,
ErrorKind::InvalidPredicateInjection,
ErrorKind::InvalidWasm,
ErrorKind::InjectionTimeout,
ErrorKind::PredicateInjectionTimeout,
ErrorKind::BackendUnavailable,
ErrorKind::ScriptError,
ErrorKind::ScriptTimeout,
ErrorKind::BehaviorError,
ErrorKind::ImposterDisabled,
ErrorKind::RequestTooLarge,
ErrorKind::UpstreamFailure,
ErrorKind::Unavailable,
ErrorKind::Timeout,
ErrorKind::InternalError,
ErrorKind::ClientError,
ErrorKind::ServerError,
];
#[must_use]
pub fn slug(self) -> &'static str {
match self {
ErrorKind::BadData => "bad data",
ErrorKind::InvalidInjection => "invalid injection",
ErrorKind::ResourceConflict => "resource conflict",
ErrorKind::InsufficientAccess => "insufficient access",
ErrorKind::NoSuchResource => "no such resource",
ErrorKind::Unauthorized => "unauthorized",
ErrorKind::InvalidPredicateInjection => "invalid predicate injection",
ErrorKind::InvalidWasm => "invalid wasm",
ErrorKind::InjectionTimeout => "injection timeout",
ErrorKind::PredicateInjectionTimeout => "predicate injection timeout",
ErrorKind::BackendUnavailable => "backend unavailable",
ErrorKind::ScriptError => "script error",
ErrorKind::ScriptTimeout => "script timeout",
ErrorKind::BehaviorError => "behavior error",
ErrorKind::ImposterDisabled => "imposter disabled",
ErrorKind::RequestTooLarge => "request too large",
ErrorKind::UpstreamFailure => "upstream failure",
ErrorKind::Unavailable => "unavailable",
ErrorKind::Timeout => "timeout",
ErrorKind::InternalError => "internal error",
ErrorKind::ClientError => "client error",
ErrorKind::ServerError => "server error",
}
}
#[must_use]
pub fn for_status(status: StatusCode) -> Self {
match status {
StatusCode::BAD_REQUEST | StatusCode::UNPROCESSABLE_ENTITY => ErrorKind::BadData,
StatusCode::UNAUTHORIZED => ErrorKind::Unauthorized,
StatusCode::FORBIDDEN => ErrorKind::InsufficientAccess,
StatusCode::NOT_FOUND => ErrorKind::NoSuchResource,
StatusCode::CONFLICT => ErrorKind::ResourceConflict,
StatusCode::PAYLOAD_TOO_LARGE => ErrorKind::RequestTooLarge,
StatusCode::INTERNAL_SERVER_ERROR => ErrorKind::InternalError,
StatusCode::BAD_GATEWAY => ErrorKind::UpstreamFailure,
StatusCode::SERVICE_UNAVAILABLE => ErrorKind::Unavailable,
StatusCode::GATEWAY_TIMEOUT => ErrorKind::Timeout,
s if s.is_client_error() => ErrorKind::ClientError,
_ => ErrorKind::ServerError,
}
}
}
pub(crate) fn error_body(status: StatusCode, message: &str) -> String {
error_body_typed(status, ErrorKind::for_status(status), message)
}
pub(crate) fn error_body_typed(status: StatusCode, kind: ErrorKind, message: &str) -> String {
let error = ErrorResponse {
errors: vec![ErrorDetail {
code: status.as_str().to_string(),
error_type: kind.slug().to_string(),
message: message.to_string(),
}],
};
serde_json::to_string_pretty(&error).unwrap_or_else(|_| "{}".to_string())
}
#[must_use]
pub fn generator_injection_error_body(source: &str, data: Option<&str>) -> String {
let mut error = serde_json::json!({
"code": ErrorKind::InvalidInjection.slug(),
"type": ErrorKind::InvalidInjection.slug(),
"message": "invalid predicateGenerator injection",
"source": source,
});
if let Some(data) = data {
error["data"] = data.into();
}
serde_json::json!({ "errors": [error] }).to_string()
}
pub fn error_response(status: StatusCode, message: &str) -> Response<Full<Bytes>> {
error_response_typed(status, ErrorKind::for_status(status), message)
}
pub fn error_response_typed(
status: StatusCode,
kind: ErrorKind,
message: &str,
) -> Response<Full<Bytes>> {
ErrorResponseBuilder::new(status)
.body(error_body_typed(status, kind, message))
.header("Content-Type", "application/json")
.build_full()
}
impl From<ImposterError> for Response<Full<Bytes>> {
fn from(err: ImposterError) -> Self {
match err {
ImposterError::PortInUse(p) => error_response(
StatusCode::BAD_REQUEST,
&format!("Port {p} is already in use"),
),
ImposterError::NotFound(p) => error_response(
StatusCode::NOT_FOUND,
&format!("Imposter not found on port {p}"),
),
ref bind @ ImposterError::BindError(p, ref e) if bind.is_caller_address_error() => {
tracing::warn!(port = p, error = %format_args!("{e:#}"), "imposter address cannot be bound");
let in_use = e
.downcast_ref::<std::io::Error>()
.is_some_and(|io| io.kind() == std::io::ErrorKind::AddrInUse);
let message = if in_use {
format!("Port {p} is already in use: {e:#}")
} else {
format!("Failed to bind port {p}: {e:#}")
};
error_response(StatusCode::BAD_REQUEST, &message)
}
ImposterError::BindError(p, e) => {
tracing::error!(port = p, error = %format_args!("{e:#}"), "failed to bind imposter port");
error_response(
StatusCode::INTERNAL_SERVER_ERROR,
&format!("Failed to bind port {p}: {e:#}"),
)
}
ImposterError::InvalidProtocol(p) => {
error_response(StatusCode::BAD_REQUEST, &format!("Invalid protocol: {p}"))
}
ImposterError::InvalidConfig(msg) => error_response(StatusCode::BAD_REQUEST, &msg),
ImposterError::StubIndexOutOfBounds(i) => {
error_response(StatusCode::NOT_FOUND, &format!("Stub index {i} not found"))
}
ImposterError::StubNotFound(id) => {
error_response(StatusCode::NOT_FOUND, &format!("No stub with id '{id}'"))
}
ImposterError::StubIdConflict(id) => error_response(
StatusCode::CONFLICT,
&format!("A stub with id '{id}' already exists"),
),
ImposterError::PersistError(msg) => {
tracing::error!(error = %format_args!("{msg:#}"), "failed to persist imposter state");
error_response(
StatusCode::SERVICE_UNAVAILABLE,
&format!("Persistence error: {msg:#}"),
)
}
ImposterError::Tls(msg) => error_response(
StatusCode::BAD_REQUEST,
&format!("TLS configuration error: {msg}"),
),
ImposterError::FlowStoreConfig(msg) => error_response(
StatusCode::BAD_REQUEST,
&format!("Flow store configuration error: {msg}"),
),
ImposterError::Backend(e) => crate::extensions::decorate::backend_error_response(&e),
ImposterError::ExplicitPortRequired => error_response(
StatusCode::BAD_REQUEST,
&ImposterError::ExplicitPortRequired.to_string(),
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn body_of(status: StatusCode) -> serde_json::Value {
serde_json::from_str(&error_body(status, "msg")).expect("valid json")
}
#[test]
fn explicit_port_required_maps_to_400() {
let response: Response<Full<Bytes>> = ImposterError::ExplicitPortRequired.into();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
async fn bind_response(source: anyhow::Error) -> (StatusCode, serde_json::Value) {
let response: Response<Full<Bytes>> = ImposterError::BindError(4545, source).into();
let status = response.status();
let body = http_body_util::BodyExt::collect(response)
.await
.expect("collect")
.to_bytes();
(status, serde_json::from_slice(&body).expect("json"))
}
fn io_kind(kind: std::io::ErrorKind) -> anyhow::Error {
anyhow::Error::new(std::io::Error::from(kind))
}
#[tokio::test]
async fn a_taken_address_is_a_400_bad_data_naming_already_in_use() {
let (status, body) = bind_response(io_kind(std::io::ErrorKind::AddrInUse)).await;
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body["errors"][0]["type"], "bad data");
let message = body["errors"][0]["message"].as_str().expect("message");
assert!(message.contains("already in use"), "{message}");
assert!(message.contains("4545"), "{message}");
}
#[tokio::test]
async fn a_non_local_or_forbidden_address_is_a_400() {
for kind in [
std::io::ErrorKind::AddrNotAvailable,
std::io::ErrorKind::PermissionDenied,
] {
let (status, body) = bind_response(io_kind(kind)).await;
assert_eq!(status, StatusCode::BAD_REQUEST, "{kind:?}");
assert_eq!(body["errors"][0]["type"], "bad data", "{kind:?}");
let message = body["errors"][0]["message"].as_str().expect("message");
assert!(
message.starts_with("Failed to bind port 4545: "),
"{message}"
);
}
}
#[tokio::test]
async fn an_engine_side_bind_fault_stays_a_500() {
for source in [
anyhow::anyhow!("no socket address"),
io_kind(std::io::ErrorKind::OutOfMemory),
] {
let (status, body) = bind_response(source).await;
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(body["errors"][0]["type"], "internal error");
}
}
#[test]
fn status_to_default_slug_table_is_pinned() {
let expected = [
(StatusCode::BAD_REQUEST, "bad data"),
(StatusCode::UNPROCESSABLE_ENTITY, "bad data"),
(StatusCode::UNAUTHORIZED, "unauthorized"),
(StatusCode::FORBIDDEN, "insufficient access"),
(StatusCode::NOT_FOUND, "no such resource"),
(StatusCode::CONFLICT, "resource conflict"),
(StatusCode::PAYLOAD_TOO_LARGE, "request too large"),
(StatusCode::INTERNAL_SERVER_ERROR, "internal error"),
(StatusCode::BAD_GATEWAY, "upstream failure"),
(StatusCode::SERVICE_UNAVAILABLE, "unavailable"),
(StatusCode::GATEWAY_TIMEOUT, "timeout"),
(StatusCode::IM_A_TEAPOT, "client error"),
(StatusCode::NOT_IMPLEMENTED, "server error"),
];
for (status, slug) in expected {
assert_eq!(
ErrorKind::for_status(status).slug(),
slug,
"default slug for {status}"
);
}
}
#[test]
fn mountebank_canonical_slugs_are_verbatim() {
assert_eq!(ErrorKind::BadData.slug(), "bad data");
assert_eq!(ErrorKind::InvalidInjection.slug(), "invalid injection");
assert_eq!(ErrorKind::ResourceConflict.slug(), "resource conflict");
assert_eq!(ErrorKind::InsufficientAccess.slug(), "insufficient access");
assert_eq!(ErrorKind::NoSuchResource.slug(), "no such resource");
assert_eq!(ErrorKind::Unauthorized.slug(), "unauthorized");
}
#[test]
fn every_slug_is_a_lowercase_space_separated_token() {
for kind in ErrorKind::ALL {
let s = kind.slug();
assert!(!s.is_empty(), "{kind:?} has an empty slug");
assert!(
s.chars().all(|c| c.is_ascii_lowercase() || c == ' '),
"{kind:?} slug {s:?} must be lowercase words separated by single spaces"
);
assert!(
!s.starts_with(' ') && !s.ends_with(' ') && !s.contains(" "),
"{kind:?} slug {s:?} has stray whitespace"
);
}
}
#[test]
fn error_body_adds_type_and_leaves_code_as_the_status_string() {
for status in [
StatusCode::BAD_REQUEST,
StatusCode::SERVICE_UNAVAILABLE,
StatusCode::PAYLOAD_TOO_LARGE,
StatusCode::BAD_GATEWAY,
StatusCode::GATEWAY_TIMEOUT,
] {
let body = body_of(status);
assert_eq!(
body["errors"][0]["code"],
status.as_str(),
"code must remain the status string for {status}"
);
assert_eq!(
body["errors"][0]["type"],
ErrorKind::for_status(status).slug(),
"type must be the default slug for {status}"
);
assert_eq!(body["errors"][0]["message"], "msg");
}
}
#[test]
fn typed_body_overrides_type_but_never_code() {
let raw = error_body_typed(
StatusCode::INTERNAL_SERVER_ERROR,
ErrorKind::ScriptError,
"boom",
);
let body: serde_json::Value = serde_json::from_str(&raw).expect("valid json");
assert_eq!(body["errors"][0]["code"], "500");
assert_eq!(body["errors"][0]["type"], "script error");
assert_ne!(
body["errors"][0]["type"],
ErrorKind::for_status(StatusCode::INTERNAL_SERVER_ERROR).slug(),
"this test is only meaningful if the named kind differs from the status default"
);
}
#[test]
fn the_field_is_named_type_on_the_wire() {
let raw = error_body(StatusCode::NOT_FOUND, "nope");
assert!(raw.contains("\"type\""), "wire field must be `type`: {raw}");
assert!(
!raw.contains("error_type"),
"the Rust field name must not leak: {raw}"
);
}
}