#![cfg(feature = "http")]
use std::collections::BTreeSet;
use axum::{
Router,
body::{Body, to_bytes},
http::{Method, Request, StatusCode, header},
middleware::from_fn,
response::{Html, Response},
routing::{any, get, post},
};
use footing::http::{
ProblemDetails, REQUEST_ID_HEADER_NAME, RequestContext, RequestId, TraceParent,
error::PROBLEM_JSON_MEDIA_TYPE, method_not_allowed, request_context_middleware,
route_not_found,
};
use tower::ServiceExt;
const TRACEPARENT: &str = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
const TRACE_ID: &str = "4bf92f3577b34da6a3ce929d0e0e4736";
async fn problem(response: Response, status: StatusCode, code: &str) -> ProblemDetails {
assert_eq!(response.status(), status);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
PROBLEM_JSON_MEDIA_TYPE
);
assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
let body = to_bytes(response.into_body(), 4096).await.unwrap();
let problem: ProblemDetails = serde_json::from_slice(&body).unwrap();
assert_eq!(problem.status(), status.as_u16());
assert_eq!(problem.code(), code);
assert_eq!(problem.type_uri(), "about:blank");
assert!(problem.instance().is_none());
assert!(problem.details().is_none());
problem
}
#[tokio::test]
async fn unmatched_route_has_safe_details_and_standalone_context() {
let app = Router::new().fallback(route_not_found);
let response = app
.oneshot(
Request::get("/sensitive-resource?credential=secret")
.header(REQUEST_ID_HEADER_NAME, "standalone-request")
.header("traceparent", TRACEPARENT)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert!(!response.headers().contains_key(header::ALLOW));
let problem = problem(response, StatusCode::NOT_FOUND, "route_not_found").await;
assert_eq!(problem.title(), "Not Found");
assert_eq!(problem.detail(), "route not found");
assert_eq!(problem.request_id(), Some("standalone-request"));
assert_eq!(problem.trace_id(), Some(TRACE_ID));
}
#[tokio::test]
async fn routing_errors_reuse_installed_context_and_outer_response_headers() {
let app = Router::new()
.route("/resource", get(|| async { "ok" }))
.fallback(route_not_found)
.method_not_allowed_fallback(method_not_allowed)
.layer(from_fn(request_context_middleware));
for (path, status, code) in [
("/missing", StatusCode::NOT_FOUND, "route_not_found"),
(
"/resource",
StatusCode::METHOD_NOT_ALLOWED,
"method_not_allowed",
),
] {
let mut request = Request::post(path)
.header(REQUEST_ID_HEADER_NAME, "ignored-header-request")
.body(Body::empty())
.unwrap();
request.extensions_mut().insert(
RequestContext::new(RequestId::new("installed-request").unwrap())
.with_traceparent(TraceParent::new(TRACEPARENT).unwrap()),
);
let response = app.clone().oneshot(request).await.unwrap();
assert_eq!(
response.headers()[REQUEST_ID_HEADER_NAME],
"installed-request"
);
let problem = problem(response, status, code).await;
assert_eq!(problem.request_id(), Some("installed-request"));
assert_eq!(problem.trace_id(), Some(TRACE_ID));
}
}
#[tokio::test]
async fn method_error_preserves_axum_allow_and_does_not_echo_input() {
let app = Router::new()
.route("/resource", get(|| async { "ok" }))
.route("/resource", post(|| async { StatusCode::CREATED }))
.method_not_allowed_fallback(method_not_allowed);
let response = app
.oneshot(
Request::builder()
.method(Method::from_bytes(b"SECRET-METHOD").unwrap())
.uri("/resource?secret=value")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let allowed: BTreeSet<_> = response.headers()[header::ALLOW]
.to_str()
.unwrap()
.split(',')
.map(str::trim)
.collect();
assert_eq!(allowed, BTreeSet::from(["GET", "HEAD", "POST"]));
let problem = problem(
response,
StatusCode::METHOD_NOT_ALLOWED,
"method_not_allowed",
)
.await;
assert_eq!(problem.title(), "Method Not Allowed");
assert_eq!(problem.detail(), "method not allowed");
assert!(problem.request_id().is_some());
}
#[tokio::test]
async fn head_routing_errors_keep_headers_and_never_send_a_body() {
let api = Router::new()
.route("/resource", post(|| async { "created" }))
.fallback(route_not_found)
.method_not_allowed_fallback(method_not_allowed);
let app = Router::new()
.nest("/api", api)
.fallback(route_not_found)
.layer(from_fn(request_context_middleware));
for (path, status) in [
("/missing", StatusCode::NOT_FOUND),
("/api/missing", StatusCode::NOT_FOUND),
("/api/resource", StatusCode::METHOD_NOT_ALLOWED),
] {
let response = app
.clone()
.oneshot(
Request::head(path)
.header(REQUEST_ID_HEADER_NAME, "head-request")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), status);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
PROBLEM_JSON_MEDIA_TYPE
);
assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
assert_eq!(response.headers()[REQUEST_ID_HEADER_NAME], "head-request");
assert!(
response.headers()[header::CONTENT_LENGTH]
.to_str()
.unwrap()
.parse::<usize>()
.unwrap()
> 0
);
if status == StatusCode::METHOD_NOT_ALLOWED {
assert_eq!(response.headers()[header::ALLOW], "POST");
} else {
assert!(!response.headers().contains_key(header::ALLOW));
}
assert!(
to_bytes(response.into_body(), 4096)
.await
.unwrap()
.is_empty()
);
}
}
#[tokio::test]
async fn nested_api_errors_never_fall_through_to_frontend_html() {
let api = Router::new()
.route("/resource", get(|| async { "ok" }))
.fallback(route_not_found)
.method_not_allowed_fallback(method_not_allowed);
let app = Router::new()
.nest("/api", api)
.route("/api/", any(route_not_found))
.fallback(|| async { Html("<!doctype html><title>Frontend</title>") })
.layer(from_fn(request_context_middleware));
for path in ["/api", "/api/", "/api/missing", "/api/missing/deep"] {
for method in [Method::GET, Method::POST, Method::HEAD] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method.clone())
.uri(path)
.header(header::ACCEPT, "text/html")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND, "{method} {path}");
assert_eq!(
response.headers()[header::CONTENT_TYPE],
PROBLEM_JSON_MEDIA_TYPE
);
if method == Method::HEAD {
assert!(
to_bytes(response.into_body(), 4096)
.await
.unwrap()
.is_empty()
);
} else {
problem(response, StatusCode::NOT_FOUND, "route_not_found").await;
}
}
}
let response = app
.oneshot(Request::get("/dashboard").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response.headers()[header::CONTENT_TYPE],
"text/html; charset=utf-8"
);
assert_eq!(
to_bytes(response.into_body(), 4096).await.unwrap(),
"<!doctype html><title>Frontend</title>"
);
}
#[tokio::test]
async fn business_responses_and_explicit_method_fallbacks_remain_untouched() {
let app = Router::new()
.route(
"/resource",
get(|| async { (StatusCode::NOT_FOUND, "business lookup failed") })
.fallback(|| async { (StatusCode::METHOD_NOT_ALLOWED, "custom method policy") }),
)
.fallback(route_not_found)
.method_not_allowed_fallback(method_not_allowed);
for (method, status, body) in [
(Method::GET, StatusCode::NOT_FOUND, "business lookup failed"),
(
Method::POST,
StatusCode::METHOD_NOT_ALLOWED,
"custom method policy",
),
] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri("/resource")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), status);
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), body);
}
}
#[tokio::test]
async fn endpoint_router_can_install_api_fallbacks_without_the_stack() {
use footing::http::{EndpointContract, EndpointMethod, EndpointPathPattern, EndpointRouter};
let (app, contracts) = EndpointRouter::new()
.route(
EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/resource")),
|| async { "ok" },
)
.unwrap()
.with_api_fallbacks()
.into_parts();
assert_eq!(contracts.len(), 1);
assert_eq!(contracts[0].path().as_str(), "/resource");
for (path, status, code) in [
("/missing", StatusCode::NOT_FOUND, "route_not_found"),
(
"/resource",
StatusCode::METHOD_NOT_ALLOWED,
"method_not_allowed",
),
] {
let response = app
.clone()
.oneshot(Request::post(path).body(Body::empty()).unwrap())
.await
.unwrap();
if status == StatusCode::METHOD_NOT_ALLOWED {
assert_eq!(response.headers()[header::ALLOW], "GET,HEAD");
}
problem(response, status, code).await;
}
}
#[cfg(feature = "http-stack")]
async fn assert_stacked_routing_problem(
app: &Router,
path: &str,
status: StatusCode,
code: &str,
allow: Option<&str>,
) {
let response = app
.clone()
.oneshot(
Request::delete(path)
.header(REQUEST_ID_HEADER_NAME, "stack-request")
.header("traceparent", TRACEPARENT)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.headers()[REQUEST_ID_HEADER_NAME], "stack-request");
assert_eq!(response.headers()["x-content-type-options"], "nosniff");
assert_eq!(response.headers()["x-frame-options"], "DENY");
assert_eq!(
response
.headers()
.get(header::ALLOW)
.map(|value| value.to_str().unwrap()),
allow
);
let problem = problem(response, status, code).await;
assert_eq!(problem.request_id(), Some("stack-request"));
assert_eq!(problem.trace_id(), Some(TRACE_ID));
}
#[cfg(feature = "http-stack")]
#[tokio::test]
async fn endpoint_router_installs_api_fallbacks_inside_the_standard_stack() {
use footing::http::{
EndpointContract, EndpointMethod, EndpointPathPattern, EndpointRouter,
HttpMiddlewareConfig, HttpMiddlewareStack,
};
let stack = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
.build()
.unwrap();
let app = EndpointRouter::new()
.route(
EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/resource")),
|| async { "ok" },
)
.unwrap()
.with_api_fallbacks()
.into_router(stack)
.unwrap();
assert_stacked_routing_problem(
&app,
"/missing",
StatusCode::NOT_FOUND,
"route_not_found",
None,
)
.await;
assert_stacked_routing_problem(
&app,
"/resource",
StatusCode::METHOD_NOT_ALLOWED,
"method_not_allowed",
Some("GET,HEAD"),
)
.await;
}
#[cfg(all(feature = "openapi", feature = "http-stack"))]
#[tokio::test]
async fn openapi_fallbacks_cover_composed_routes_inside_the_stack_without_new_operations() {
use footing::http::{
EndpointPolicy, HttpMiddlewareConfig, HttpMiddlewareStack,
openapi::{OpenApiRouter, route, utoipa},
};
use utoipa::openapi::{Info, OpenApi, path::Paths};
#[utoipa::path(get, path = "/direct", responses((status = 200)))]
async fn direct() -> &'static str {
"direct"
}
#[utoipa::path(post, path = "/merged", responses((status = 200)))]
async fn merged() -> &'static str {
"merged"
}
#[utoipa::path(get, path = "/nested", responses((status = 200)))]
async fn nested() -> &'static str {
"nested"
}
let document = || OpenApi::new(Info::new("Test API", "1"), Paths::new());
let merged = OpenApiRouter::new(document())
.unwrap()
.route(
route!(merged)
.unwrap()
.with_contract(|_| EndpointPolicy::new())
.unwrap(),
)
.unwrap();
let nested = OpenApiRouter::new(document())
.unwrap()
.route(
route!(nested)
.unwrap()
.with_contract(|_| EndpointPolicy::new())
.unwrap(),
)
.unwrap();
let stack = HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
.build()
.unwrap();
let (app, document) = OpenApiRouter::new(document())
.unwrap()
.route(
route!(direct)
.unwrap()
.with_contract(|_| EndpointPolicy::new())
.unwrap(),
)
.unwrap()
.merge(merged)
.unwrap()
.nest("/v1", nested)
.unwrap()
.with_api_fallbacks()
.into_parts_with_stack(stack)
.unwrap();
let document = serde_json::to_value(document).unwrap();
let paths = document["paths"].as_object().unwrap();
assert_eq!(paths.len(), 3);
for (path, method) in [
("/direct", "get"),
("/merged", "post"),
("/v1/nested", "get"),
] {
let operations: Vec<_> = paths[path]
.as_object()
.unwrap()
.keys()
.map(String::as_str)
.collect();
assert_eq!(operations, [method]);
}
for path in ["/missing", "/v1/missing"] {
assert_stacked_routing_problem(&app, path, StatusCode::NOT_FOUND, "route_not_found", None)
.await;
}
for (path, allow) in [
("/direct", "GET,HEAD"),
("/merged", "POST"),
("/v1/nested", "GET,HEAD"),
] {
assert_stacked_routing_problem(
&app,
path,
StatusCode::METHOD_NOT_ALLOWED,
"method_not_allowed",
Some(allow),
)
.await;
}
}