#![cfg(feature = "openapi")]
use axum::{
Json, Router,
body::{Body, to_bytes},
http::{Request, StatusCode},
};
use footing::{
http::{
ApiProblem, CursorPagination, EndpointAuth, EndpointContract, EndpointContractRegistry,
EndpointMethod, EndpointPagination, EndpointPathPattern, EndpointPermissions,
FieldViolation, FieldViolations, HttpMiddlewareConfig, HttpMiddlewareError,
HttpMiddlewareStack, IdempotencyRequestPolicy, ProblemDetails, RateLimitRequestPolicy,
RequiredIdempotencyKey,
error::PROBLEM_JSON_MEDIA_TYPE,
openapi::{self, OpenApiContractError, OpenApiRouteError, OpenApiRouter, route, utoipa},
},
pagination::{CursorPage, OffsetPage, PageLimits},
};
use serde_json::{Value, json};
use tower::ServiceExt;
use utoipa::{
IntoParams, PartialSchema, ToSchema,
openapi::{
Info, OpenApi, Required,
path::{HttpMethod, Operation, PathItem, Paths},
},
};
#[derive(serde::Serialize, ToSchema)]
struct Item {
id: u64,
}
#[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))
))]
async fn items(page: CursorPagination) -> Result<Json<CursorPage<Item>>, ApiProblem> {
CursorPage::new(vec![], page.page_size(), None, false, None)
.map(Json)
.map_err(|_| ApiProblem::internal_error())
}
#[utoipa::path(get, path = "/other", responses((status = 200, body = CursorPage<OtherItem>)))]
async fn other() -> Json<CursorPage<OtherItem>> {
Json(CursorPage::new(vec![], 10, None, false, None).unwrap())
}
#[utoipa::path(get, path = "/offset", params(footing::http::OffsetPagination), responses((status = 200, body = OffsetPage<Item>)))]
async fn offset(page: footing::http::OffsetPagination) -> Json<OffsetPage<Item>> {
Json(OffsetPage::new(vec![], page.page(), page.page_size(), 0).unwrap())
}
fn contracts() -> [EndpointContract; 1] {
[
EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Exact("/items"))
.with_pagination(EndpointPagination::Cursor),
]
}
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 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);
}
}
_ => {}
}
}
fn minimal_stack() -> HttpMiddlewareStack {
HttpMiddlewareStack::builder(HttpMiddlewareConfig::minimal())
.build()
.unwrap()
}
#[tokio::test]
async fn attached_contracts_validate_runtime_policies_and_annotate_registered_routes() {
let contract = contracts()[0].with_rate_limit(RateLimitRequestPolicy::Disabled);
let api = OpenApiRouter::new(OpenApi::new(Info::new("test", "1"), Paths::new()))
.unwrap()
.route(route!(items).unwrap().with_contract(contract).unwrap())
.unwrap();
assert_eq!(api.contracts().endpoints(), &[contract]);
let (router, document) = api
.into_parts_with_stack(minimal_stack(), 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]
fn attached_contracts_reject_path_mismatch_and_missing_runtime_requirements() {
let wrong: EndpointContract =
EndpointContract::new(EndpointMethod::Get, EndpointPathPattern::Exact("/wrong"));
let route: openapi::OpenApiRoute = route!(items).unwrap();
assert!(matches!(
route.with_contract(wrong),
Err(OpenApiRouteError::InvalidContracts(
OpenApiContractError::UndocumentedEndpoint { .. }
))
));
for (contract, expected) in [
(contracts()[0], "rate_limit"),
(
contracts()[0]
.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).unwrap())
.unwrap()
.into_parts_with_stack(minimal_stack(), str::to_owned);
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)
.unwrap(),
)
.unwrap()
.into_parts_with_stack(minimal_stack(), str::to_owned);
assert!(matches!(
result,
Err(OpenApiRouteError::InvalidMiddleware(
HttpMiddlewareError::EndpointContractIdempotencyMismatch { .. }
))
));
}
#[test]
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(), str::to_owned);
assert!(matches!(
result,
Err(OpenApiRouteError::InvalidContracts(
OpenApiContractError::OperationWithoutContract { .. }
))
));
}
#[test]
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).unwrap())
.unwrap()
.into_parts();
assert_eq!(attached, vec![contract]);
}
#[tokio::test]
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, "has_more": false, "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!(
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]
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]
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]
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]
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 = FieldViolations::from_vec(vec![violation]);
assert!(serde_json::to_value(violations).unwrap().is_array());
assert_eq!(
serde_json::to_value(FieldViolations::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();
for (field, expected) in [
("code", footing::http::ProblemCode::schema()),
("type", footing::http::ProblemType::schema()),
("request_id", footing::http::RequestId::schema()),
] {
let expected = serde_json::to_value(expected).unwrap();
let property = &problem["properties"][field];
let constraints = if let Some(variants) = property["oneOf"].as_array() {
assert_eq!(
variants.len(),
1,
"{field} must not admit null or other alternatives"
);
&variants[0]
} else {
property
};
for (constraint, value) in expected.as_object().unwrap() {
assert_eq!(&constraints[constraint], value, "{field}.{constraint}");
}
}
assert!(
!problem["required"]
.as_array()
.unwrap()
.contains(&json!("request_id"))
);
}
#[test]
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::ProblemType,
request_id: footing::http::RequestId,
traceparent: footing::http::TraceParent,
violations: FieldViolations,
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
);
assert_eq!(schemas["FieldViolations"]["type"], "array");
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]
async fn query_wrappers_document_query_parameters_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::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]
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], endpoints[0]];
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(&[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(&[endpoint])),
Err(OpenApiContractError::OperationWithoutContract { method: "HEAD", .. })
));
}
#[test]
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]
fn permissions_are_exported_as_metadata_without_inventing_security_schemes() {
let (_, document) = api();
let endpoint = contracts()[0]
.with_auth(footing::http::EndpointAuth::User)
.with_permissions(EndpointPermissions::One("inventory:read"));
let document = openapi::annotate_contracts(
document,
&EndpointContractRegistry::new(&[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))
))]
async fn create_item(_: RequiredIdempotencyKey) -> StatusCode {
StatusCode::NO_CONTENT
}
#[tokio::test]
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(),
]);
assert!(matches!(
openapi::validate_contracts(&document, ®istry),
Err(OpenApiContractError::InvalidParameter {
reason: "must be required",
..
})
));
let optional = [contracts[0].with_idempotency(IdempotencyRequestPolicy::HeaderOptional)];
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&optional)).unwrap();
let disabled = [contracts[0].with_idempotency(IdempotencyRequestPolicy::Disabled)];
assert!(matches!(
openapi::validate_contracts(&document, &EndpointContractRegistry::new(&disabled)),
Err(OpenApiContractError::InvalidParameter { .. })
));
}
#[test]
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();
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(),
]);
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();
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",
..
})
));
}
#[tokio::test]
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]
fn pagination_contracts_reject_missing_required_and_duplicate_query_parameters() {
let (_, mut document) = api();
let endpoints = contracts();
let registry = EndpointContractRegistry::new(&endpoints);
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",
..
})
));
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",
..
})
));
}
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]
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]
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
}
#[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 = get.parameters.as_ref().unwrap();
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!(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 { .. })
));
}
}
}