#![cfg(feature = "openapi")]
#[cfg(feature = "pagination")]
use axum::{Json, body::to_bytes};
use axum::{
Router,
body::Body,
http::{Request, StatusCode},
};
#[cfg(any(feature = "pagination", feature = "observability"))]
use footing::http::ApiProblem;
#[cfg(feature = "http-stack")]
use footing::http::RateLimitRequestPolicy;
#[cfg(any(feature = "pagination", feature = "observability"))]
use footing::http::error::PROBLEM_JSON_MEDIA_TYPE;
use footing::http::{
EndpointAuth, EndpointContract, EndpointContractRegistry, EndpointMethod, EndpointPathPattern,
EndpointPermissions, EndpointPolicy, IdempotencyRequestPolicy,
openapi::{self, OpenApiContractError, OpenApiRouteError, OpenApiRouter, utoipa},
};
#[cfg(feature = "pagination")]
use footing::http::{EndpointPagination, openapi::route};
#[cfg(feature = "observability")]
use footing::http::{FieldViolation, ProblemDetails};
#[cfg(feature = "http-stack")]
use footing::http::{
HttpMiddlewareConfig, HttpMiddlewareError, HttpMiddlewareStack, RequiredIdempotencyKey,
};
#[cfg(feature = "pagination")]
use footing::{
http::CursorPagination,
pagination::{CursorPage, OffsetPage, PageLimits},
};
use serde_json::{Value, json};
use tower::ServiceExt;
#[cfg(feature = "observability")]
use utoipa::PartialSchema;
use utoipa::openapi::{
Info, OpenApi, RefOr, Required,
path::{HttpMethod, Operation, Parameter, PathItem, Paths},
};
#[cfg(feature = "pagination")]
use utoipa::{IntoParams, ToSchema};
#[cfg(feature = "pagination")]
#[derive(serde::Serialize, ToSchema)]
struct Item {
id: u64,
}
#[cfg(feature = "pagination")]
#[derive(serde::Serialize, ToSchema)]
struct OtherItem {
name: String,
}
#[utoipa::path(get, path = "/items", params(CursorPagination), responses(
(status = 200, body = CursorPage<Item>),
(status = 400, response = inline(ApiProblem))
))]
#[cfg(feature = "pagination")]
async fn items(page: CursorPagination) -> Result<Json<CursorPage<Item>>, ApiProblem> {
CursorPage::new(vec![], page.page_size(), None, None)
.map(Json)
.map_err(|_| ApiProblem::internal_error())
}
#[utoipa::path(get, path = "/other", responses((status = 200, body = CursorPage<OtherItem>)))]
#[cfg(feature = "pagination")]
async fn other() -> Json<CursorPage<OtherItem>> {
Json(CursorPage::new(vec![], 10, None, None).unwrap())
}
#[utoipa::path(get, path = "/offset", params(footing::http::OffsetPagination), responses((status = 200, body = OffsetPage<Item>)))]
#[cfg(feature = "pagination")]
async fn offset(page: footing::http::OffsetPagination) -> Json<OffsetPage<Item>> {
Json(OffsetPage::new(vec![], page.page(), page.page_size(), 0).unwrap())
}
#[cfg(feature = "pagination")]
fn contracts() -> [EndpointContract; 1] {
[
EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/items"))
.with_pagination(EndpointPagination::Cursor),
]
}
#[cfg(feature = "pagination")]
fn api() -> (Router, OpenApi) {
#[derive(utoipa::OpenApi)]
#[openapi(info(title = "Inventory", version = "1.0.0"))]
struct Api;
let (router, document, _) = OpenApiRouter::new(<Api as utoipa::OpenApi>::openapi())
.unwrap()
.route(route!(items).unwrap())
.unwrap()
.into_parts();
(router, document)
}
fn inline_parameter(parameter: &RefOr<Parameter>) -> &Parameter {
let RefOr::T(parameter) = parameter else {
panic!("expected an inline parameter");
};
parameter
}
#[cfg(feature = "pagination")]
fn inline_parameter_mut(parameter: &mut RefOr<Parameter>) -> &mut Parameter {
let RefOr::T(parameter) = parameter else {
panic!("expected an inline parameter");
};
parameter
}
#[cfg(any(feature = "pagination", feature = "observability"))]
fn assert_refs_resolve(value: &Value, root: &Value) {
match value {
Value::Object(object) => {
if let Some(Value::String(reference)) = object.get("$ref") {
let pointer = reference.strip_prefix('#').expect("local reference");
assert!(
root.pointer(pointer).is_some(),
"unresolved reference: {reference}"
);
}
for value in object.values() {
assert_refs_resolve(value, root);
}
}
Value::Array(array) => {
for value in array {
assert_refs_resolve(value, root);
}
}
_ => {}
}
}
#[cfg(feature = "http-stack")]
fn minimal_stack() -> HttpMiddlewareStack {
HttpMiddlewareStack::builder(HttpMiddlewareConfig::minimal())
.build()
.unwrap()
}
#[tokio::test]
#[cfg(feature = "http-stack")]
async fn derived_contracts_share_pagination_with_the_document_and_handler_in_either_order() {
let limits = PageLimits::new(3, 7).unwrap();
for (cursor, pagination_first) in [(true, true), (true, false), (false, true), (false, false)] {
let route = if cursor {
route!(items)
} else {
route!(offset)
}
.unwrap();
let path = if cursor { "/items" } else { "/offset" };
let pagination = if cursor {
EndpointPagination::Cursor
} else {
EndpointPagination::Offset
};
let paginate = |route: openapi::OpenApiRoute| {
if cursor {
route.with_cursor_pagination(limits)
} else {
route.with_offset_pagination(limits)
}
.unwrap()
};
let policy = |_| EndpointPolicy::new();
let route = if pagination_first {
paginate(route).with_contract(policy).unwrap()
} else {
paginate(route.with_contract(policy).unwrap())
};
let api = OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route)
.unwrap();
let registry = api.contracts();
let contract = ®istry.endpoints()[0];
assert_eq!(contract.method(), EndpointMethod::Get);
assert_eq!(contract.path().as_str(), path);
assert_eq!(contract.pagination(), pagination);
let (app, document) = api.into_parts_with_stack(minimal_stack()).unwrap();
let parameters = document.paths.paths[path]
.get
.as_ref()
.unwrap()
.parameters
.as_ref()
.unwrap();
let page_size = parameters
.iter()
.map(inline_parameter)
.find(|parameter| parameter.name == "page_size")
.unwrap();
let schema = serde_json::to_value(page_size.schema.as_ref().unwrap()).unwrap();
assert_eq!(schema["default"], 3);
assert_eq!(schema["maximum"], 7);
let response = app
.oneshot(Request::get(path).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body: Value =
serde_json::from_slice(&to_bytes(response.into_body(), 4096).await.unwrap()).unwrap();
assert_eq!(body["page_size"], 3);
}
}
#[tokio::test]
async fn derived_contracts_cover_explicit_methods_and_preserve_typed_permissions_when_nested() {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Permission {
Read,
Write,
}
let document: OpenApi = serde_json::from_value(json!({
"openapi": "3.1.0", "info": {"title": "test", "version": "1"},
"paths": {"/items/{id}": {
"parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}],
"get": {"responses": {"200": {"description": "ok"}}},
"post": {"responses": {"200": {"description": "ok"}}}
}}
})).unwrap();
let route = openapi::OpenApiRoute::from_handler(|| async { "ok" }, document)
.unwrap()
.with_contract(|method| {
let permission = if method == EndpointMethod::Get {
Permission::Read
} else {
Permission::Write
};
EndpointPolicy::new()
.with_auth(EndpointAuth::Authenticated)
.with_permissions(EndpointPermissions::One(permission))
})
.unwrap();
let document = || OpenApi::new(Info::new("test", "1"), Paths::new());
let module = OpenApiRouter::new(document())
.unwrap()
.route(route)
.unwrap();
let (app, document, contracts): (Router, _, _) = OpenApiRouter::new(document())
.unwrap()
.nest("/api", module)
.unwrap()
.into_parts();
assert!(document.paths.paths.contains_key("/api/items/{id}"));
assert_eq!(contracts.len(), 2, "automatic HEAD does not add a contract");
for (contract, method, permission) in [
(&contracts[0], EndpointMethod::Get, Permission::Read),
(&contracts[1], EndpointMethod::Post, Permission::Write),
] {
assert_eq!(contract.method(), method);
assert_eq!(
contract.path(),
&EndpointPathPattern::template("/api/items/{id}")
);
assert_eq!(contract.auth(), EndpointAuth::Authenticated);
assert_eq!(contract.permissions(), EndpointPermissions::One(permission));
}
for method in ["GET", "POST", "HEAD"] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri("/api/items/42")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}
#[test]
#[cfg(feature = "http-stack")]
fn derived_contracts_keep_document_and_runtime_validation() {
let missing_header: Result<openapi::OpenApiRoute, _> =
route!(other).unwrap().with_contract(|_| {
EndpointPolicy::new().with_idempotency(IdempotencyRequestPolicy::Required)
});
assert!(matches!(
missing_header,
Err(OpenApiRouteError::InvalidContracts(
OpenApiContractError::InvalidParameter { .. }
))
));
for authentication in [false, true] {
let route = route!(other)
.unwrap()
.with_contract(|_| {
if authentication {
EndpointPolicy::new().with_auth(EndpointAuth::Authenticated)
} else {
EndpointPolicy::new().with_rate_limit(RateLimitRequestPolicy::Enabled)
}
})
.unwrap();
let error = OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route)
.unwrap()
.into_parts_with_stack(minimal_stack())
.err()
.unwrap();
assert!(matches!(
(authentication, error),
(
false,
OpenApiRouteError::InvalidMiddleware(
HttpMiddlewareError::EndpointContractRateLimitMismatch { .. }
)
) | (
true,
OpenApiRouteError::InvalidMiddleware(
HttpMiddlewareError::EndpointContractAuthenticationRequired { .. }
)
)
));
}
}
#[test]
#[cfg(feature = "pagination")]
fn derived_contracts_reject_duplicate_attachment_and_unsupported_methods() {
let route: openapi::OpenApiRoute = route!(other)
.unwrap()
.with_contract(|_| EndpointPolicy::new())
.unwrap();
assert!(matches!(
route.with_contract(|_| EndpointPolicy::new()),
Err(OpenApiRouteError::InvalidDocument { .. })
));
let document = document_with_path(PathItem::new(HttpMethod::Trace, Operation::new()));
let route: openapi::OpenApiRoute =
openapi::OpenApiRoute::from_handler(|| async {}, document).unwrap();
assert!(matches!(
route.with_contract(|_| EndpointPolicy::new()),
Err(OpenApiRouteError::InvalidContracts(
OpenApiContractError::UnsupportedPathItem { .. }
))
));
}
#[tokio::test]
#[cfg(feature = "http-stack")]
async fn checked_routes_export_contract_metadata_only_when_explicitly_requested() {
let contract = contracts()[0].clone();
let api = OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(
route!(items)
.unwrap()
.with_contract(|_| contract.policy())
.unwrap()
.with_cursor_pagination(PageLimits::default())
.unwrap(),
)
.unwrap();
let endpoints = api.contracts().endpoints().to_vec();
assert_eq!(endpoints, [contract]);
let (router, document) = api
.into_parts_with_stack(
HttpMiddlewareStack::builder(HttpMiddlewareConfig::standard())
.build()
.unwrap(),
)
.unwrap();
assert!(
document.paths.paths["/items"]
.get
.as_ref()
.unwrap()
.extensions
.is_none()
);
assert!(
!serde_json::to_string(&document)
.unwrap()
.contains("footing")
);
let document = openapi::annotate_contracts(
document,
&EndpointContractRegistry::new(&endpoints),
str::to_owned,
)
.unwrap();
assert_eq!(
document.paths.paths["/items"]
.get
.as_ref()
.unwrap()
.extensions
.as_ref()
.unwrap()[openapi::CONTRACT_EXTENSION]["contract"]["rate_limit"],
"disabled"
);
let response = router
.oneshot(Request::get("/items").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
#[test]
#[cfg(feature = "http-stack")]
fn attached_contracts_reject_missing_runtime_requirements() {
for (contract, expected) in [
(
contracts()[0]
.clone()
.with_rate_limit(RateLimitRequestPolicy::Enabled),
"rate_limit",
),
(
contracts()[0]
.clone()
.with_rate_limit(RateLimitRequestPolicy::Disabled)
.with_auth(EndpointAuth::Authenticated),
"auth",
),
] {
let result = OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(
route!(items)
.unwrap()
.with_contract(|_| contract.policy())
.unwrap()
.with_cursor_pagination(PageLimits::default())
.unwrap(),
)
.unwrap()
.into_parts_with_stack(minimal_stack());
assert!(matches!(
(expected, result),
(
"rate_limit",
Err(OpenApiRouteError::InvalidMiddleware(
HttpMiddlewareError::EndpointContractRateLimitMismatch { .. },
)),
) | (
"auth",
Err(OpenApiRouteError::InvalidMiddleware(
HttpMiddlewareError::EndpointContractAuthenticationRequired { .. },
)),
)
));
}
let required: EndpointContract =
EndpointContract::new(EndpointMethod::Post, EndpointPathPattern::exact("/items"))
.with_rate_limit(RateLimitRequestPolicy::Disabled)
.with_idempotency(IdempotencyRequestPolicy::Required);
let result = OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(
route!(create_item)
.unwrap()
.with_contract(|_| required.policy())
.unwrap(),
)
.unwrap()
.into_parts_with_stack(minimal_stack());
assert!(matches!(
result,
Err(OpenApiRouteError::InvalidMiddleware(
HttpMiddlewareError::EndpointContractIdempotencyMismatch { .. }
))
));
}
#[test]
#[cfg(feature = "http-stack")]
fn checked_document_router_rejects_operations_without_contracts() {
let result = OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route!(items).unwrap())
.unwrap()
.into_parts_with_stack(minimal_stack());
assert!(matches!(
result,
Err(OpenApiRouteError::InvalidContracts(
OpenApiContractError::OperationWithoutContract { .. }
))
));
}
#[test]
#[cfg(feature = "pagination")]
fn native_parts_preserve_typed_contract_metadata() {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Permission {
Read,
}
let contract = EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/items"))
.with_pagination(EndpointPagination::Cursor)
.with_auth(EndpointAuth::Authenticated)
.with_permissions(EndpointPermissions::One(Permission::Read));
let (_, _, attached) =
OpenApiRouter::<(), _>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(
route!(items)
.unwrap()
.with_contract(|_| contract.policy())
.unwrap()
.with_cursor_pagination(PageLimits::default())
.unwrap(),
)
.unwrap()
.into_parts();
assert_eq!(attached, vec![contract]);
}
#[tokio::test]
#[cfg(feature = "pagination")]
async fn documented_routes_serve_the_declared_payloads_and_errors() {
let (router, document) = api();
let endpoints = contracts();
let document = openapi::annotate_contracts(
document,
&EndpointContractRegistry::new(&endpoints),
str::to_owned,
)
.unwrap();
let document = serde_json::to_value(document).unwrap();
assert_eq!(document["openapi"], "3.1.0");
assert_refs_resolve(&document, &document);
let operation = &document["paths"]["/items"]["get"];
assert_eq!(
operation[openapi::CONTRACT_EXTENSION]["contract"]["pagination"],
"cursor"
);
let success = router
.clone()
.oneshot(
Request::get("/items?page_size=7")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(success.status(), StatusCode::OK);
let payload: Value =
serde_json::from_slice(&to_bytes(success.into_body(), 4096).await.unwrap()).unwrap();
assert_eq!(
payload,
json!({"items": [], "page_size": 7, "next_cursor": null, "total": null})
);
let schema_ref = operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"]
.as_str()
.unwrap();
let schema = document
.pointer(schema_ref.strip_prefix('#').unwrap())
.unwrap();
assert_eq!(schema["properties"].as_object().unwrap().len(), 4);
assert!(schema["properties"].get("has_more").is_none());
assert!(
schema["required"]
.as_array()
.unwrap()
.contains(&json!("next_cursor"))
);
assert!(
schema["required"]
.as_array()
.unwrap()
.contains(&json!("total"))
);
assert_eq!(
schema["properties"]["total"]["type"],
json!(["integer", "null"])
);
assert_eq!(
schema["properties"]["next_cursor"]["type"],
json!(["string", "null"])
);
let failure = router
.oneshot(
Request::get("/items?page_size=0")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(failure.status(), StatusCode::BAD_REQUEST);
assert_eq!(failure.headers()["content-type"], PROBLEM_JSON_MEDIA_TYPE);
let problem: Value =
serde_json::from_slice(&to_bytes(failure.into_body(), 4096).await.unwrap()).unwrap();
let response = &operation["responses"]["400"];
let problem_schema = &response["content"][PROBLEM_JSON_MEDIA_TYPE]["schema"];
for key in problem_schema["required"].as_array().unwrap() {
assert!(problem.get(key.as_str().unwrap()).is_some());
}
assert_eq!(problem_schema["properties"]["status"]["minimum"], 400);
assert_eq!(problem_schema["properties"]["status"]["maximum"], 599);
assert!(problem_schema["properties"].get("type").is_some());
assert!(problem_schema["properties"].get("type_uri").is_none());
}
#[test]
#[cfg(feature = "pagination")]
fn generic_payload_components_have_distinct_names_and_resolved_references() {
#[derive(utoipa::OpenApi)]
#[openapi(paths(items, other, offset))]
struct Api;
let _: Router = Router::new()
.route("/other", axum::routing::get(other))
.route("/offset", axum::routing::get(offset));
let document = <Api as utoipa::OpenApi>::openapi();
let json = serde_json::to_value(document).unwrap();
assert_refs_resolve(&json, &json);
let reference = |path: &str| {
json["paths"][path]["get"]["responses"]["200"]["content"]["application/json"]["schema"]["$ref"].as_str().unwrap()
};
assert_ne!(reference("/items"), reference("/other"));
assert_ne!(reference("/items"), reference("/offset"));
}
#[tokio::test]
#[cfg(feature = "pagination")]
async fn custom_pagination_documentation_matches_extractor_limits() {
let limits = PageLimits::new(7, 12)
.unwrap()
.with_max_cursor_length(40)
.unwrap();
let (router, document, _) =
OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(
route!(items)
.unwrap()
.with_cursor_pagination(limits)
.unwrap(),
)
.unwrap()
.into_parts();
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&contracts())).unwrap();
let json = serde_json::to_value(document).unwrap();
let parameters = &json["paths"]["/items"]["get"]["parameters"];
assert_eq!(parameters[0]["schema"]["default"], 7);
assert_eq!(parameters[0]["schema"]["maximum"], 12);
assert_eq!(parameters[1]["schema"]["maxLength"], 40);
assert!(
parameters
.as_array()
.unwrap()
.iter()
.all(|parameter| parameter["required"] == false && parameter["in"] == "query")
);
for (query, status) in [
("", StatusCode::OK),
("?page_size=12", StatusCode::OK),
("?page_size=13", StatusCode::BAD_REQUEST),
] {
let response = router
.clone()
.oneshot(
Request::get(format!("/items{query}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), status);
}
}
#[test]
#[cfg(feature = "http-stack")]
fn idempotency_parameters_reflect_optional_and_required_policies() {
assert!(openapi::idempotency_key_parameter(IdempotencyRequestPolicy::Disabled).is_none());
for (policy, required) in [
(IdempotencyRequestPolicy::HeaderOptional, false),
(IdempotencyRequestPolicy::Required, true),
] {
let parameter =
serde_json::to_value(openapi::idempotency_key_parameter(policy).unwrap()).unwrap();
assert_eq!(parameter["required"], required);
assert_eq!(parameter["name"], "idempotency-key");
assert_eq!(parameter["in"], "header");
assert_eq!(parameter["schema"]["maxLength"], 128);
}
assert_eq!(
serde_json::to_value(RequiredIdempotencyKey::into_params(|| None)).unwrap()[0]["required"],
true
);
}
#[test]
#[cfg(feature = "observability")]
fn scalar_and_transparent_schemas_follow_serialization() {
let code = footing::http::ProblemCode::try_new("example:invalid").unwrap();
assert_eq!(serde_json::to_value(code).unwrap(), "example:invalid");
assert_eq!(
serde_json::to_value(footing::http::ProblemCode::schema()).unwrap()["type"],
"string"
);
assert_eq!(
serde_json::to_value(footing::http::RequestId::schema()).unwrap()["maxLength"],
128
);
let violation = FieldViolation::new("name", "required", "Name is required");
let violations = vec![violation];
assert!(serde_json::to_value(violations).unwrap().is_array());
assert_eq!(
serde_json::to_value(Vec::<FieldViolation>::schema()).unwrap()["type"],
"array"
);
let check = footing::observability::HealthCheck::new(
"database",
footing::observability::HealthState::Serving,
)
.unwrap();
assert!(serde_json::to_value(check).unwrap()["message"].is_null());
let schema = serde_json::to_value(footing::observability::HealthCheck::schema()).unwrap();
assert!(
schema["required"]
.as_array()
.unwrap()
.contains(&json!("message"))
);
assert_eq!(
schema["properties"]["message"]["type"],
json!(["string", "null"])
);
let problem = serde_json::to_value(ProblemDetails::schema()).unwrap();
assert_eq!(problem["properties"]["status"]["type"], "integer");
assert_eq!(problem["properties"]["status"]["minimum"], 400);
assert_eq!(problem["properties"]["status"]["maximum"], 599);
for (field, expected, description) in [
(
"code",
footing::http::ProblemCode::schema(),
"Stable machine-readable error code.",
),
(
"type",
footing::http::ProblemUri::schema(),
"URI identifying the problem type.",
),
(
"instance",
footing::http::ProblemUri::schema(),
"URI identifying this specific problem occurrence.",
),
(
"request_id",
footing::http::RequestId::schema(),
"Request identifier used for log correlation.",
),
] {
let expected = serde_json::to_value(expected).unwrap();
let property = &problem["properties"][field];
assert_eq!(property["description"], description);
let constraints = if let Some(variants) = property["oneOf"]
.as_array()
.or_else(|| property["allOf"].as_array())
{
assert_eq!(
variants.len(),
1,
"{field} must contain only its scalar schema"
);
&variants[0]
} else {
property
};
for (constraint, value) in expected.as_object().unwrap() {
assert_eq!(
&constraints[constraint], value,
"{field}.{constraint}: {property}"
);
}
}
assert!(
!problem["required"]
.as_array()
.unwrap()
.contains(&json!("request_id"))
);
assert!(
!problem["required"]
.as_array()
.unwrap()
.contains(&json!("instance"))
);
let uri = serde_json::to_value(footing::http::ProblemUri::schema()).unwrap();
assert_eq!(uri["format"], "uri-reference");
assert_eq!(uri["minLength"], 0);
}
#[test]
#[cfg(feature = "observability")]
fn public_payload_schemas_compose_and_reusable_problem_responses_resolve() {
#[derive(serde::Serialize, utoipa::ToSchema)]
struct DiagnosticPayload {
code: footing::http::ProblemCode,
problem_type: footing::http::ProblemUri,
request_id: footing::http::RequestId,
traceparent: footing::http::TraceParent,
violations: Vec<FieldViolation>,
health: footing::observability::HealthReport,
}
#[derive(utoipa::OpenApi)]
#[openapi(components(schemas(DiagnosticPayload), responses(ApiProblem)))]
struct Api;
let document = <Api as utoipa::OpenApi>::openapi();
let json = serde_json::to_value(document).unwrap();
assert_refs_resolve(&json, &json);
let schemas = &json["components"]["schemas"];
assert_eq!(schemas["ProblemCode"]["type"], "string");
assert_eq!(
schemas["TraceParent"]["minLength"],
footing::http::TRACEPARENT_LENGTH
);
assert_eq!(
schemas["TraceParent"]["maxLength"],
footing::http::MAX_TRACEPARENT_LENGTH
);
let violations = &schemas["DiagnosticPayload"]["properties"]["violations"];
assert_eq!(violations["type"], "array");
assert_eq!(
violations["items"]["$ref"],
"#/components/schemas/FieldViolation"
);
assert!(
schemas["HealthReport"]["properties"]
.get("checks")
.is_some()
);
let registered = &json["components"]["responses"]["ApiProblem"]["content"]
[PROBLEM_JSON_MEDIA_TYPE]["schema"];
let inline = serde_json::to_value(openapi::problem_response("Invalid request")).unwrap();
assert_eq!(
registered,
&inline["content"][PROBLEM_JSON_MEDIA_TYPE]["schema"]
);
}
#[tokio::test]
#[cfg(feature = "pagination")]
async fn parameter_wrappers_document_locations_and_offset_defaults() {
#[derive(serde::Deserialize, utoipa::IntoParams)]
struct Search {
query: String,
}
let router = Router::new().route(
"/search",
axum::routing::get(|params: footing::http::QueryParams<Search>| async move {
params.into_inner().query
}),
);
let response = router
.oneshot(
Request::get("/search?query=item")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(to_bytes(response.into_body(), 4096).await.unwrap(), "item");
let parameters =
serde_json::to_value(footing::http::QueryParams::<Search>::into_params(|| None)).unwrap();
assert_eq!(parameters[0]["name"], "query");
assert_eq!(parameters[0]["in"], "query");
let parameters =
serde_json::to_value(footing::http::PathParams::<Search>::into_params(|| None)).unwrap();
assert_eq!(parameters[0]["name"], "query");
assert_eq!(parameters[0]["in"], "path");
assert_eq!(parameters[0]["required"], true);
let parameters =
serde_json::to_value(footing::http::OffsetPagination::into_params(|| None)).unwrap();
assert_eq!(parameters[0]["name"], "page");
assert_eq!(parameters[0]["schema"]["default"], 1);
assert_eq!(
parameters[1]["schema"]["default"],
PageLimits::default().default_page_size()
);
}
#[test]
#[cfg(feature = "pagination")]
fn contracts_reject_missing_extra_and_mismatched_routes() {
let (_, document) = api();
let missing: [EndpointContract; 1] = [EndpointContract::new(
EndpointMethod::Post,
EndpointPathPattern::exact("/items"),
)];
assert!(matches!(
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&missing)),
Err(OpenApiContractError::UndocumentedEndpoint { method: "POST", .. })
));
assert!(matches!(
openapi::validate_contracts(&document, &EndpointContractRegistry::<&str>::new(&[])),
Err(OpenApiContractError::OperationWithoutContract { .. })
));
let endpoints = contracts();
let mut extra = document.clone();
extra.paths.paths.get_mut("/items").unwrap().trace = Some(Operation::new());
assert!(matches!(
openapi::validate_contracts(&extra, &EndpointContractRegistry::new(&endpoints)),
Err(OpenApiContractError::OperationWithoutContract {
method: "TRACE",
..
})
));
let duplicate = [endpoints[0].clone(), endpoints[0].clone()];
assert!(matches!(
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&duplicate)),
Err(OpenApiContractError::InvalidContracts(_))
));
extra
.paths
.paths
.insert("/empty".into(), PathItem::default());
extra.paths.paths.get_mut("/items").unwrap().trace = None;
assert!(matches!(
openapi::validate_contracts(&extra, &EndpointContractRegistry::new(&endpoints)),
Err(OpenApiContractError::EmptyPathItem { .. })
));
}
#[test]
fn template_names_and_explicit_methods_must_match() {
let mut document = OpenApi::new(Info::new("test", "1"), Paths::new());
document.paths.paths.insert(
"/items/{id}".into(),
PathItem::new(HttpMethod::Get, Operation::new()),
);
let endpoint = EndpointContract::<&str>::new(
EndpointMethod::Get,
EndpointPathPattern::template("/items/{id}"),
);
openapi::validate_contracts(
&document,
&EndpointContractRegistry::new(std::slice::from_ref(&endpoint)),
)
.unwrap();
let renamed = EndpointContract::<&str>::new(
EndpointMethod::Get,
EndpointPathPattern::template("/items/{key}"),
);
assert!(matches!(
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&[renamed])),
Err(OpenApiContractError::UndocumentedEndpoint { .. })
));
document.paths.paths.get_mut("/items/{id}").unwrap().head = Some(Operation::new());
assert!(matches!(
openapi::validate_contracts(
&document,
&EndpointContractRegistry::new(std::slice::from_ref(&endpoint))
),
Err(OpenApiContractError::OperationWithoutContract { method: "HEAD", .. })
));
}
#[test]
#[cfg(feature = "pagination")]
fn contract_annotation_preserves_business_metadata_and_rejects_conflicts() {
let (_, mut document) = api();
let operation = document
.paths
.paths
.get_mut("/items")
.unwrap()
.get
.as_mut()
.unwrap();
operation
.extensions
.get_or_insert_default()
.insert("x-business".into(), json!({"owner": "inventory"}));
let before = serde_json::to_value(&document).unwrap();
let endpoints = contracts();
let registry = EndpointContractRegistry::new(&endpoints);
let annotated = openapi::annotate_contracts(document, ®istry, str::to_owned).unwrap();
let again = openapi::annotate_contracts(annotated.clone(), ®istry, str::to_owned).unwrap();
let mut after = serde_json::to_value(again).unwrap();
let metadata = after["paths"]["/items"]["get"]
.as_object_mut()
.unwrap()
.remove(openapi::CONTRACT_EXTENSION)
.unwrap();
assert_eq!(
metadata["schema_version"],
footing::http::EndpointContractSnapshot::SCHEMA_VERSION
);
assert_eq!(after, before);
let mut conflicting = annotated;
conflicting
.paths
.paths
.get_mut("/items")
.unwrap()
.get
.as_mut()
.unwrap()
.extensions
.as_mut()
.unwrap()
.insert(
openapi::CONTRACT_EXTENSION.into(),
json!({"schema_version": 999}),
);
assert!(matches!(
openapi::annotate_contracts(conflicting, ®istry, str::to_owned),
Err(OpenApiContractError::ConflictingMetadata { .. })
));
}
#[test]
#[cfg(feature = "pagination")]
fn permissions_are_exported_as_metadata_without_inventing_security_schemes() {
let (_, document) = api();
let endpoint = contracts()[0]
.clone()
.with_auth(footing::http::EndpointAuth::User)
.with_permissions(EndpointPermissions::One("inventory:read"));
let document = openapi::annotate_contracts(
document,
&EndpointContractRegistry::new(std::slice::from_ref(&endpoint)),
str::to_owned,
)
.unwrap();
let json = serde_json::to_value(document).unwrap();
let operation = &json["paths"]["/items"]["get"];
assert_eq!(
operation[openapi::CONTRACT_EXTENSION]["contract"]["permissions"]["values"],
json!(["inventory:read"])
);
assert!(operation.get("security").is_none());
}
#[utoipa::path(post, path = "/items", params(RequiredIdempotencyKey), responses(
(status = 204, description = "Created"),
(status = 400, response = inline(ApiProblem))
))]
#[cfg(feature = "http-stack")]
async fn create_item(_: RequiredIdempotencyKey) -> StatusCode {
StatusCode::NO_CONTENT
}
#[tokio::test]
#[cfg(feature = "http-stack")]
async fn idempotency_contract_rejects_missing_or_optional_headers_before_serving() {
let (router, mut document, _) =
OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route!(create_item).unwrap())
.unwrap()
.into_parts();
let contracts: [EndpointContract; 1] =
[
EndpointContract::new(EndpointMethod::Post, EndpointPathPattern::exact("/items"))
.with_idempotency(IdempotencyRequestPolicy::Required),
];
let registry = EndpointContractRegistry::new(&contracts);
openapi::validate_contracts(&document, ®istry).unwrap();
for (key, status) in [
(None, StatusCode::BAD_REQUEST),
(Some("create-item"), StatusCode::NO_CONTENT),
] {
let mut request = Request::post("/items");
if let Some(key) = key {
request = request.header("idempotency-key", key);
}
let response = router
.clone()
.oneshot(request.body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), status);
}
document
.paths
.paths
.get_mut("/items")
.unwrap()
.post
.as_mut()
.unwrap()
.parameters = None;
assert!(matches!(
openapi::annotate_contracts(document.clone(), ®istry, str::to_owned),
Err(OpenApiContractError::InvalidParameter {
name: "idempotency-key",
reason: "is missing",
..
})
));
document
.paths
.paths
.get_mut("/items")
.unwrap()
.post
.as_mut()
.unwrap()
.parameters = Some(vec![
openapi::idempotency_key_parameter(IdempotencyRequestPolicy::HeaderOptional)
.unwrap()
.into(),
]);
assert!(matches!(
openapi::validate_contracts(&document, ®istry),
Err(OpenApiContractError::InvalidParameter {
reason: "must be required",
..
})
));
let optional = [contracts[0]
.clone()
.with_idempotency(IdempotencyRequestPolicy::HeaderOptional)];
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&optional)).unwrap();
let disabled = [contracts[0]
.clone()
.with_idempotency(IdempotencyRequestPolicy::Disabled)];
assert!(matches!(
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&disabled)),
Err(OpenApiContractError::InvalidParameter { .. })
));
}
#[test]
#[cfg(feature = "http-stack")]
fn contract_parameters_respect_path_inheritance_overrides_and_header_case() {
let (_, mut document, _) =
OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route!(create_item).unwrap())
.unwrap()
.into_parts();
let contracts: [EndpointContract; 1] =
[
EndpointContract::new(EndpointMethod::Post, EndpointPathPattern::exact("/items"))
.with_idempotency(IdempotencyRequestPolicy::Required),
];
let registry = EndpointContractRegistry::new(&contracts);
let item = document.paths.paths.get_mut("/items").unwrap();
item.parameters = item.post.as_mut().unwrap().parameters.take();
inline_parameter_mut(&mut item.parameters.as_mut().unwrap()[0]).name = "Idempotency-Key".into();
openapi::validate_contracts(&document, ®istry).unwrap();
let item = document.paths.paths.get_mut("/items").unwrap();
item.post.as_mut().unwrap().parameters = Some(vec![
openapi::idempotency_key_parameter(IdempotencyRequestPolicy::HeaderOptional)
.unwrap()
.into(),
]);
assert!(matches!(
openapi::validate_contracts(&document, ®istry),
Err(OpenApiContractError::InvalidParameter {
reason: "must be required",
..
})
));
let item = document.paths.paths.get_mut("/items").unwrap();
item.post.as_mut().unwrap().parameters = None;
let mut duplicate = item.parameters.as_ref().unwrap()[0].clone();
inline_parameter_mut(&mut duplicate).name = "IDEMPOTENCY-KEY".into();
item.parameters.as_mut().unwrap().push(duplicate);
assert!(matches!(
openapi::validate_contracts(&document, ®istry),
Err(OpenApiContractError::InvalidParameter {
reason: "is duplicated",
..
})
));
}
#[test]
fn parameter_component_references_preserve_contracts_and_inheritance() {
let contract: EndpointContract =
EndpointContract::new(EndpointMethod::Post, EndpointPathPattern::exact("/items"))
.with_idempotency(IdempotencyRequestPolicy::Required);
for pointer in ["/paths/~1items", "/paths/~1items/post"] {
let mut value = json!({
"openapi": "3.1.0", "info": {"title": "test", "version": "1"},
"paths": {"/items": {"post": {"responses": {}}}},
"components": {"parameters": {
"Alias": {"$ref": "#/components/parameters/Key~1~0"},
"Key/~": {"name": "Idempotency-Key", "in": "header", "required": true,
"description": "Shared request key", "schema": {"type": "string"}}
}}
});
value.pointer_mut(pointer).unwrap()["parameters"] =
json!([{"$ref": "#/components/parameters/Alias"}]);
let document: OpenApi = serde_json::from_value(value).unwrap();
openapi::validate_contracts(
&document,
&EndpointContractRegistry::new(std::slice::from_ref(&contract)),
)
.unwrap();
let route = openapi::OpenApiRoute::from_handler(|| async {}, document)
.unwrap()
.with_contract(|_| contract.policy())
.unwrap();
let (_, document, _) =
OpenApiRouter::<()>::new(OpenApi::new(Info::new("root", "1"), Paths::new()))
.unwrap()
.route(route)
.unwrap()
.into_parts();
let item = &document.paths.paths["/items"];
assert!(item.parameters.is_none());
let parameter =
inline_parameter(&item.post.as_ref().unwrap().parameters.as_ref().unwrap()[0]);
assert_eq!(parameter.name, "Idempotency-Key");
assert_eq!(parameter.description.as_deref(), Some("Shared request key"));
assert!(matches!(parameter.required, Required::True));
}
}
#[test]
fn parameter_component_references_reject_missing_external_and_cyclic_targets() {
let contracts: [EndpointContract; 1] =
[
EndpointContract::new(EndpointMethod::Post, EndpointPathPattern::exact("/items"))
.with_idempotency(IdempotencyRequestPolicy::Required),
];
for (reference, reason) in [
(
"#/components/parameters/Missing",
"references a missing parameter component",
),
(
"other.json#/components/parameters/Key",
"must reference a local parameter component",
),
(
"#/components/parameters/First",
"contains a cyclic parameter reference",
),
] {
let document: OpenApi = serde_json::from_value(json!({
"openapi": "3.1.0", "info": {"title": "test", "version": "1"},
"paths": {"/items": {"post": {
"parameters": [{"$ref": reference}], "responses": {}
}}},
"components": {"parameters": {
"First": {"$ref": "#/components/parameters/Second"},
"Second": {"$ref": "#/components/parameters/First"}
}}
}))
.unwrap();
assert!(matches!(
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&contracts)),
Err(OpenApiContractError::InvalidParameter { reason: actual, .. }) if actual == reason
));
assert!(matches!(
openapi::OpenApiRoute::<()>::from_handler(|| async {}, document),
Err(OpenApiRouteError::InvalidDocument { reason: actual }) if actual == reason
));
}
}
#[tokio::test]
#[cfg(feature = "pagination")]
async fn offset_limits_and_defaults_are_shared_by_document_and_handler() {
let limits = PageLimits::new(4, 8).unwrap();
let (router, document, _) =
OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(
route!(offset)
.unwrap()
.with_offset_pagination(limits)
.unwrap(),
)
.unwrap()
.into_parts();
let contracts: [EndpointContract; 1] =
[
EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/offset"))
.with_pagination(EndpointPagination::Offset),
];
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&contracts)).unwrap();
let json = serde_json::to_value(document).unwrap();
let size = json["paths"]["/offset"]["get"]["parameters"]
.as_array()
.unwrap()
.iter()
.find(|parameter| parameter["name"] == "page_size")
.unwrap();
assert_eq!(size["schema"]["default"], 4);
assert_eq!(size["schema"]["maximum"], 8);
let response = router
.clone()
.oneshot(Request::get("/offset").body(Body::empty()).unwrap())
.await
.unwrap();
let body: Value =
serde_json::from_slice(&to_bytes(response.into_body(), 4096).await.unwrap()).unwrap();
assert_eq!(body["page_size"], 4);
let response = router
.oneshot(
Request::get("/offset?page_size=9")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
let route = route!(offset)
.unwrap()
.with_offset_pagination(limits)
.unwrap();
let result = route.with_cursor_pagination(limits);
assert!(matches!(
result,
Err(OpenApiRouteError::PaginationAlreadyConfigured)
));
let _: Result<openapi::OpenApiRoute<()>, _> = result;
}
#[test]
#[cfg(feature = "pagination")]
fn pagination_contracts_reject_missing_required_and_duplicate_query_parameters() {
let (_, mut document) = api();
let endpoints = contracts();
let registry = EndpointContractRegistry::new(&endpoints);
inline_parameter_mut(
&mut document
.paths
.paths
.get_mut("/items")
.unwrap()
.get
.as_mut()
.unwrap()
.parameters
.as_mut()
.unwrap()[0],
)
.required = Required::True;
assert!(matches!(
openapi::validate_contracts(&document, ®istry),
Err(OpenApiContractError::InvalidParameter {
reason: "must be optional",
..
})
));
inline_parameter_mut(
&mut document
.paths
.paths
.get_mut("/items")
.unwrap()
.get
.as_mut()
.unwrap()
.parameters
.as_mut()
.unwrap()[0],
)
.required = Required::False;
let duplicate = document.paths.paths["/items"]
.get
.as_ref()
.unwrap()
.parameters
.as_ref()
.unwrap()[0]
.clone();
document
.paths
.paths
.get_mut("/items")
.unwrap()
.get
.as_mut()
.unwrap()
.parameters
.as_mut()
.unwrap()
.push(duplicate);
assert!(matches!(
openapi::validate_contracts(&document, ®istry),
Err(OpenApiContractError::InvalidParameter {
reason: "is duplicated",
..
})
));
document
.paths
.paths
.get_mut("/items")
.unwrap()
.get
.as_mut()
.unwrap()
.parameters = None;
assert!(matches!(
openapi::validate_contracts(&document, ®istry),
Err(OpenApiContractError::InvalidParameter {
name: "page_size",
reason: "is missing",
..
})
));
}
#[cfg(feature = "http-stack")]
mod nested_handler {
use super::*;
#[utoipa::path(get, path = "/state/{id}", params(("id" = u32, Path)), responses((status = 200, body = String)))]
pub async fn state(
axum::extract::State(prefix): axum::extract::State<String>,
axum::extract::Path(id): axum::extract::Path<u32>,
) -> String {
format!("{prefix}{id}")
}
}
#[tokio::test]
#[cfg(feature = "http-stack")]
async fn route_registration_keeps_methods_paths_schemas_and_state_together() {
let (router, document, _) =
OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route!(items).unwrap())
.unwrap()
.route(route!(create_item).unwrap())
.unwrap()
.route(route!(other).unwrap())
.unwrap()
.route(route!(nested_handler::state).unwrap())
.unwrap()
.into_parts();
let json = serde_json::to_value(document).unwrap();
assert_refs_resolve(&json, &json);
assert!(json["paths"]["/items"]["get"].is_object());
assert!(json["paths"]["/items"]["post"].is_object());
assert!(json["components"]["schemas"]["OtherItem"].is_object());
let router = router.with_state("item-".to_owned());
let response = router
.clone()
.oneshot(Request::get("/state/42").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
to_bytes(response.into_body(), 4096).await.unwrap(),
"item-42"
);
let response = router
.clone()
.oneshot(
Request::post("/items")
.header("idempotency-key", "new")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
let response = router
.clone()
.oneshot(Request::get("/items").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let response = router
.oneshot(Request::delete("/items").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
}
#[test]
#[cfg(feature = "pagination")]
fn route_registration_rejects_unregistered_paths_duplicate_operations_and_schema_conflicts() {
let (_, document) = api();
assert!(matches!(
OpenApiRouter::<()>::new(document),
Err(OpenApiRouteError::InvalidDocument { .. })
));
let router = OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route!(items).unwrap())
.unwrap();
assert!(matches!(
router.route(route!(items).unwrap()),
Err(OpenApiRouteError::DuplicateOperation { method: "GET", .. })
));
let mut document = OpenApi::new(Info::new("test", "1"), Paths::new());
document.components.get_or_insert_default().schemas.insert(
"Item".into(),
utoipa::openapi::schema::ObjectBuilder::new()
.schema_type(utoipa::openapi::schema::Type::String)
.into(),
);
let router = OpenApiRouter::<()>::new(document).unwrap();
assert!(matches!(
router.route(route!(items).unwrap()),
Err(OpenApiRouteError::ConflictingComponent { kind: "schema", .. })
));
}
fn document_with_path(item: PathItem) -> OpenApi {
let mut document = OpenApi::new(Info::new("test", "1"), Paths::new());
document.paths.paths.insert("/items".into(), item);
document
}
#[tokio::test]
#[cfg(feature = "http-stack")]
async fn module_merge_preserves_state_routes_and_contracts_until_stack_validation() {
use axum::extract::State;
let module = |path: &'static str| {
let base = OpenApi::new(Info::new(path, "1"), Paths::new());
let mut document = base.clone();
document.paths.paths.insert(
path.into(),
PathItem::new(HttpMethod::Get, Operation::new()),
);
OpenApiRouter::<String>::new(base)
.unwrap()
.route(
openapi::OpenApiRoute::from_handler(
move |State(state): State<String>| async move { format!("{state}{path}") },
document,
)
.unwrap()
.with_contract(|_| {
EndpointPolicy::new().with_rate_limit(RateLimitRequestPolicy::Disabled)
})
.unwrap(),
)
.unwrap()
};
let api = OpenApiRouter::new(OpenApi::new(Info::new("Service", "1"), Paths::new()))
.unwrap()
.merge(module("/users"))
.unwrap()
.merge(module("/jobs"))
.unwrap();
assert_eq!(api.contracts().endpoints().len(), 2);
let (app, document) = api.into_parts_with_stack(minimal_stack()).unwrap();
assert_eq!(document.info.title, "Service");
assert_eq!(document.paths.paths.len(), 2);
let app = app.with_state("module:".to_owned());
for path in ["/users", "/jobs"] {
assert!(
document.paths.paths[path]
.get
.as_ref()
.unwrap()
.extensions
.is_none()
);
let response = app
.clone()
.oneshot(Request::get(path).body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
to_bytes(response.into_body(), 1024).await.unwrap(),
format!("module:{path}")
);
}
}
fn module_document(base: Value, path: &str, operation: Value) -> OpenApiRouter {
let base: OpenApi = serde_json::from_value(base).unwrap();
let mut document = OpenApi::new(Info::new("handler", "1"), Paths::new());
document
.paths
.paths
.insert(path.into(), serde_json::from_value(operation).unwrap());
OpenApiRouter::new(base)
.unwrap()
.route(openapi::OpenApiRoute::from_handler(|| async {}, document).unwrap())
.unwrap()
}
#[test]
fn normalization_rejects_references_into_managed_path_metadata_including_base_forward_refs() {
for reference in [
"#/paths/~1items/parameters",
"#/paths/~1items/parameters/0/schema",
"#/paths/~1items/servers/0/variables/version",
"#/paths/~1items/get/parameters",
"#/paths/~1items/get/parameters/0/schema",
"#/paths/~1items/post/parameters/0/content/application~1json/schema",
"#%2Fpaths%2F~1items%2Fparameters%2F0%2Fschema",
"#/%70aths/~1items/%67et/%70arameters/0/schema",
"#/paths/~1items/%73ervers/0/variables/version",
] {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"},
"paths": {}, "components": {"schemas": {"Alias": {"$ref": reference}}}});
assert!(
matches!(
OpenApiRouter::<()>::new(serde_json::from_value(base.clone()).unwrap()),
Err(OpenApiRouteError::InvalidDocument { .. })
),
"accepted base forward reference {reference}"
);
let mut document = base;
document["paths"]["/items"] = json!({
"parameters": [{"name": "filter", "in": "query", "required": false,
"schema": {"type": "string"}}],
"servers": [{"url": "/{version}", "variables": {"version": {
"default": "v1", "enum": ["v1", "v2"]}}}],
"get": {"parameters": [{"name": "page_size", "in": "query", "required": false,
"schema": {"type": "integer"}}], "responses": {}},
"post": {"parameters": [{"name": "page_size", "in": "query", "required": false,
"content": {"application/json": {"schema": {"type": "integer"}}}}], "responses": {}}
});
assert!(
matches!(
openapi::OpenApiRoute::<()>::from_handler(
|| async {},
serde_json::from_value(document).unwrap()
),
Err(OpenApiRouteError::InvalidDocument { .. })
),
"accepted handler reference {reference}"
);
}
}
#[test]
fn normalization_rejects_incoming_metadata_references_but_preserves_receiving_root_references() {
for (reference, pointer) in [
("#/info/x-schema", "/info/x-schema"),
("#/%69nfo/x-schema", "/info/x-schema"),
("#/tags/0/x-schema", "/tags/0/x-schema"),
(
"#/servers/0/variables/version",
"/servers/0/variables/version",
),
("#/security/0", "/security/0"),
] {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1", "x-schema": true},
"paths": {}, "tags": [{"name": "shared", "x-schema": true}],
"servers": [{"url": "/{version}", "variables": {"version": {
"default": "v1", "enum": ["v1", "v2"]}}}], "security": [{"enum": ["item"]}],
"components": {"schemas": {"Alias": {"$ref": reference}}, "securitySchemes": {
"enum": {"type": "oauth2", "flows": {"implicit": {
"authorizationUrl": "https://example.com/authorize", "scopes": {"item": "Item access"}}}}
}}});
let root =
|| OpenApiRouter::<()>::new(serde_json::from_value(base.clone()).unwrap()).unwrap();
let plain = || {
OpenApiRouter::<()>::new(OpenApi::new(Info::new("plain", "1"), Paths::new())).unwrap()
};
let (_, retained, _) = root().into_parts();
assert_eq!(
serde_json::to_value(retained).unwrap().pointer(pointer),
base.pointer(pointer)
);
assert!(
matches!(
plain().merge(root()),
Err(OpenApiRouteError::InvalidDocument { .. })
),
"accepted incoming module reference {reference}"
);
let mut document = base.clone();
document["paths"]["/items"] = json!({"get": {"responses": {}}});
assert!(
matches!(
openapi::OpenApiRoute::<()>::from_handler(
|| async {},
serde_json::from_value(document).unwrap()
),
Err(OpenApiRouteError::InvalidDocument { .. })
),
"accepted incoming handler reference {reference}"
);
let (_, retained, _) = root().merge(plain()).unwrap().into_parts();
assert_eq!(
serde_json::to_value(retained).unwrap().pointer(pointer),
base.pointer(pointer)
);
}
}
#[test]
fn normalization_preserves_stable_reference_targets_and_does_not_scan_user_data() {
let data = json!({"$ref": "#/paths/~1items/get/parameters/0/schema", "operationRef": "#/info/x-schema"});
for (path, reference) in [
("/items", "#/components/schemas/Shared"),
(
"/items",
"#/components/pathItems/Shared/get/parameters/0/schema",
),
(
"/items",
"#/paths/~1items/get/responses/200/content/application~1json/schema/properties/parameters",
),
(
"/parameters",
"#/paths/~1parameters/get/responses/200/content/application~1json/schema",
),
(
"/items",
"#/paths/~1items/get/requestBody/content/application~1json/schema/properties/servers",
),
(
"/items",
"other.json#/paths/~1items/get/parameters/0/schema",
),
("/items", "other.json#/info/x-schema"),
] {
let mut document = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {},
"components": {"schemas": {"Shared": {"type": "string"}}, "pathItems": {"Shared": {
"get": {"parameters": [{"name": "filter", "in": "query", "required": false,
"schema": {"type": "string"}}], "responses": {}}
}}}});
document["paths"][path] = json!({"get": {"x-data": data,
"requestBody": {"content": {"application/json": {"schema": {
"type": "object", "properties": {"servers": {"type": "string"}}}}}},
"responses": {"200": {"description": "OK", "content": {"application/json": {
"schema": {"type": "object", "properties": {"parameters": {"type": "string"}},
"default": data, "example": data, "x-data": data},
"example": data, "examples": {"inline": {"value": data}}}}},
"201": {"description": "Alias", "content": {"application/json": {"schema": {"$ref": reference}}},
"links": {"self": {"operationRef": format!("#/paths/{}/get", path.replace('/', "~1")), "parameters": {}}}}}
}});
let document: OpenApi = serde_json::from_value(document).unwrap();
let expected = serde_json::to_value(&document).unwrap();
let route = openapi::OpenApiRoute::<()>::from_handler(|| async {}, document).unwrap();
let (_, exported, _) =
OpenApiRouter::new(OpenApi::new(Info::new("root", "1"), Paths::new()))
.unwrap()
.route(route)
.unwrap()
.into_parts();
let exported = serde_json::to_value(exported).unwrap();
assert_eq!(
exported["paths"][path]["get"], expected["paths"][path]["get"],
"{reference}"
);
if let Some(pointer) = reference.strip_prefix('#') {
assert_eq!(
exported.pointer(pointer),
expected.pointer(pointer),
"{reference}"
);
assert!(exported.pointer(pointer).is_some(), "{reference}");
}
}
}
#[test]
#[cfg(feature = "pagination")]
fn normalization_prevents_pagination_from_invalidating_parameter_references() {
for (parameter_representation, suffix) in [
(
json!({"content": {"application/json": {"schema": {"type": "integer"}}}}),
"content/application~1json/schema",
),
(
json!({"schema": {"type": "object", "properties": {"limit": {"type": "integer"}}}}),
"schema/properties/limit",
),
] {
let reference = format!("#/paths/~1items/get/parameters/0/{suffix}");
let mut parameter = json!({"name": "page_size", "in": "query", "required": false});
parameter
.as_object_mut()
.unwrap()
.extend(parameter_representation.as_object().unwrap().clone());
let document = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {
"/items": {"get": {"parameters": [parameter], "responses": {"200": {"description": "OK",
"content": {"application/json": {"schema": {"$ref": reference}}}}}}}
}});
assert!(document.pointer(&reference[1..]).is_some());
let result = openapi::OpenApiRoute::<()>::from_handler(
|| async {},
serde_json::from_value(document).unwrap(),
)
.and_then(|route| route.with_offset_pagination(PageLimits::new(10, 100).unwrap()));
assert!(
matches!(result, Err(OpenApiRouteError::InvalidDocument { .. })),
"{reference}"
);
}
}
#[tokio::test]
#[cfg(feature = "http-stack")]
async fn module_nesting_keeps_runtime_paths_contracts_and_route_policies_together() {
use axum::extract::{MatchedPath, OriginalUri, Path, State};
use footing::http::{
HttpMiddlewareSettings, HttpRateLimitSettings, HttpRequestPolicy, HttpRouteRule,
RateLimitKeySourceSettings, TokenBucketRateLimiter,
};
use std::{sync::Arc, time::Duration};
#[utoipa::path(get, path = "/users/{id}", params(("id" = String, Path)),
responses((status = 200, body = String)))]
async fn user(
State(state): State<String>,
Path(id): Path<String>,
path: MatchedPath,
OriginalUri(uri): OriginalUri,
) -> String {
format!("{state}:{id}:{}:{uri}", path.as_str())
}
let document = || OpenApi::new(Info::new("test", "1"), Paths::new());
let api = OpenApiRouter::new(document())
.unwrap()
.nest(
"/api",
OpenApiRouter::new(document())
.unwrap()
.nest(
"/v1",
OpenApiRouter::new(document())
.unwrap()
.route(
route!(user)
.unwrap()
.with_contract(|_| {
EndpointPolicy::new()
.with_rate_limit(RateLimitRequestPolicy::Enabled)
})
.unwrap(),
)
.unwrap(),
)
.unwrap(),
)
.unwrap();
assert_eq!(
api.contracts().endpoints()[0].path().as_str(),
"/api/v1/users/{id}"
);
let mut rate_limit = HttpRateLimitSettings::default();
rate_limit.enabled = true;
rate_limit.capacity = 1;
rate_limit.refill_interval = Duration::from_secs(3600);
rate_limit.key_source = RateLimitKeySourceSettings::Fixed("test".into());
let policy = HttpRequestPolicy::default()
.with_default_rate_limit(RateLimitRequestPolicy::Disabled)
.with_rule(
HttpRouteRule::exact("/api/v1/users/{id}")
.unwrap()
.rate_limit(RateLimitRequestPolicy::Enabled),
);
let config = HttpMiddlewareSettings::new()
.with_rate_limit(rate_limit)
.with_request_policy(policy.into())
.build()
.unwrap();
let limiter = config.rate_limit().unwrap().limiter_config();
let stack = HttpMiddlewareStack::builder(config)
.with_rate_limit_store(Arc::new(TokenBucketRateLimiter::new(limiter)))
.build()
.unwrap();
let (app, spec) = api.into_parts_with_stack(stack).unwrap();
let app = app.with_state("state".to_owned());
assert_eq!(spec.paths.paths.len(), 1);
let operation = spec.paths.paths["/api/v1/users/{id}"].get.as_ref().unwrap();
assert_eq!(operation.operation_id.as_deref(), Some("user"));
assert!(operation.extensions.is_none());
let request = || {
Request::get("/api/v1/users/42?full=true")
.body(Body::empty())
.unwrap()
};
let response = app.clone().oneshot(request()).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
to_bytes(response.into_body(), 1024).await.unwrap(),
"state:42:/api/v1/users/{id}:/api/v1/users/42?full=true"
);
assert_eq!(
app.oneshot(request()).await.unwrap().status(),
StatusCode::TOO_MANY_REQUESTS
);
}
#[tokio::test]
async fn nesting_preserves_axum_root_and_trailing_slash_semantics() {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {}});
let operation = json!({"get": {"responses": {}}});
for (path, mounted, missing) in [
("/", "/api", "/api/"),
("/users/", "/api/users/", "/api/users"),
("/users//list", "/api/users//list", "/api/users/list"),
] {
let module = module_document(base.clone(), path, operation.clone());
let (app, spec, _) = OpenApiRouter::new(serde_json::from_value(base.clone()).unwrap())
.unwrap()
.nest("/api", module)
.unwrap()
.into_parts();
assert!(spec.paths.paths.contains_key(mounted));
for (path, expected) in [(mounted, StatusCode::OK), (missing, StatusCode::NOT_FOUND)] {
assert_eq!(
app.clone()
.oneshot(Request::get(path).body(Body::empty()).unwrap())
.await
.unwrap()
.status(),
expected
);
}
}
}
#[test]
fn nesting_rejects_ambiguous_prefixes_and_preserves_merge_checks() {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {}});
let operation = json!({"get": {"operationId": "users", "responses": {}}});
for prefix in [
"",
"/",
"api",
"/api/",
"/api//v1",
"/./api",
"/api/../v1",
"/{tenant}",
"/api/*tail",
"/:legacy",
"/api%2fv1",
"/api?query",
"/api#fragment",
] {
let root = OpenApiRouter::<()>::new(serde_json::from_value(base.clone()).unwrap()).unwrap();
assert!(
matches!(
root.nest(
prefix,
module_document(base.clone(), "/users", operation.clone())
),
Err(OpenApiRouteError::InvalidPrefix)
),
"{prefix}"
);
}
assert!(matches!(
module_document(base.clone(), "/api/users", operation.clone()).nest(
"/api",
module_document(base.clone(), "/users", operation.clone())
),
Err(OpenApiRouteError::DuplicateOperation { .. })
));
assert!(matches!(
module_document(base.clone(), "/other", operation.clone())
.nest("/api", module_document(base, "/users", operation)),
Err(OpenApiRouteError::DuplicateOperationId { .. })
));
}
#[test]
fn nesting_rejects_local_path_links_and_response_references() {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {}});
for reference in [
"#/paths/~1users/get",
"#%2Fpaths%2F~1users/get",
"#/%70aths/~1users/get",
] {
let mut link = serde_json::to_value(
utoipa::openapi::link::LinkBuilder::new()
.operation_ref(reference)
.build(),
)
.unwrap();
link["parameters"] = json!({});
for operation in [
json!({"get": {"responses": {"200": {"description": "ok",
"links": {"self": link}}}}}),
json!({"get": {"responses": {"200": {"description": "ok"},
"201": {"$ref": format!("{reference}/responses/200")}}}}),
] {
let module = module_document(base.clone(), "/users", operation);
let root =
OpenApiRouter::<()>::new(serde_json::from_value(base.clone()).unwrap()).unwrap();
assert!(
matches!(root.nest("/api", module),
Err(OpenApiRouteError::InvalidDocument { reason })
if reason.contains("local paths")),
"{reference}"
);
}
}
}
#[test]
fn nesting_checks_local_refs_inside_components_and_nested_schemas() {
let reference = "#/paths/~1users/get/responses/200/content/application~1json/schema";
for schema in [
json!({"$ref": reference}),
json!({"type": "array", "items": {"$ref": reference}}),
json!({"type": "array", "items": false, "prefixItems": [{"type": "object",
"properties": {"child": {"$ref": reference}}}]}),
json!({"type": "object", "additionalProperties": {"$ref": reference}}),
json!({"type": "object", "propertyNames": {"oneOf": [{"$ref": reference}]}}),
json!({"oneOf": [{"$ref": reference}]}),
json!({"allOf": [{"$ref": reference}]}),
json!({"anyOf": [{"$ref": reference}]}),
json!({"oneOf": [{"type": "string"}], "discriminator": {
"propertyName": "kind", "mapping": {"value": reference}}}),
] {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"},
"paths": {}, "components": {"schemas": {"Nested": schema}}});
let operation = json!({"get": {"responses": {"200": {"description": "ok",
"content": {"application/json": {"schema": {"type": "string"}}}}}}});
let module = module_document(base, "/users", operation);
let root =
OpenApiRouter::<()>::new(OpenApi::new(Info::new("root", "1"), Paths::new())).unwrap();
assert!(
matches!(root.nest("/api", module),
Err(OpenApiRouteError::InvalidDocument { reason }) if reason.contains("local paths")),
"{schema}"
);
}
}
#[test]
fn nesting_keeps_component_external_and_user_data_references_unchanged() {
let data = json!({"$ref": "#/paths/~1users/get", "operationRef": "#/paths/~1users/get"});
let by_id = utoipa::openapi::link::LinkBuilder::new()
.operation_id("users")
.parameter("data", data.clone())
.request_body(Some(data.clone()))
.build();
let mut external = serde_json::to_value(
utoipa::openapi::link::LinkBuilder::new()
.operation_ref("other.json#/paths/~1users/get")
.build(),
)
.unwrap();
external["parameters"] = json!({});
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"},
"paths": {}, "components": {"schemas": {"Shared": {"type": "object",
"example": data, "default": data, "x-data": data}}}});
let operation = json!({"get": {"operationId": "users", "x-data": data,
"responses": {"200": {"description": "ok", "links": {
"byId": by_id,
"external": external},
"content": {"application/json": {
"schema": {"$ref": "#/%63omponents/schemas/Sh%61red"},
"example": data, "examples": {"inline": {"value": data},
"external": {"$ref": "other.json#/paths/~1users/get"}}}}}}}});
let module = module_document(base, "/users", operation);
let root =
OpenApiRouter::<()>::new(OpenApi::new(Info::new("root", "1"), Paths::new())).unwrap();
let (_, spec, _) = root.nest("/api", module).unwrap().into_parts();
let spec = serde_json::to_value(spec).unwrap();
let operation = &spec["paths"]["/api/users"]["get"];
assert_eq!(operation["x-data"], data);
assert_eq!(
operation["responses"]["200"]["content"]["application/json"]["example"],
data
);
assert_eq!(
operation["responses"]["200"]["content"]["application/json"]["examples"]["inline"]["value"],
data
);
assert_eq!(
operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],
"#/%63omponents/schemas/Sh%61red"
);
assert_eq!(
operation["responses"]["200"]["links"]["byId"]["parameters"]["data"],
data
);
assert_eq!(
operation["responses"]["200"]["links"]["external"],
serde_json::to_value(
utoipa::openapi::link::LinkBuilder::new()
.operation_ref("other.json#/paths/~1users/get")
.build()
)
.unwrap()
);
assert_eq!(spec["components"]["schemas"]["Shared"]["example"], data);
assert_eq!(spec["components"]["schemas"]["Shared"]["default"], data);
}
#[test]
#[cfg(feature = "http-stack")]
fn nesting_updates_existing_footing_metadata_without_losing_other_metadata() {
let contract = EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::exact("/items"))
.with_rate_limit(RateLimitRequestPolicy::Disabled);
let base = || OpenApi::new(Info::new("test", "1"), Paths::new());
let mut document = base();
document.paths.paths.insert(
"/items".into(),
serde_json::from_value(json!({"get": {
"responses": {}, "security": [{"module-auth": []}],
"servers": [{"url": "https://example.com"}], "x-business": {"path": "/items"}
}}))
.unwrap(),
);
let document = openapi::annotate_contracts(
document,
&EndpointContractRegistry::new(std::slice::from_ref(&contract)),
str::to_owned,
)
.unwrap();
let module = OpenApiRouter::new(base())
.unwrap()
.route(
openapi::OpenApiRoute::from_handler(|| async {}, document)
.unwrap()
.with_contract(|_| contract.policy())
.unwrap(),
)
.unwrap();
let (_, spec) = OpenApiRouter::<()>::new(base())
.unwrap()
.nest("/v1", module)
.unwrap()
.into_parts_with_stack(minimal_stack())
.unwrap();
let operation = serde_json::to_value(&spec.paths.paths["/v1/items"].get).unwrap();
assert_eq!(
operation[openapi::CONTRACT_EXTENSION]["contract"]["path"],
"/v1/items"
);
assert_eq!(operation["security"], json!([{"module-auth": []}]));
assert_eq!(
operation["servers"],
json!([{"url": "https://example.com"}])
);
assert_eq!(operation["x-business"], json!({"path": "/items"}));
}
#[test]
fn module_merge_keeps_each_documents_security_and_server_inheritance() {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {}});
let security_values = [None, Some(json!([])), Some(json!([{"auth": ["read"]}]))];
let server_values = [None, Some(json!([])), Some(json!([{"url": "/api"}]))];
for left_security in &security_values {
for right_security in &security_values {
for left_servers in &server_values {
for right_servers in &server_values {
let configure = |security: &Option<Value>, servers: &Option<Value>| {
let mut value = base.clone();
if let Some(security) = security {
value["security"] = security.clone();
}
if let Some(servers) = servers {
value["servers"] = servers.clone();
}
value
};
let left = module_document(
configure(left_security, left_servers),
"/left",
json!({"get": {"responses": {}}}),
);
let right = module_document(
configure(right_security, right_servers),
"/right",
json!({"get": {"responses": {}}, "post": {"responses": {}, "security": [], "servers": []}}),
);
let (_, document, _) = left.merge(right).unwrap().into_parts();
let json = serde_json::to_value(document).unwrap();
assert_eq!(json.get("security"), left_security.as_ref());
assert_eq!(json.get("servers"), left_servers.as_ref());
let left = &json["paths"]["/left"]["get"];
assert!(left.get("security").is_none());
assert!(left.get("servers").is_none());
let right = &json["paths"]["/right"];
assert_eq!(
right["get"]["security"],
right_security.clone().unwrap_or(json!([]))
);
assert_eq!(
right["get"]["servers"],
right_servers.clone().unwrap_or(json!([{"url": "/"}]))
);
assert_eq!(right["post"]["security"], json!([]));
assert_eq!(right["post"]["servers"], json!([]));
}
}
}
}
}
#[tokio::test]
async fn nested_module_merges_keep_shared_paths_and_new_routes_use_root_defaults() {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {}});
let mut module_base = base.clone();
module_base["security"] = json!([{"module-auth": []}]);
module_base["servers"] = json!([{"url": "/module"}]);
let get = module_document(module_base, "/items", json!({"get": {"responses": {}}}));
let post = module_document(base.clone(), "/items", json!({"post": {"responses": {}}}));
let mut root = base;
root["security"] = json!([{"root-auth": []}]);
root["servers"] = json!([{"url": "/root"}]);
let (app, document, _) = OpenApiRouter::new(serde_json::from_value(root).unwrap())
.unwrap()
.merge(get.merge(post).unwrap())
.unwrap()
.route(
openapi::OpenApiRoute::from_handler(
|| async {},
document_with_path(
serde_json::from_value(json!({"put": {"responses": {}}})).unwrap(),
),
)
.unwrap(),
)
.unwrap()
.into_parts();
let document = serde_json::to_value(document).unwrap();
let path = &document["paths"]["/items"];
assert_eq!(path["get"]["security"], json!([{"module-auth": []}]));
assert_eq!(path["get"]["servers"], json!([{"url": "/module"}]));
assert_eq!(path["post"]["security"], json!([]));
assert_eq!(path["post"]["servers"], json!([{"url": "/"}]));
assert!(path["put"].get("security").is_none());
assert!(path["put"].get("servers").is_none());
assert_eq!(document["security"], json!([{"root-auth": []}]));
assert_eq!(document["servers"], json!([{"url": "/root"}]));
for method in [
axum::http::Method::GET,
axum::http::Method::POST,
axum::http::Method::PUT,
] {
let response = app
.clone()
.oneshot(
Request::builder()
.method(method)
.uri("/items")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}
#[test]
fn module_merge_reuses_operation_component_and_path_conflict_checks() {
let base = json!({"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {}});
let get = json!({"get": {"responses": {}, "operationId": "list"}});
assert!(matches!(
module_document(base.clone(), "/items", get.clone()).merge(module_document(
base.clone(),
"/items",
get.clone()
)),
Err(OpenApiRouteError::DuplicateOperation { .. })
));
assert!(matches!(
module_document(base.clone(), "/items", get.clone()).merge(module_document(
base.clone(),
"/other",
get
)),
Err(OpenApiRouteError::DuplicateOperationId { .. })
));
for field in ["summary", "description", "x-owner"] {
let mut left = json!({"get": {"responses": {}}});
let mut right = json!({"post": {"responses": {}}});
left[field] = json!("left");
right[field] = json!("right");
assert!(matches!(
module_document(base.clone(), "/items", left).merge(module_document(
base.clone(),
"/items",
right
)),
Err(OpenApiRouteError::ConflictingPathMetadata { .. })
));
}
for (kind, left, right) in [
(
"schemas",
json!({"type": "string"}),
json!({"type": "integer"}),
),
(
"responses",
json!({"description": "left"}),
json!({"description": "right"}),
),
(
"parameters",
json!({"name": "left", "in": "query", "required": false}),
json!({"name": "right", "in": "query", "required": false}),
),
(
"requestBodies",
json!({"description": "left", "content": {}}),
json!({"description": "right", "content": {}}),
),
(
"headers",
json!({"description": "left"}),
json!({"description": "right"}),
),
(
"examples",
json!({"value": "left"}),
json!({"value": "right"}),
),
(
"links",
json!({"operationId": "left", "parameters": {}}),
json!({"operationId": "right", "parameters": {}}),
),
(
"callbacks",
json!({"{$request.query.url}": {"post": {"responses": {}, "security": [], "servers": [{"url": "/"}]}}}),
json!({"{$request.query.url}": {"put": {"responses": {}, "security": [], "servers": [{"url": "/"}]}}}),
),
(
"pathItems",
json!({"summary": "left"}),
json!({"summary": "right"}),
),
(
"mediaTypes",
json!({"schema": {"type": "string"}}),
json!({"schema": {"type": "integer"}}),
),
(
"securitySchemes",
json!({"type": "http", "scheme": "basic"}),
json!({"type": "http", "scheme": "bearer"}),
),
] {
let mut first = base.clone();
let mut second = base.clone();
first["components"] = json!({(kind): {"Shared": left}});
second["components"] = json!({(kind): {"Shared": right}});
let expected: OpenApi = serde_json::from_value(first.clone())
.unwrap_or_else(|error| panic!("invalid {kind} fixture: {error}"));
let (_, merged, _) =
OpenApiRouter::<()>::new(serde_json::from_value(base.clone()).unwrap())
.unwrap()
.merge(OpenApiRouter::new(expected.clone()).unwrap())
.unwrap()
.merge(OpenApiRouter::new(expected.clone()).unwrap())
.unwrap()
.into_parts();
assert_eq!(
serde_json::to_value(merged).unwrap()["components"][kind],
serde_json::to_value(expected).unwrap()["components"][kind],
"{kind} must survive merging and deduplication"
);
let first = OpenApiRouter::<()>::new(serde_json::from_value(first).unwrap()).unwrap();
let second = OpenApiRouter::new(serde_json::from_value(second).unwrap()).unwrap();
assert!(matches!(
first.merge(second),
Err(OpenApiRouteError::ConflictingComponent { .. })
));
}
}
#[test]
fn module_metadata_merges_without_silent_conflicts_or_lost_extensions() {
let base = json!({"openapi": "3.1.0", "info": {"title": "root", "version": "1"}, "paths": {}});
let make = |mut value: Value| {
let paths_extension = value["paths"].as_object_mut().unwrap().remove("x-paths");
let mut document: OpenApi = serde_json::from_value(value).unwrap();
document.paths.extensions =
paths_extension.map(|value| [("x-paths", value)].into_iter().collect());
OpenApiRouter::<()>::new(document).unwrap()
};
let mut incoming = base.clone();
incoming["info"]["title"] = json!("module");
incoming["tags"] = json!([{"name": "users", "description": "Users"}]);
incoming["externalDocs"] = json!({"url": "https://example.com/docs"});
incoming["x-module"] = json!(true);
incoming["paths"]["x-paths"] = json!(true);
incoming["components"] = json!({"x-components": true});
incoming["jsonSchemaDialect"] = json!("https://example.com/dialect");
incoming["$self"] = json!("https://example.com/openapi.json");
incoming["webhooks"] = json!({"created": {"post": {
"responses": {}, "security": [], "servers": [{"url": "/"}]
}}});
let mut compatible = base.clone();
compatible["jsonSchemaDialect"] = incoming["jsonSchemaDialect"].clone();
compatible["$self"] = incoming["$self"].clone();
let merged = make(compatible)
.merge(make(incoming.clone()))
.unwrap()
.merge(make(incoming.clone()))
.unwrap();
let (_, document, _) = merged.into_parts();
let json = serde_json::to_value(document).unwrap();
assert_eq!(json["info"]["title"], "root");
assert_eq!(json["tags"].as_array().unwrap().len(), 1);
for pointer in [
"/externalDocs/url",
"/x-module",
"/paths/x-paths",
"/components/x-components",
"/jsonSchemaDialect",
"/$self",
"/webhooks/created",
] {
assert_eq!(json.pointer(pointer), incoming.pointer(pointer));
}
for (pointer, value) in [
("/externalDocs/url", json!("https://example.com/other")),
("/x-module", json!(false)),
("/paths/x-paths", json!(false)),
("/components/x-components", json!(false)),
(
"/jsonSchemaDialect",
json!("https://example.com/other-dialect"),
),
("/$self", json!("https://example.com/other.json")),
] {
let mut conflicting = incoming.clone();
*conflicting.pointer_mut(pointer).unwrap() = value;
assert!(matches!(
make(incoming.clone()).merge(make(conflicting)),
Err(OpenApiRouteError::ConflictingDocumentMetadata { .. })
));
}
let mut conflicting = incoming.clone();
conflicting["webhooks"]["created"]["post"]["description"] = json!("Different webhook");
assert!(matches!(
make(incoming.clone()).merge(make(conflicting)),
Err(OpenApiRouteError::ConflictingComponent {
kind: "webhook",
..
})
));
let mut conflicting = incoming.clone();
conflicting["tags"][0]["description"] = json!("Different users");
assert!(matches!(
make(incoming).merge(make(conflicting)),
Err(OpenApiRouteError::ConflictingTag { .. })
));
for schema in [
"https://spec.openapis.org/oas/3.1/dialect/base",
"https://example.com/schema",
] {
let mut explicit = base.clone();
explicit["$schema"] = json!(schema);
for (left, right) in [
(base.clone(), explicit.clone()),
(explicit.clone(), base.clone()),
] {
assert!(matches!(
make(left).merge(make(right)),
Err(OpenApiRouteError::ConflictingDocumentMetadata { field: "$schema" })
));
}
let (_, document, _) = make(explicit.clone())
.merge(make(explicit))
.unwrap()
.into_parts();
let document = serde_json::to_value(document).unwrap();
assert_eq!(document["$schema"], schema);
assert!(document.get("jsonSchemaDialect").is_none());
}
}
#[test]
fn route_registration_requires_unique_case_sensitive_operation_ids() {
use footing::result::ClassifyError as _;
let get = json!({"get": {"responses": {}, "operationId": "list"}});
for (path, item, duplicate_id) in [
(
"/items",
json!({"post": {"responses": {}, "operationId": "list"}}),
Some("list"),
),
("/other", get.clone(), Some("list")),
(
"/other",
json!({
"get": {"responses": {}, "operationId": "other"},
"post": {"responses": {}, "operationId": "other"}
}),
Some("other"),
),
(
"/items",
json!({"post": {"responses": {}, "operationId": "List"}}),
None,
),
] {
let mut document = OpenApi::new(Info::new("test", "1"), Paths::new());
document
.paths
.paths
.insert(path.into(), serde_json::from_value(item).unwrap());
let router = OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(
openapi::OpenApiRoute::from_handler(
|| async {},
document_with_path(serde_json::from_value(get.clone()).unwrap()),
)
.unwrap(),
)
.unwrap();
let result =
router.route(openapi::OpenApiRoute::from_handler(|| async {}, document).unwrap());
if let Some(expected_id) = duplicate_id {
let error = result.unwrap_err();
assert_eq!(error.error_code(), "openapi_duplicate_operation_id");
assert!(error.to_string().contains(expected_id));
assert!(error.to_string().contains("#[utoipa::path(operation_id"));
assert!(matches!(
error,
OpenApiRouteError::DuplicateOperationId { operation_id } if operation_id == expected_id
));
} else {
let (_, document, _) = result.unwrap().into_parts();
let item = &document.paths.paths["/items"];
assert_eq!(
item.get.as_ref().unwrap().operation_id.as_deref(),
Some("list")
);
assert_eq!(
item.post.as_ref().unwrap().operation_id.as_deref(),
Some("List")
);
}
}
}
#[test]
fn route_document_defaults_do_not_change_other_routes_security_or_servers() {
let base: OpenApi = serde_json::from_value(json!({
"openapi": "3.1.0", "info": {"title": "test", "version": "1"}, "paths": {},
"security": [{"base-auth": []}], "servers": [{"url": "/base"}]
}))
.unwrap();
let mut get =
document_with_path(serde_json::from_value(json!({"get": {"responses": {}}})).unwrap());
get.security = Some(serde_json::from_value(json!([{"get-auth": ["read"]}])).unwrap());
get.servers = Some(serde_json::from_value(json!([{"url": "/get"}])).unwrap());
let mut post = document_with_path(
serde_json::from_value(json!({
"servers": [{"url": "/post"}], "post": {"responses": {}, "security": []}
}))
.unwrap(),
);
post.security = get.security.clone();
post.servers = get.servers.clone();
let put =
document_with_path(serde_json::from_value(json!({"put": {"responses": {}}})).unwrap());
for documents in [[get.clone(), post.clone(), put.clone()], [put, post, get]] {
let mut router = OpenApiRouter::<()>::new(base.clone()).unwrap();
for document in documents {
router = router
.route(openapi::OpenApiRoute::from_handler(|| async {}, document).unwrap())
.unwrap();
}
let (_, document, _) = router.into_parts();
let json = serde_json::to_value(document).unwrap();
assert_eq!(json["security"], json!([{"base-auth": []}]));
assert_eq!(json["servers"], json!([{"url": "/base"}]));
let path = &json["paths"]["/items"];
assert_eq!(path["get"]["security"], json!([{"get-auth": ["read"]}]));
assert_eq!(path["get"]["servers"], json!([{"url": "/get"}]));
assert_eq!(path["post"]["security"], json!([]));
assert_eq!(path["post"]["servers"], json!([{"url": "/post"}]));
assert!(path["put"].get("security").is_none());
assert!(path["put"].get("servers").is_none());
}
}
#[tokio::test]
async fn shared_paths_preserve_each_operations_inherited_parameters_and_servers() {
let get: PathItem = serde_json::from_value(json!({
"servers": [{"url": "/get-server"}],
"parameters": [
{"name": "x-get", "in": "header", "required": true},
{"name": "x-shared", "in": "header", "required": true},
{"name": "Filter", "in": "query", "required": false}
],
"get": {"responses": {}, "parameters": [
{"name": "X-Shared", "in": "header", "required": false},
{"name": "filter", "in": "query", "required": false}
]}
}))
.unwrap();
let post: PathItem = serde_json::from_value(json!({
"servers": [{"url": "/post-path-server"}],
"parameters": [{"name": "x-post", "in": "header", "required": true}],
"post": {"responses": {}, "servers": []}
}))
.unwrap();
for paths in [[get.clone(), post.clone()], [post.clone(), get.clone()]] {
let mut api =
OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new())).unwrap();
for item in paths {
api = api
.route(
openapi::OpenApiRoute::from_handler(
|| async { "ok" },
document_with_path(item),
)
.unwrap(),
)
.unwrap();
}
let (router, document, _) = api.into_parts();
let path = &document.paths.paths["/items"];
assert!(path.parameters.is_none());
assert!(path.servers.is_none());
let get = path.get.as_ref().unwrap();
let parameters: Vec<_> = get
.parameters
.as_ref()
.unwrap()
.iter()
.map(inline_parameter)
.collect();
assert_eq!(parameters.len(), 4);
assert_eq!(parameters[0].name, "X-Shared");
assert!(matches!(parameters[0].required, Required::False));
assert!(parameters.iter().any(|parameter| parameter.name == "x-get"));
assert!(
parameters
.iter()
.any(|parameter| parameter.name == "Filter")
);
assert_eq!(get.servers.as_ref().unwrap()[0].url, "/get-server");
let post = path.post.as_ref().unwrap();
assert_eq!(post.parameters.as_ref().unwrap().len(), 1);
assert_eq!(
inline_parameter(&post.parameters.as_ref().unwrap()[0]).name,
"x-post"
);
assert!(post.servers.as_ref().unwrap().is_empty());
for method in [axum::http::Method::GET, axum::http::Method::POST] {
assert_eq!(
router
.clone()
.oneshot(
Request::builder()
.method(method)
.uri("/items")
.body(Body::empty())
.unwrap()
)
.await
.unwrap()
.status(),
StatusCode::OK
);
}
}
}
#[test]
fn shared_path_metadata_is_retained_or_rejected_on_conflict() {
for field in ["summary", "description", "x-owner"] {
for first in [None, Some("same"), Some("different")] {
let mut get = json!({"get": {"responses": {}}});
if let Some(value) = first {
get[field] = json!(value);
}
let mut post = json!({"post": {"responses": {}}});
post[field] = json!("same");
for paths in [[get.clone(), post.clone()], [post.clone(), get.clone()]] {
let mut result =
OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new()));
for item in paths {
result = result.and_then(|router| {
router.route(
openapi::OpenApiRoute::from_handler(
|| async {},
document_with_path(serde_json::from_value(item).unwrap()),
)
.unwrap(),
)
});
}
if first == Some("different") {
let error = result.unwrap_err();
assert!(
matches!(error, OpenApiRouteError::ConflictingPathMetadata { field: actual, ref path } if actual == if field == "x-owner" { "extensions" } else { field } && path == "/items")
);
} else {
let (_, document, _) = result.unwrap().into_parts();
assert_eq!(
serde_json::to_value(document).unwrap()["paths"]["/items"][field],
"same"
);
}
}
}
}
}
#[test]
fn path_extensions_merge_by_key_and_duplicate_parameters_are_rejected() {
let get = json!({"get": {"responses": {}}, "x-get": "get"});
let post = json!({"post": {"responses": {}}, "x-post": "post"});
for paths in [[get.clone(), post.clone()], [post.clone(), get.clone()]] {
let mut router =
OpenApiRouter::<()>::new(OpenApi::new(Info::new("test", "1"), Paths::new())).unwrap();
for item in paths {
router = router
.route(
openapi::OpenApiRoute::from_handler(
|| async {},
document_with_path(serde_json::from_value(item).unwrap()),
)
.unwrap(),
)
.unwrap();
}
let (_, document, _) = router.into_parts();
let extensions = document.paths.paths["/items"].extensions.as_ref().unwrap();
assert_eq!(extensions["x-get"], "get");
assert_eq!(extensions["x-post"], "post");
}
for parameters in [
json!([
{"name": "x-key", "in": "header", "required": true},
{"name": "X-Key", "in": "header", "required": false}
]),
json!([
{"name": "page_size", "in": "query", "required": false, "schema": {"type": "integer", "maximum": 10}},
{"name": "page_size", "in": "query", "required": false, "schema": {"type": "integer", "maximum": 100}}
]),
] {
for operation_level in [false, true] {
let mut item = json!({"get": {"responses": {}}});
let target = if operation_level {
&mut item["get"]
} else {
&mut item
};
target["parameters"] = parameters.clone();
let invalid = serde_json::from_value(item).unwrap();
assert!(matches!(
openapi::OpenApiRoute::<()>::from_handler(|| async {}, document_with_path(invalid)),
Err(OpenApiRouteError::InvalidDocument { .. })
));
}
}
}