From cf361b6acab425a190c01ec68d952dd87c4abbef Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 25 Oct 2026 15:08:25 +0800 Subject: [PATCH] =?UTF-8?q?fix(crud):=20=E4=B8=8A=E6=B8=B8=20@JsonIgnore?= =?UTF-8?q?=20=E5=AD=97=E6=AE=B5=E4=B8=8D=E5=86=8D=E4=BB=8E=20CRUD=20?= =?UTF-8?q?=E5=87=BA=E5=8F=82=E6=B3=84=E6=BC=8F=E3=80=81=E4=B9=9F=E4=B8=8D?= =?UTF-8?q?=E5=86=8D=E8=A2=AB=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **影响** - 改动前:`GET /api/ssw/tdc/Identity` 与 `GET /api/ssw/tdc/Identity/{id}` 会把 `secretKey` 原样回显(`SELECT *` + camelCase 直出)⇒ 接入密钥泄漏到 API 响应。 - 改动后:这 3 个键在出参里**整条不出现**(不是 null),入参里带则**静默忽略**。 **改动** - `src/registry.rs`:`TableSpec` 新增 `hidden_fields`(camelCase JSON 键), 18 个实体逐个登记;`validate()` 校验每个键能反解成合法列名。 - `src/crud.rs`:新增 `row_to_json_spec()`(出参删键)+ `body_to_columns()` 增加 第三个参数 `hidden_fields`(入参跳键);`update` 的 frozen 列自检跳过 hidden 列 (上游 `devUrl` / `devToken` 既是 `@JsonIgnore` 又是 frozen ⇒ Jackson 绑不上 ⇒ `changed()` 恒 false ⇒ 上游既不拒也不写)。 - `tests/crud_engine.rs`:新增 1 条集成测试(建 Identity 送 `secretKey` ⇒ 库里 仍为空、detail/list 无 `secretKey` 键、update 送 `secretKey` 不落库)。 **设计** - 清单**逐字照抄上游**:全仓只有 3 个属性标了 `@JsonIgnore` (`IdentityEntity.f_secret_key` / `DeliveryTaskEntity.f_dev_url` / `f_dev_token`)。 - 🟡 **有意比上游更严的一处**:`CredentialEntity.f_secret_key` 上游**漏标** `@JsonIgnore`(该列是「预留 SK 密文(本期空)」,上游自注)⇒ 本仓补上去敏; 该列本仓从不写入(恒 NULL)⇒ 对外行为零差异,纯属兜底。 Co-Authored-By: Claude Code --- src/crud.rs | 73 +++++++++++++++++++++++++++++---- src/registry.rs | 72 +++++++++++++++++++++++++++++++++ tests/crud_engine.rs | 96 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 233 insertions(+), 8 deletions(-) diff --git a/src/crud.rs b/src/crud.rs index ec1b295..1771a9e 100644 --- a/src/crud.rs +++ b/src/crud.rs @@ -123,6 +123,23 @@ pub fn row_to_json(row: &Value) -> Value { Value::Object(out) } +/// 行数据 ⇒ 上游 Jackson 形状,并**删掉**该实体的不外泄字段。 +/// +/// 🔴 上游实体上标了 `@JsonIgnore` 的属性,序列化时**整条不出现**(不是 null)⇒ 本仓照抄。 +/// 清单见 [`TableSpec::hidden_fields`](键是 camelCase JSON 键)。 +pub fn row_to_json_spec(spec: &TableSpec, row: &Value) -> Value { + let mut out = row_to_json(row); + if spec.hidden_fields.is_empty() { + return out; + } + if let Some(obj) = out.as_object_mut() { + for key in spec.hidden_fields { + obj.remove(*key); + } + } + out +} + /// 标量值 ⇒ 文本(用于「值真的变化」比较;非标量返回 `None`)。 fn scalar_text(v: &Value) -> Option { match v { @@ -137,8 +154,14 @@ fn scalar_text(v: &Value) -> Option { /// /// - `null` 值跳过(等价 MyBatis-Plus 的 `NOT_NULL` 合并策略:null 表示「不覆盖」); /// - 系统列跳过; +/// - **不外泄字段跳过**(上游实体上标了 `@JsonIgnore` ⇒ Jackson **绑定不到**该属性 +/// ⇒ 客户端送什么都不会写库;不是拒,是「当它不存在」); /// - 表里没有的键**静默忽略**(对齐 Spring Boot 默认 `FAIL_ON_UNKNOWN_PROPERTIES=false`)。 -pub fn body_to_columns(body: &Value, types: &HashMap) -> Vec<(String, String)> { +pub fn body_to_columns( + body: &Value, + types: &HashMap, + hidden_fields: &[&str], +) -> Vec<(String, String)> { let obj = match body.as_object() { Some(o) => o, None => return Vec::new(), @@ -148,6 +171,9 @@ pub fn body_to_columns(body: &Value, types: &HashMap) -> Vec<(St if value.is_null() { continue; } + if hidden_fields.contains(&key.as_str()) { + continue; + } let col = json_key_to_column(key); if SYSTEM_COLUMNS.contains(&col.as_str()) { continue; @@ -485,7 +511,7 @@ pub async fn list( Ok(r) => r, Err(e) => return server_error(e), }; - let list: Vec = rows.iter().map(row_to_json).collect(); + let list: Vec = rows.iter().map(|r| row_to_json_spec(spec, r)).collect(); ActionResult::page( list, Pagination { @@ -524,7 +550,12 @@ pub async fn all( Ok(r) => r, Err(e) => return server_error(e), }; - ActionResult::ok(rows.iter().map(row_to_json).collect::>()).into_response() + ActionResult::ok( + rows.iter() + .map(|r| row_to_json_spec(spec, r)) + .collect::>(), + ) + .into_response() } /// 详情:`GET /api/ssw/tdc/{Entity}/{id}`。 @@ -550,7 +581,7 @@ pub async fn detail( Err(e) => return server_error(e), }; match rows.first() { - Some(row) => ActionResult::ok(row_to_json(row)).into_response(), + Some(row) => ActionResult::ok(row_to_json_spec(spec, row)).into_response(), None => ActionResult::fail("记录不存在或已删除").into_response(), } } @@ -690,7 +721,7 @@ pub async fn create( } // ③ body 列(跳过已被引擎消费的列)。 - for (col, text) in body_to_columns(body, &types) { + for (col, text) in body_to_columns(body, &types, spec.hidden_fields) { if skip.contains(&col) { continue; } @@ -784,7 +815,19 @@ pub async fn update( }; // 冻结列:只拒「值真的变化」(上游 `changedAuthorityColumn` 口径)。 + // + // 🔴 **不外泄字段不参与**(上游同口径):上游 `DeliveryTaskEntity.devUrl` / `devToken` + // 标了 `@JsonIgnore` ⇒ Jackson **永远绑不上** ⇒ 上游 `changed(cur, in)` 里 `in` 恒 null + // ⇒ `changed()` 恒 false ⇒ 上游**压根不会**走到「拒绝」分支(既不拒、也不写)。 + let hidden_columns: Vec = spec + .hidden_fields + .iter() + .map(|k| json_key_to_column(k)) + .collect(); for fc in spec.frozen_columns { + if hidden_columns.iter().any(|c| c == fc.column) { + continue; + } let key = column_to_json_key(fc.column); if let Some(incoming) = body.get(&key) { if !incoming.is_null() { @@ -812,7 +855,7 @@ pub async fn update( let mut sets: Vec = Vec::new(); let mut binds: Vec = Vec::new(); - for (col, text) in body_to_columns(body, &types) { + for (col, text) in body_to_columns(body, &types, spec.hidden_fields) { binds.push(text); let idx = binds.len(); sets.push(format!("{} = {}", col, cast_param(&types, &col, idx))); @@ -971,7 +1014,7 @@ pub async fn detail_aggregate( Some(row) => row, None => return ActionResult::fail(detail_not_found_msg(spec.api_name)).into_response(), }; - let mut data = row_to_json(row); + let mut data = row_to_json_spec(spec, row); for (key, table) in children { let sql = format!( "SELECT * FROM {} WHERE f_resource_id = CAST($1 AS character varying) ORDER BY f_sort_code", @@ -1046,10 +1089,24 @@ mod tests { "nope": "x", "count": 3 }); - let cols = body_to_columns(&body, &types); + let cols = body_to_columns(&body, &types, &[]); assert_eq!(cols, vec![("f_name".to_string(), "产品".to_string())]); } + /// 🔴 不外泄字段(上游 `@JsonIgnore`)**入参也当它不存在**。 + #[test] + fn body_to_columns_skips_json_ignored_fields() { + let mut types = HashMap::new(); + types.insert( + "f_secret_key".to_string(), + "character varying(200)".to_string(), + ); + types.insert("f_name".to_string(), "character varying(200)".to_string()); + let body = json!({"name": "身份", "secretKey": "SENTINEL"}); + let cols = body_to_columns(&body, &types, &["secretKey"]); + assert_eq!(cols, vec![("f_name".to_string(), "身份".to_string())]); + } + #[test] fn build_where_rejects_client_tenant_id() { let spec = registry::find("Product").unwrap(); diff --git a/src/registry.rs b/src/registry.rs index 897bfb7..de6540c 100644 --- a/src/registry.rs +++ b/src/registry.rs @@ -69,6 +69,21 @@ pub struct TableSpec { pub no_delete: Option<&'static str>, /// 不可经编辑入口改写的列。 pub frozen_columns: &'static [FrozenColumn], + /// **不外泄字段**(上游实体上标了 `@JsonIgnore` 的属性)—— 键是 **camelCase JSON 键**。 + /// + /// 🔴 语义**逐字照抄 Jackson 的 `@JsonIgnore`**(既管序列化,也管反序列化): + /// - **出参**:该键**整条删掉**(不是置 null); + /// - **入参**:请求体里带这个键 ⇒ **静默忽略**(不写库),与上游绑定不到实体字段一致。 + /// + /// 上游真源(2026-10-25 核对,全仓只有这 3 个属性标了 `@JsonIgnore`): + /// - `IdentityEntity.f_secret_key`(接入 SK = 连接器前端登录密钥) + /// - `DeliveryTaskEntity.f_dev_url`(工作台外网入口,URL 内含 token) + /// - `DeliveryTaskEntity.f_dev_token`(工作台控制通道令牌 `X-Session-Token`) + /// + /// ⚠️ 与 [`TableSpec::frozen_columns`] 的区别:frozen 是「**拒改**并回话术」, + /// hidden 是「**当它不存在**」—— 上游两者对 `f_dev_url` / `f_dev_token` **同时存在** + /// (实体 `@JsonIgnore` + 控制器 `changedAuthorityColumn`),本仓照抄。 + pub hidden_fields: &'static [&'static str], } /// `DeliveryTask` 的 41 个服务端权威列。 @@ -150,6 +165,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: Some("计量明细只读:禁止经泛型 CRUD 新增/修改(「已用」的唯一来源,防旁路污染配额)"), no_delete: Some("计量明细只读:禁止经泛型 CRUD 删除(审计证据不可篡改)"), frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "AuditLog", @@ -172,6 +188,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: Some("审计日志不允许修改"), no_delete: Some("审计日志不允许删除"), frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Contract", @@ -194,6 +211,7 @@ pub static REGISTRY: &[TableSpec] = &[ // 上游 `ContractController#beforeDelete` **无条件**抛(权威归档在平台,副本只随联动清退) no_delete: Some("本地合约副本不可删除(权威归档在平台,副本仅随空间/合约清退联动)"), frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Credential", @@ -212,6 +230,10 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + // 🟡 **有意比上游更严的一处**:上游 `CredentialEntity.f_secret_key` **漏标** `@JsonIgnore` + // (该列是「预留 SK 密文(本期空)」,上游自注)⇒ 本仓补上去敏。 + // 该列本仓**从不写入**(恒 NULL)⇒ 对外行为零差异,纯属兜底。 + hidden_fields: &["secretKey"], }, TableSpec { api_name: "DataInterface", @@ -226,6 +248,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Dataset", @@ -240,6 +263,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: Some("数据集为只读视图,不支持新增/编辑/删除"), no_delete: Some("数据集为只读视图,不支持新增/编辑/删除"), frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Datasource", @@ -259,6 +283,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "DeliveryLog", @@ -273,6 +298,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: Some("交付日志是审计证据,不允许删除"), frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "DeliveryTask", @@ -302,6 +328,8 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: Some("交付任务记录是审计证据,不允许删除"), frozen_columns: DELIVERY_TASK_FROZEN, + // 上游 `DeliveryTaskEntity` 对这两个属性标了 `@JsonIgnore`(工作台凭证,2026-10-25 核对)。 + hidden_fields: &["devUrl", "devToken"], }, TableSpec { api_name: "DestroyLog", @@ -316,6 +344,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: Some("销毁日志是合规存证,不可删除"), frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Identity", @@ -336,6 +365,9 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + // 上游 `IdentityEntity.f_secret_key` 标了 `@JsonIgnore`(2026-10-25 核对): + // 「防 CRUD list/detail 泄露——operator 用 Identity/{id}/RotateSecret 取/重置」。 + hidden_fields: &["secretKey"], }, TableSpec { api_name: "Notification", @@ -357,6 +389,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Order", @@ -377,6 +410,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Policy", @@ -395,6 +429,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "PolicyCheckLog", @@ -414,6 +449,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: Some("策略评估流水是审计证据,不允许删除"), frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "PolicyTemplate", @@ -428,6 +464,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Product", @@ -451,6 +488,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, TableSpec { api_name: "Resource", @@ -473,6 +511,7 @@ pub static REGISTRY: &[TableSpec] = &[ no_update: None, no_delete: None, frozen_columns: &[], + hidden_fields: &[], }, ]; @@ -550,6 +589,12 @@ pub fn validate() -> Result<(), String> { return Err(format!("注册表冻结列非法: {}.{}", spec.table, fc.column)); } } + for key in spec.hidden_fields { + let col = json_key_to_column(key); + if valid_table(&col).is_none() { + return Err(format!("注册表不外泄字段非法: {}.{}", spec.table, col)); + } + } for cs in create_codes(spec.api_name) { let col = json_key_to_column(cs.key); if valid_table(&col).is_none() { @@ -676,6 +721,33 @@ mod tests { assert_eq!(find("Product").unwrap().tenant_column, Some("f_tenant_id")); } + /// 🔴 **不外泄字段清单**(上游 `@JsonIgnore`)**字面钉住**。 + /// + /// 上游全仓只有 **3 个属性**标了 `@JsonIgnore`(2026-10-25 核对 `ssw-tdc-entity`): + /// `IdentityEntity.f_secret_key`、`DeliveryTaskEntity.f_dev_url` / `f_dev_token`。 + /// 本仓另有一处**有意更严**:`CredentialEntity.f_secret_key`(上游漏标,该列是预留空列)。 + #[test] + fn json_ignored_fields_are_pinned_literally() { + assert_eq!(find("Identity").unwrap().hidden_fields, &["secretKey"]); + assert_eq!( + find("DeliveryTask").unwrap().hidden_fields, + &["devUrl", "devToken"] + ); + assert_eq!(find("Credential").unwrap().hidden_fields, &["secretKey"]); + // 其余 15 个实体一个都不许有不外泄字段(上游没有别的 @JsonIgnore)。 + for s in REGISTRY { + if matches!(s.api_name, "Identity" | "DeliveryTask" | "Credential") { + continue; + } + assert!( + s.hidden_fields.is_empty(), + "{} 不该有不外泄字段(上游无 @JsonIgnore):{:?}", + s.api_name, + s.hidden_fields + ); + } + } + #[test] fn permission_keys_cover_every_entity() { assert_eq!(PERMISSION_KEYS.len(), 18); diff --git a/tests/crud_engine.rs b/tests/crud_engine.rs index c847282..9e43f1c 100644 --- a/tests/crud_engine.rs +++ b/tests/crud_engine.rs @@ -821,3 +821,99 @@ async fn internal_errors_do_not_echo_the_database_message() { assert!(!msg.contains("f_price"), "不得回显列名:{}", msg); assert!(!msg.contains("numeric"), "不得回显数据库原文:{}", msg); } + +/// 🔴 **上游 `@JsonIgnore` 的属性:既不外泄、也不可写**(R10 回归)。 +/// +/// 上游 `IdentityEntity.f_secret_key` 标了 `@JsonIgnore`,注释明写「防 CRUD list/detail 泄露」。 +/// Jackson 的 `@JsonIgnore` **既管序列化也管反序列化** ⇒ +/// - 出参:**整条键不出现**(不是 null); +/// - 入参:**绑不上实体** ⇒ 客户端送什么都不会写库(是「当它不存在」,不是「报错」)。 +/// +/// 本仓此前 `crud.rs` 是 `SELECT *` + camelCase 直出 ⇒ `secretKey` 原样回显(= 泄漏)。 +#[tokio::test] +async fn json_ignored_fields_are_neither_exposed_nor_writable() { + let state = test_state().await; + let spec = registry::find("Identity").unwrap(); + + // 读库里那一列(**只判空,不回显值** —— 免得把密钥写进 transcript)。 + let read_secret = |id: &str| { + let state = state.clone(); + let id = id.to_string(); + async move { + let sql = "SELECT f_secret_key FROM tdc_identity WHERE f_id = CAST($1 AS text)"; + let _g = state.db_lock.lock().await; + tdc_connector::db::query_scalar_text(state.db.as_ref(), sql, &[&id]) + .await + .expect("查询失败") + } + }; + + // ① 新建:请求体里带 secretKey ⇒ **静默忽略**(上游绑不上该属性) + let resp = crud::create( + &state, + spec, + &json!({ + "identityCode": "REDACT-TEST-1", + "name": "去敏测试身份", + "secretKey": "SENTINEL-MUST-NOT-BE-STORED", + }), + Some(&principal()), + ) + .await; + let body = body_of(resp).await; + assert_eq!(body["code"], 200, "新建失败:{}", body["msg"]); + let id = body["data"].as_str().expect("应返回 id").to_string(); + + let stored = read_secret(&id).await; + assert!( + stored + .as_deref() + .map(|s| s.trim().is_empty()) + .unwrap_or(true), + "客户端送的 secretKey 不应被写库" + ); + + // ② 详情:响应里**没有** secretKey 这个键 + let resp = crud::detail(&state, spec, &id, Some(&principal())).await; + let body = body_of(resp).await; + assert_eq!(body["code"], 200); + assert_eq!(body["data"]["identityCode"], "REDACT-TEST-1"); + assert!( + body["data"].get("secretKey").is_none(), + "详情不得回显 secretKey(上游是 @JsonIgnore ⇒ 整条不出现)" + ); + + // ③ 列表:同样没有 + let params = HashMap::new(); + let resp = crud::list(&state, spec, ¶ms, Some(&principal())).await; + let body = body_of(resp).await; + assert_eq!(body["code"], 200); + for row in body["data"]["list"].as_array().expect("list 应是数组") { + assert!(row.get("secretKey").is_none(), "列表不得回显 secretKey"); + } + + // ④ 修改:送 secretKey ⇒ 报「修改成功」但**不写**(上游:绑不上 ⇒ 等于没送) + let resp = crud::update( + &state, + spec, + &id, + &json!({ + "name": "改名后的去敏测试身份", + "secretKey": "SENTINEL-SECOND", + }), + Some(&principal()), + ) + .await; + let body = body_of(resp).await; + assert_eq!(body["code"], 200); + assert_eq!(body["msg"], "修改成功"); + + let stored = read_secret(&id).await; + assert!( + stored + .as_deref() + .map(|s| s.trim().is_empty()) + .unwrap_or(true), + "修改也不应写 secretKey" + ); +}