use super::support::{config, get, request};
use serde_json::Value;
use servlet::{
App,
ecosystem::{
axum::body::to_bytes,
recourse::{
catalog::{Catalog, CatalogSpec, CodeNumber},
diagnostic::{DiagnosticType, NoEvidence},
http::{CorrelationId, CorrelationIdError, Fixed, HttpProblemType},
},
recourse_axum::{
HandlerResult, ProblemContext, RecourseLayer, RecourseLayerBuilder, RequestIdGenerator,
},
tokio,
tower::ServiceExt,
zlid::{Family, ZLID},
},
web::{
Body, Router,
http::{HeaderName, Request, StatusCode},
routing::get as route_get,
with_recourse,
},
};
const PRIVATE_PANIC: &str = "private panic sentinel";
const FALLBACK_ID: &str = "recourse-generated";
enum TestCatalog {}
impl CatalogSpec for TestCatalog {
const NAME: &'static str = "servlet-recourse-test";
const PREFIX: &'static str = "MRC";
const TYPE_BASE: &'static str = "https://servlet.invalid/problems/";
}
enum Missing {}
impl DiagnosticType for Missing {
type Catalog = TestCatalog;
type Evidence = NoEvidence;
const NUMBER: CodeNumber = CodeNumber::new(1);
const TITLE: &'static str = "Missing";
const DETAIL: &'static str = "The requested item is missing.";
const SUGGESTIONS: &'static [&'static str] = &[];
const DOCS: &'static str = "The resource could not be found.";
}
impl HttpProblemType for Missing {
type Policy = Fixed<404>;
}
enum Internal {}
impl DiagnosticType for Internal {
type Catalog = TestCatalog;
type Evidence = NoEvidence;
const NUMBER: CodeNumber = CodeNumber::new(2);
const TITLE: &'static str = "Internal error";
const DETAIL: &'static str = "The service could not complete the request.";
const SUGGESTIONS: &'static [&'static str] = &[];
const DOCS: &'static str = "A sanitized internal failure.";
}
impl HttpProblemType for Internal {
type Policy = Fixed<500>;
}
struct FallbackRequestIds;
impl RequestIdGenerator for FallbackRequestIds {
fn generate(&self) -> Result<CorrelationId, CorrelationIdError> {
CorrelationId::new(FALLBACK_ID)
}
}
async fn missing(problems: ProblemContext<TestCatalog>) -> HandlerResult<&'static str> {
Err(problems.problem::<Missing>(NoEvidence))
}
async fn panic_before_response() -> &'static str {
panic!("{PRIVATE_PANIC}");
}
fn recourse_builder() -> RecourseLayerBuilder<TestCatalog> {
let catalog = Catalog::builder()
.problem::<Missing>()
.problem::<Internal>()
.build()
.unwrap();
RecourseLayer::builder(catalog)
.internal::<Internal>()
.request_ids(FallbackRequestIds)
.discard_faults()
}
fn router() -> Router {
let routes = Router::new()
.route("/missing", route_get(missing))
.route("/panic", route_get(panic_before_response))
.route("/ok", route_get(|| async { "still running" }));
with_recourse(routes, recourse_builder()).unwrap()
}
fn problem(response: &str, status: StatusCode) -> (&str, Value) {
let (head, body) = response.split_once("\r\n\r\n").unwrap();
let status_line = head.lines().next().unwrap();
assert_eq!(
status_line.split_whitespace().nth(1),
Some(status.as_str()),
"{head}"
);
assert_eq!(header(head, "content-type"), "application/problem+json");
let id = header(head, "x-request-id");
assert_eq!(
ZLID::parse_canonical(id).unwrap().family(),
Some(Family::Random)
);
let problem: Value = serde_json::from_str(body).unwrap();
assert_eq!(problem["status"], status.as_u16());
(id, problem)
}
fn header<'a>(head: &'a str, name: &str) -> &'a str {
head.lines()
.filter_map(|line| line.split_once(':'))
.find_map(|(key, value)| key.eq_ignore_ascii_case(name).then(|| value.trim()))
.unwrap_or_else(|| panic!("missing {name} in {head}"))
}
#[tokio::test]
async fn typed_problem_uses_servlet_request_id_despite_client_header() {
let running = App::new("recourse-problem")
.config(config())
.http(router())
.start()
.await
.unwrap();
let response = request(
running.local_addr().unwrap(),
concat!(
"GET /missing HTTP/1.1\r\nHost: localhost\r\n",
"X-Request-Id: client-supplied\r\nConnection: close\r\n\r\n"
),
)
.await;
let (id, body) = problem(&response, StatusCode::NOT_FOUND);
assert!(!response.contains("client-supplied"));
assert_eq!(body["code"], "MRC-1");
assert_eq!(body["instance"], format!("/problem-occurrences/{id}"));
running.handle().shutdown();
running.wait().await.unwrap();
}
#[tokio::test]
async fn contained_panic_returns_redacted_problem_and_keeps_serving() {
let running = App::new("recourse-panic")
.config(config())
.http(router())
.start()
.await
.unwrap();
let address = running.local_addr().unwrap();
let response = get(address, "/panic").await;
let (id, body) = problem(&response, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(body["code"], "MRC-2");
assert_eq!(body["instance"], format!("/problem-occurrences/{id}"));
assert!(!response.contains(PRIVATE_PANIC));
let next = get(address, "/ok").await;
assert!(next.starts_with("HTTP/1.1 200"));
assert!(next.ends_with("still running"));
running.handle().shutdown();
running.wait().await.unwrap();
}
#[tokio::test]
async fn standalone_router_generates_request_id_despite_client_header() {
let configured = recourse_builder().request_id_header(HeaderName::from_static("x-custom-id"));
let routes = Router::new().route("/missing", route_get(missing));
let response = with_recourse(routes, configured)
.unwrap()
.oneshot(
Request::builder()
.uri("/missing")
.header("x-request-id", "standalone-client")
.header("x-custom-id", "other-client")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(response.headers()["x-request-id"], FALLBACK_ID);
assert!(!response.headers().contains_key("x-custom-id"));
let raw_body = to_bytes(response.into_body(), 4096).await.unwrap();
let body: Value = serde_json::from_slice(&raw_body).unwrap();
assert_eq!(
body["instance"],
format!("/problem-occurrences/{FALLBACK_ID}")
);
}
#[tokio::test]
async fn runtime_rejection_keeps_servlet_problem_shape() {
let mut settings = config();
settings.request_body_limit = 4;
let running = App::new("recourse-admission")
.config(settings)
.http(router())
.start()
.await
.unwrap();
let response = request(
running.local_addr().unwrap(),
concat!(
"POST /missing HTTP/1.1\r\nHost: localhost\r\n",
"Content-Length: 100\r\nConnection: close\r\n\r\n"
),
)
.await;
let (id, body) = problem(&response, StatusCode::PAYLOAD_TOO_LARGE);
assert_eq!(body["type"], "about:blank");
assert_eq!(body["code"], "body_too_large");
assert_eq!(body["request_id"], id);
assert!(body.get("instance").is_none());
running.handle().shutdown();
running.wait().await.unwrap();
}