diff --git a/src/crud.rs b/src/crud.rs index 13c83f0..f753b46 100644 --- a/src/crud.rs +++ b/src/crud.rs @@ -922,9 +922,7 @@ pub async fn detail_aggregate( }; let row = match rows.first() { Some(row) => row, - None => { - return ActionResult::fail(detail_not_found_msg(spec.api_name)).into_response() - } + None => return ActionResult::fail(detail_not_found_msg(spec.api_name)).into_response(), }; let mut data = row_to_json(row); for (key, table) in children { diff --git a/src/routes/body.rs b/src/routes/body.rs index abefd6e..63d91cc 100644 --- a/src/routes/body.rs +++ b/src/routes/body.rs @@ -26,8 +26,13 @@ pub const BODY_FORMAT_ERROR: &str = "请求体格式有误,请检查 JSON 结 /// 错误媒体类型会以「JSON 解析失败」的口径回报 /// (上游的 415 落到 JNPF 全局兜底,形状未知 ⇒ 这是**已登记的刻意分歧**)。 /// -/// ⚠️ **空 body ⇒ `None`**(保留既有语义:POST / PUT 允许不带 body ⇒ 引擎按缺省值走)。 -pub struct JsonBody(pub Option); +/// 🔴 **空 body ⇒ 业务失败**(不是 `None`):上游写端点用**必填** `@RequestBody` +/// (`ResourceController.create(@RequestBody ResourceEntity entity)`), +/// 空 body 会被 Spring 抛成 `HttpMessageNotReadableException`, +/// 再被 `SswExceptionHandler#handleNotReadable` 统一映射成 +/// 「请求体格式有误,请检查 JSON 结构与字段类型」 +/// ⇒ 本仓对齐:**空 body 走同一个拒因**,**不**建出一行全 null 的垃圾数据。 +pub struct JsonBody(pub Value); impl FromRequest for JsonBody where @@ -41,10 +46,10 @@ where .await .map_err(|_| ActionResult::fail(BODY_FORMAT_ERROR).into_response())?; if bytes.is_empty() { - return Ok(JsonBody(None)); + return Err(ActionResult::fail(BODY_FORMAT_ERROR).into_response()); } match serde_json::from_slice::(&bytes) { - Ok(v) => Ok(JsonBody(Some(v))), + Ok(v) => Ok(JsonBody(v)), Err(_) => Err(ActionResult::fail(BODY_FORMAT_ERROR).into_response()), } } diff --git a/src/routes/crud.rs b/src/routes/crud.rs index 77a88d3..838669a 100644 --- a/src/routes/crud.rs +++ b/src/routes/crud.rs @@ -8,7 +8,7 @@ //! PUT {path}/{id} 修改 //! DELETE {path}/{id} 逻辑删除 //! -//! 🔴 axum 规定**主体抽取器必须是最后一个参数** ⇒ `Option>` 永远排最后, +//! 🔴 axum 规定**主体抽取器必须是最后一个参数** ⇒ `JsonBody` 永远排最后, //! `Option>` 排它前面。 //! //! 🔴 路由路径**一律取 `TableSpec::path`**(注册表是唯一真源)⇒ 不另写字符串。 @@ -16,7 +16,6 @@ use axum::extract::{Extension, Path, RawQuery, State}; use axum::routing::get; use axum::Router; -use serde_json::Value; use super::body::JsonBody; use crate::auth::Principal; @@ -45,7 +44,7 @@ pub fn router() -> Router { p: Option>, b: JsonBody| { let principal = p.map(|e| e.0); - let body = b.0.unwrap_or(Value::Null); + let body = b.0; async move { crud::create(&st, s, &body, principal.as_ref()).await } }, ), @@ -78,7 +77,7 @@ pub fn router() -> Router { p: Option>, b: JsonBody| { let principal = p.map(|e| e.0); - let body = b.0.unwrap_or(Value::Null); + let body = b.0; async move { crud::update(&st, s, &id, &body, principal.as_ref()).await } }, ) diff --git a/tests/api_smoke.rs b/tests/api_smoke.rs index 4f94adc..d49548d 100644 --- a/tests/api_smoke.rs +++ b/tests/api_smoke.rs @@ -434,6 +434,46 @@ async fn malformed_json_returns_the_business_envelope() { assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型"); } +/// 空 body 的写请求 ⇒ 业务失败(上游必填 `@RequestBody` ⇒ 空 body 被拒),**不**建出垃圾行。 +#[tokio::test] +async fn empty_body_on_write_returns_the_business_envelope() { + let (app, token, _state) = build().await; + let t = token.as_str(); + + // 🔴 用**本用例专属**的实体(`Notification` ⇒ `tdc_notify`): + // 本测试二进制共用一个 PGlite,且 `cargo test` 并行跑用例 ⇒ + // 若与 `write_routes_work_over_http` 共用 `PolicyTemplate`, + // 它的 POST 建行 / DELETE 之间的窗口会让「前后 total 对比」随机变红。 + // `tdc_notify` 只有 `f_id` 是 NOT NULL 且无 DEFAULT ⇒ 空 body 原本能建出一行全 null 垃圾数据。 + let (status, body) = call(&app, get("/api/ssw/tdc/Notification", Some(t))).await; + assert_eq!(status, 200); + let before = body["data"]["pagination"]["total"].as_i64().unwrap_or(0); + + // POST + Content-Type: application/json + 空 body + let r = Request::builder() + .method("POST") + .uri("/api/ssw/tdc/Notification") + .header("Content-Type", "application/json") + .header("X-Internal-Token", t) + .body(Body::empty()) + .unwrap(); + let (status, body) = call(&app, r).await; + assert_eq!( + status, 200, + "空 body 也应是 HTTP 200 + 业务信封:{:?}", + body + ); + assert_eq!(body["code"], 400, "空 body 应是业务失败:{:?}", body); + assert_eq!(body["msg"], "请求体格式有误,请检查 JSON 结构与字段类型"); + assert_eq!(body.get("data"), Some(&Value::Null)); + + // 🔴 关键:不得建出一行垃圾数据 + let (status, body) = call(&app, get("/api/ssw/tdc/Notification", Some(t))).await; + assert_eq!(status, 200); + let after = body["data"]["pagination"]["total"].as_i64().unwrap_or(0); + assert_eq!(after, before, "空 body 不得建出行:{:?}", body); +} + /// 方法不允许 ⇒ JSON(不是空体)。 #[tokio::test] async fn method_not_allowed_returns_json() {