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
+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,