feat: add bounded binary API request bodies

This commit is contained in:
2026-09-23 18:29:54 +09:00
parent 2766e5b41b
commit 97822cf691
32 changed files with 1050 additions and 149 deletions
+1
View File
@@ -20,6 +20,7 @@ reqwest = [
[dependencies]
api-macros-impl = { path = "../api-macros-impl" }
bytes.workspace = true
axum = { workspace = true, optional = true }
futures = { workspace = true, optional = true }
reqwest = { version = "0.13", default-features = false, optional = true, features = ["stream", "rustls"] }
+5 -1
View File
@@ -52,7 +52,11 @@ pub fn status(code: u16) -> StatusCode {
pub mod framework {
pub use axum::{
Json, Router,
extract::{Extension, Path, Query, State, rejection::JsonRejection},
body::Bytes,
extract::{
DefaultBodyLimit, Extension, Path, Query, State,
rejection::{BytesRejection, JsonRejection},
},
http::{HeaderMap, StatusCode},
response::Response,
routing::{delete, get, head, options, patch, post, put},
+75 -10
View File
@@ -45,12 +45,13 @@
//! security schemes. Body operations may opt into typed Axum rejection normalization with
//! typed Axum rejection normalization with `normalize_body_errors = true` and [`HttpRequestError`].
//!
//! Arguments are classified with `#[body]`, `#[query]`, `#[header]`, `#[path]`, or `#[extension]`.
//! Extension values are trusted server-local Axum context: generated clients and OpenAPI omit them.
//! An unannotated argument whose Rust name occurs in the route template is inferred as a path
//! argument. Header attributes may carry a wire name, as in `#[header("x-request-id")]`.
//! Exactly one JSON body is allowed. JSON request, response, and error bodies must be named
//! Rust types; tuples, references, arrays, and other anonymous structural types are rejected.
//! Arguments are classified with `#[body]`, `#[binary]`, `#[query]`, `#[header]`, `#[path]`, or
//! `#[extension]`. Extension values are trusted server-local Axum context: generated clients and
//! OpenAPI omit them. An unannotated argument whose Rust name occurs in the route template is
//! inferred as a path argument. Header attributes may carry a wire name, as in
//! `#[header("x-request-id")]`. Exactly one JSON or binary body is allowed. JSON request, response,
//! and error bodies must be named Rust types; tuples, references, arrays, and other anonymous
//! structural types are rejected. Binary request bodies use [`BinaryBody`] and remain byte-exact.
//! `openapi = false` explicitly excludes an operation whose wire body cannot yet satisfy the
//! strict OpenAPI schema boundary; Reqwest and Axum adapters are still generated.
//!
@@ -63,9 +64,9 @@
//! deterministic `Operation<utf8-hex>` fallback. The `ApiContract::OPERATIONS` inventory is
//! sorted by operation ID, so its ordering is independent of source method order.
//!
//! Only empty and JSON bodies are accepted by this first contract. [`WireKind`] reserves
//! explicit variants for future transport work; accepting one requires a deliberate macro and
//! adapter change rather than silently treating it as JSON.
//! Empty, JSON, and bounded binary request bodies are supported. [`WireKind`] reserves explicit
//! variants for other future transport work; accepting one requires a deliberate macro and adapter
//! change rather than silently treating it as JSON.
//!
//! # OpenAPI 3.1 export
//!
@@ -115,6 +116,70 @@ pub mod openapi;
#[cfg(feature = "reqwest")]
pub mod reqwest;
/// Framework-neutral owned bytes used by explicit `#[binary]` request bodies.
///
/// The wrapper preserves the exact byte sequence while keeping payload content out of `Debug`
/// output. Its `bytes::Bytes` storage lets generated Axum adapters transfer an extracted body
/// without reserialization and lets generated Reqwest clients authorize and send the same storage.
#[derive(Clone, Default, Eq, Hash, PartialEq)]
pub struct BinaryBody(bytes::Bytes);
impl BinaryBody {
pub const fn new(bytes: bytes::Bytes) -> Self {
Self(bytes)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn into_bytes(self) -> bytes::Bytes {
self.0
}
}
impl AsRef<[u8]> for BinaryBody {
fn as_ref(&self) -> &[u8] {
self.0.as_ref()
}
}
impl std::ops::Deref for BinaryBody {
type Target = [u8];
fn deref(&self) -> &Self::Target {
self.as_ref()
}
}
impl From<bytes::Bytes> for BinaryBody {
fn from(value: bytes::Bytes) -> Self {
Self(value)
}
}
impl From<Vec<u8>> for BinaryBody {
fn from(value: Vec<u8>) -> Self {
Self(value.into())
}
}
impl From<&'static [u8]> for BinaryBody {
fn from(value: &'static [u8]) -> Self {
Self(bytes::Bytes::from_static(value))
}
}
impl std::fmt::Debug for BinaryBody {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("BinaryBody(<redacted>)")
}
}
/// A transport-neutral HTTP method.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum HttpMethod {
@@ -189,7 +254,7 @@ pub trait ApiContract {
pub trait Operation {
/// Tuple of all non-receiver parameter types in declaration order.
type Parameters;
/// JSON request body type, or [`NoBody`].
/// Typed JSON or binary request body, or [`NoBody`].
type RequestBody;
/// JSON success response body type, or [`NoBody`].
type ResponseBody;
+18
View File
@@ -385,6 +385,24 @@ impl OpenApiOperation<'_> {
Ok(())
}
pub fn binary_request_body(&mut self) -> Result<(), OpenApiError> {
if self.request_body.is_some() {
return Err(OpenApiError::InvalidContract(format!(
"multiple request bodies for `{}`",
self.operation_id
)));
}
self.request_body = Some(json!({
"required": true,
"content": {
"application/octet-stream": {
"schema": { "type": "string", "format": "binary" }
}
},
}));
Ok(())
}
pub fn response<T: OpenApiSchema>(
&mut self,
status: u16,
+55 -8
View File
@@ -6,6 +6,7 @@
use std::{fmt, time::Duration};
use bytes::Bytes;
use futures::StreamExt as _;
use reqwest::{
Client, Method, StatusCode, Url,
@@ -319,15 +320,50 @@ impl<A> ClientCore<A> {
}
}
/// A prepared request body whose bytes are authorized and transmitted without further encoding.
pub struct EncodedBody {
bytes: Bytes,
content_type: &'static str,
}
impl EncodedBody {
fn json(bytes: Vec<u8>) -> Self {
Self {
bytes: bytes.into(),
content_type: "application/json",
}
}
fn binary(body: crate::BinaryBody) -> Self {
Self {
bytes: body.into_bytes(),
content_type: "application/octet-stream",
}
}
}
impl fmt::Debug for EncodedBody {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("EncodedBody")
.field("bytes", &"<redacted>")
.field("content_type", &self.content_type)
.finish()
}
}
impl<A: RequestAuthorizer> ClientCore<A> {
pub async fn send(
&self,
method: Method,
url: Url,
mut headers: HeaderMap,
body: Option<Vec<u8>>,
body: Option<EncodedBody>,
) -> Result<ReceivedResponse, ClientFailure> {
let body_bytes = body.as_deref().unwrap_or_default();
let body_bytes = body
.as_ref()
.map(|body| body.bytes.as_ref())
.unwrap_or_default();
let path_and_query = &url[url::Position::BeforePath..url::Position::AfterQuery];
let authorization = self
.authorizer
@@ -338,6 +374,12 @@ impl<A: RequestAuthorizer> ClientCore<A> {
})
.map_err(|_| ClientFailure::Authorization)?;
headers.extend(authorization);
if let Some(body) = body.as_ref() {
headers.insert(
reqwest::header::CONTENT_TYPE,
HeaderValue::from_static(body.content_type),
);
}
let mut request = self
.client
@@ -345,9 +387,7 @@ impl<A: RequestAuthorizer> ClientCore<A> {
.headers(headers)
.timeout(self.request_timeout);
if let Some(body) = body {
request = request
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(body);
request = request.body(body.bytes);
}
let response = request.send().await.map_err(|error| {
if error.is_timeout() {
@@ -413,9 +453,16 @@ pub fn insert_header<T: fmt::Display>(
Ok(())
}
/// Serialize the request body once. These exact bytes are authorized and transmitted.
pub fn encode_json<T: Serialize + ?Sized>(value: &T) -> Result<Vec<u8>, ClientFailure> {
serde_json::to_vec(value).map_err(|_| ClientFailure::RequestEncoding)
/// Serialize a JSON request body once. These exact bytes are authorized and transmitted.
pub fn encode_json<T: Serialize + ?Sized>(value: &T) -> Result<EncodedBody, ClientFailure> {
serde_json::to_vec(value)
.map(EncodedBody::json)
.map_err(|_| ClientFailure::RequestEncoding)
}
/// Move an explicit binary request body into the exact authorized/transmitted representation.
pub fn encode_binary(value: crate::BinaryBody) -> EncodedBody {
EncodedBody::binary(value)
}
/// Response received under the configured byte limit. Its content is always redacted in Debug.
+15 -1
View File
@@ -1,6 +1,8 @@
#![allow(async_fn_in_trait)]
use api_macros::{ApiContract, HttpMethod, NoBody, Operation, ParameterLocation, WireKind, api};
use api_macros::{
ApiContract, BinaryBody, HttpMethod, NoBody, Operation, ParameterLocation, WireKind, api,
};
pub struct CreateWidget;
pub struct Widget;
@@ -35,6 +37,12 @@ pub trait WrapperApi {
async fn search(&self) -> SearchResult<Widget>;
}
#[api]
pub trait BinaryApi {
#[put("/payload", operation_id = "payload.upload")]
async fn upload(&self, #[binary] payload: BinaryBody) -> Widget;
}
#[api]
pub trait RawIdentifierApi {
#[get("/type", operation_id = "raw.type")]
@@ -97,6 +105,12 @@ fn expansion_exposes_deterministic_metadata_and_type_connections() {
assert_eq!(lookup.parameters[0].location, ParameterLocation::Path);
assert_eq!(lookup.parameters[1].location, ParameterLocation::Query);
let upload = <binary_api_operations::Upload as Operation>::METADATA;
assert_eq!(upload.request_body.wire_kind, WireKind::Binary);
assert_eq!(upload.parameters[0].location, ParameterLocation::Body);
fn assert_binary_request<O: Operation<RequestBody = BinaryBody>>() {}
assert_binary_request::<binary_api_operations::Upload>();
let delete = <widget_api_operations::Delete as Operation>::METADATA;
assert_eq!(delete.response.status, 204);
assert_eq!(delete.response.body.wire_kind, WireKind::Empty);
+110
View File
@@ -38,6 +38,12 @@ impl api_macros::HttpError for PublicError {
}
}
impl api_macros::HttpRequestError for PublicError {
fn from_request_rejection(status: u16, message: String) -> Self {
Self { message, status }
}
}
#[api(reqwest, axum)]
pub trait WidgetApi {
#[post(
@@ -86,6 +92,45 @@ impl WidgetApi for WidgetService {
async fn delete(&self, _widget_id: u64) {}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct BinaryReceipt {
bytes: Vec<u8>,
content_type: String,
}
#[api(reqwest, axum)]
pub trait BinaryApi {
#[put(
"/binary",
operation_id = "binary.put",
status = 200,
error_status = 400,
additional_error_statuses = [413],
normalize_body_errors = true
)]
async fn upload(
&self,
#[header("content-type")] content_type: String,
#[binary] body: api_macros::BinaryBody,
) -> Result<BinaryReceipt, PublicError>;
}
#[derive(Clone)]
pub struct BinaryService;
impl BinaryApi for BinaryService {
async fn upload(
&self,
content_type: String,
body: api_macros::BinaryBody,
) -> Result<BinaryReceipt, PublicError> {
Ok(BinaryReceipt {
bytes: body.as_ref().to_vec(),
content_type,
})
}
}
#[api(reqwest)]
pub trait FailureApi {
#[get("/malformed", operation_id = "failure.malformed", status = 200)]
@@ -276,6 +321,71 @@ async fn generated_client_and_router_follow_the_normalized_contract() {
server.abort();
}
#[tokio::test]
async fn binary_adapter_preserves_exact_bytes_content_type_and_route_limit() {
let app = binary_api_axum::upload(Arc::new(BinaryService))
.layer(api_macros::axum::framework::DefaultBodyLimit::max(4));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind binary fixture server");
let address = listener.local_addr().expect("binary fixture address");
let server = tokio::spawn(async move {
api_macros::axum::framework::serve(listener, app)
.await
.expect("serve binary fixture API");
});
let recorded = Arc::new(Mutex::new(None));
let client = BinaryApiClient::builder(format!("http://{address}/"))
.expect("validated base URL")
.authorizer(RecordingAuthorizer {
request: recorded.clone(),
credential: "Bearer binary-test".to_owned(),
})
.build()
.expect("binary client build");
for expected in [vec![], vec![0, 1], vec![0, 255, 1, 2]] {
let receipt = client
.upload(
"text/plain".to_owned(),
api_macros::BinaryBody::from(expected.clone()),
)
.await
.expect("binary body within the route limit");
assert_eq!(receipt.bytes, expected);
assert_eq!(receipt.content_type, "application/octet-stream");
assert_eq!(
recorded
.lock()
.expect("recording lock")
.as_ref()
.expect("authorized request")
.body,
expected
);
}
let oversized = client
.upload(
"text/plain".to_owned(),
api_macros::BinaryBody::from(vec![0, 1, 2, 3, 4]),
)
.await
.expect_err("one byte over the route limit must be rejected");
assert!(matches!(
oversized,
api_reqwest::ClientError::Public { status, .. }
if status == api_reqwest::framework::StatusCode::PAYLOAD_TOO_LARGE
));
assert_eq!(
format!("{:?}", api_macros::BinaryBody::from(vec![1, 2, 3])),
"BinaryBody(<redacted>)"
);
server.abort();
}
#[test]
fn base_urls_are_strict_and_named_adapter_types_are_public() {
assert!(api_reqwest::BaseUrl::try_from("ftp://example.test/").is_err());
+22 -1
View File
@@ -2,7 +2,7 @@
#![allow(async_fn_in_trait, dead_code)]
use api_macros::{
api,
BinaryBody, api,
openapi::{OpenApiInfo, OpenApiSchema},
};
use schemars::JsonSchema;
@@ -100,6 +100,9 @@ pub trait FixtureApi {
#[delete("/widgets/{widget_id}", operation_id = "widgets.delete", status = 204)]
async fn delete(&self, #[path] widget_id: u32) -> ();
#[put("/uploads", operation_id = "uploads.put", status = 200)]
async fn upload(&self, #[binary] body: BinaryBody) -> Widget;
}
fn document() -> api_macros::openapi::OpenApiDocument {
@@ -282,6 +285,24 @@ fn operations_and_components_preserve_the_wire_contract() {
);
}
let upload = &value["paths"]["/uploads"]["put"];
assert_eq!(upload["operationId"], "uploads.put");
assert_eq!(
upload["requestBody"],
json!({
"required": true,
"content": {
"application/octet-stream": {
"schema": { "type": "string", "format": "binary" }
}
}
})
);
assert!(
!schemas.contains_key("BinaryBody"),
"binary payloads are not JSON Schema components"
);
let delete = &value["paths"]["/widgets/{widget_id}"]["delete"];
assert_eq!(delete["operationId"], "widgets.delete");
assert!(delete.get("security").is_none());
@@ -0,0 +1,11 @@
use api_macros::api;
pub struct Response;
#[api]
pub trait InvalidBinaryMethod {
#[get("/payload")]
async fn download(&self, #[binary] body: api_macros::BinaryBody) -> Response;
}
fn main() {}
@@ -0,0 +1,5 @@
error: GET operations cannot declare a request body
--> tests/ui/invalid_binary_method.rs:8:14
|
8 | async fn download(&self, #[binary] body: api_macros::BinaryBody) -> Response;
| ^^^^^^^^
@@ -0,0 +1,11 @@
use api_macros::api;
pub struct Response;
#[api]
pub trait InvalidBinaryType {
#[put("/payload")]
async fn upload(&self, #[binary] body: Vec<u8>) -> Response;
}
fn main() {}
@@ -0,0 +1,5 @@
error: binary request bodies must use api_macros::BinaryBody
--> tests/ui/invalid_binary_type.rs:8:44
|
8 | async fn upload(&self, #[binary] body: Vec<u8>) -> Response;
| ^^^^^^^
@@ -0,0 +1,16 @@
use api_macros::api;
pub struct JsonBody;
pub struct Response;
#[api]
pub trait MixedRequestBodies {
#[post("/payload")]
async fn upload(
&self,
#[body] json: JsonBody,
#[binary] binary: api_macros::BinaryBody,
) -> Response;
}
fn main() {}
@@ -0,0 +1,5 @@
error: an API operation may declare only one JSON or binary request body
--> tests/ui/mixed_request_bodies.rs:12:19
|
12 | #[binary] binary: api_macros::BinaryBody,
| ^^^^^^
@@ -0,0 +1,15 @@
use api_macros::api;
pub struct Response;
#[api]
pub trait MultipleBinaryBodies {
#[post("/payload")]
async fn upload(
&self,
#[binary] first: api_macros::BinaryBody,
#[binary] second: api_macros::BinaryBody,
) -> Response;
}
fn main() {}
@@ -0,0 +1,5 @@
error: an API operation may declare only one JSON or binary request body
--> tests/ui/multiple_binary_bodies.rs:11:19
|
11 | #[binary] second: api_macros::BinaryBody,
| ^^^^^^
@@ -1,4 +1,4 @@
error: an API operation may declare only one request body
error: an API operation may declare only one JSON or binary request body
--> tests/ui/multiple_bodies.rs:13:17
|
13 | #[body] second: SecondBody,