From 8db55d12204a59cea3d892c07a66969ed9735b0b Mon Sep 17 00:00:00 2001 From: admin Date: Sat, 24 Oct 2026 19:47:55 +0800 Subject: [PATCH] =?UTF-8?q?fix(protocol):=20=E8=BE=93=E5=87=BA=E5=B1=82?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=8E=BB=E6=8E=A7=E5=88=B6=E5=AD=97=E7=AC=A6?= =?UTF-8?q?=20+=20=E8=A1=A5=E5=85=A8=E5=AE=88=E5=8D=AB=E7=99=BD=E5=90=8D?= =?UTF-8?q?=E5=8D=95=20+=20=E6=8B=86=E5=BC=80=E6=9C=9F=E6=9C=9B=E5=80=BC?= =?UTF-8?q?=E6=9D=A5=E6=BA=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - emit_warn 构造输出行前统一剥掉日志不安全字符(只剥不截)⇒ 兄弟模块 即使传未净化值,ESC / 换行也进不了日志;固定路径整行不被截断 - 源级守卫白名单补齐 eprintln!("{line}") 形态 ⇒ 合法重构不再假红 - 固定路径的期望整行拆成两份互相独立的期望值 ⇒ 同步改写不再全绿 - emitted_count 的「原始行数」语义被用例钉住 ⇒ 行数防线不再依赖未钉语义 Co-Authored-By: Claude Code --- src/protocol.rs | 203 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 178 insertions(+), 25 deletions(-) diff --git a/src/protocol.rs b/src/protocol.rs index 1fffc0d..a77c114 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -20,8 +20,12 @@ //! 对端声明值),而 `SafePeer` 只能经 `SafePeer::new` 构造 ⇒ 调用点在**类型上**没法把 //! 未净化的对端值送进日志。 //! -//! 🔴 净化的**出口**同样被封住:变量 key 的告警入口 `warn_once_variable` 是**模块私有** -//! ⇒ crate 内的兄弟模块既拿不到它,也没法用它把裸 `&str` 打进日志。 +//! 🔴 净化的**出口**有**两道**防线: +//! ① 变量 key 的告警入口 `warn_once_variable` 是**模块私有** +//! ⇒ crate 内的兄弟模块既拿不到它,也没法用它把裸 `&str` 打进日志。 +//! ② **输出层统一 scrub**:`emit_warn` 在构造输出行**之前**把消息体里的全部 +//! 日志不安全字符**剥掉**(只剥不截)⇒ 即便兄弟模块 / 外部 crate 传进来 +//! 未净化的值,ESC / 换行也**进不了日志**(见 `scrub_for_log`)。 use std::collections::HashSet; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -111,10 +115,18 @@ fn claim_variable_key(set: &Mutex>, key: &str) -> bool { /// /// 🔴 **完整输出行只构造一次**:真实输出与测试记录器共享**同一个**字符串 `line` /// ⇒ 二者不可能分叉(不会一个记 A、一个打 B)。 +/// +/// 🔴 **输出层统一 scrub**:构造输出行**之前**先把消息体里的全部日志不安全字符 +/// (C0/C1 控制符、ANSI ESC 序列、零宽、双向控制符)**剥掉**(**只剥不截**)。 +/// ⇒ 兄弟模块 / 外部 crate 即使传进来未净化的值,ESC / 换行也**进不了日志** +/// ⇒ 既伪造不出第二条日志行,也注入不了终端转义。 +/// ⚠️ 这里**必须**用 `scrub_for_log`(不截断),**不能**用 `sanitize_for_log` +/// (它按 `LOG_MAX_LEN` = 64 **截断**)—— 固定路径的整行**长于** 64 字节 +/// ⇒ 一截断,全部逐字断言当场崩。 /// ⚠️ stable 没有可用的**进程内** stderr 捕获手段(`std::io::set_output_capture` 是 `#[unstable]`) /// ⇒ 「这一行真的落到了 fd 2」由**子进程**用例实测;本函数只保证「那一行还在、且内容是共享的那一行」。 fn emit_warn(message: &str) { - let line = format!("[tdc-connector] WARN {}", message); + let line = format!("[tdc-connector] WARN {}", scrub_for_log(message)); eprintln!("{}", line); #[cfg(test)] warn_recorder::record(&line); @@ -221,6 +233,10 @@ pub fn is_protocol_acceptable(declared: Option<&str>) -> bool { /// `&'static str`(Rust 类型系统的固有极限,doctest 也拦不住该形态)。 /// 真正的硬保证是**结构上的**:非测试代码里 `warn_once` 只有一处调用点 /// (`check_protocol_with_warn`),且传的是字面量 `"protocol:missing"`。 +/// +/// 🔴 **消息体在输出层统一净化**:本函数**不**净化 `message`,但 `emit_warn` +/// 在构造输出行**之前**会把消息体里的全部日志不安全字符剥掉(见 `scrub_for_log`) +/// ⇒ 兄弟模块即使传进来未净化的值,ESC / 换行也进不了日志。 pub fn warn_once(key: &'static str, message: &str) -> bool { if claim_fixed_key(fixed_warned_keys(), key) { emit_warn(message); @@ -262,19 +278,22 @@ fn is_log_unsafe(c: char) -> bool { ) } -/// 净化对端可控的字符串,供**日志 / 告警**用途:去控制字符(含 ANSI ESC 序列)并按整字符截断。 +/// 剥掉全部日志不安全字符(C0/C1 控制符、ANSI ESC 序列、零宽、双向控制符)。 /// -/// ⚠️ **只用于日志**。安全判定(`is_protocol_compatible` / `is_protocol_acceptable`) -/// 必须使用原值 —— 净化会引入绕过风险(如 `"1.0\u{1b}[0m"` 净化后变 `"1.0"`, -/// 反而可能被误判为兼容)。 +/// `max_len = Some(n)` 时**截断**到 n **字节**;`None` 时**只剥不截**。 /// -/// 截断**按整字符推进**(不用 `String::truncate`)⇒ 64 字节边界切在多字节字符中间也不会 panic。 -pub(crate) fn sanitize_for_log(raw: &str) -> String { +/// 🔴 `max_len = Some(n)` 时与原 `sanitize_for_log` **逐字节等价**: +/// cap 检查的**位置**(在 ESC 处理**之前**、在 `push` **之前**)原样保留。 +/// 🔴 ANSI 状态机**只此一份** ⇒ `sanitize_for_log`(截断)与 `scrub_for_log`(不截断) +/// 不会各自漂移。 +fn strip_unsafe(raw: &str, max_len: Option) -> String { let mut out = String::new(); let mut it = raw.chars().peekable(); while let Some(c) = it.next() { - if out.len() + c.len_utf8() > LOG_MAX_LEN { - break; + if let Some(limit) = max_len { + if out.len() + c.len_utf8() > limit { + break; + } } if c == '\u{1b}' { // ANSI 转义序列:ESC [ … 消费到 final byte;ESC ] … 消费到 BEL/ST;其余按 2 字节序列 @@ -313,6 +332,32 @@ pub(crate) fn sanitize_for_log(raw: &str) -> String { out } +/// 净化对端可控的字符串,供**日志 / 告警**用途:去控制字符(含 ANSI ESC 序列)并按整字符截断。 +/// +/// ⚠️ **只用于日志**。安全判定(`is_protocol_compatible` / `is_protocol_acceptable`) +/// 必须使用原值 —— 净化会引入绕过风险(如 `"1.0\u{1b}[0m"` 净化后变 `"1.0"`, +/// 反而可能被误判为兼容)。 +/// +/// 截断**按整字符推进**(不用 `String::truncate`)⇒ 64 字节边界切在多字节字符中间也不会 panic。 +/// +/// 🔴 **与 `scrub_for_log` 的分工**:本函数**剥 + 截**(给**值层**用:进 key / 进消息体 +/// 的对端声明值,预算有限);`scrub_for_log` **只剥不截**(给**输出层**用: +/// 整行输出不许被截断 —— 固定路径的整行**长于** `LOG_MAX_LEN`)。 +/// 两者共用同一份 ANSI 状态机(`strip_unsafe`)⇒ 行为不会分叉。 +pub(crate) fn sanitize_for_log(raw: &str) -> String { + strip_unsafe(raw, Some(LOG_MAX_LEN)) +} + +/// 剥掉日志不安全字符,**不截断**。 +/// +/// 🔴 与 `sanitize_for_log` 的**唯一**区别就是**不截断** —— 输出层必须用它: +/// 固定路径消息的整行**长于** `LOG_MAX_LEN`(64 字节)⇒ 用 `sanitize_for_log` +/// 会把整行截掉 ⇒ 逐字断言当场崩。 +/// ⚠️ 只剥不删**内容**:被剥掉的只是控制字符 / 转义序列,正文原样保留。 +fn scrub_for_log(raw: &str) -> String { + strip_unsafe(raw, None) +} + /// 变量 key:含**净化后**的声明值(防日志伪造 / 终端转义注入)。 /// 入参是 `SafePeer` ⇒ 调用点**没法**把未净化的原值塞进来。 fn incompatible_warn_key(peer: &SafePeer) -> String { @@ -342,7 +387,9 @@ fn check_protocol_with_warn(declared: Option<&str>) -> (bool, bool) { ); return (true, warned); } - // 判定用原值 `d`;日志用净化值(净化恰好发生一次)。 + // 判定用原值 `d`;日志用净化值 —— **两层**净化: + // ① **值层**:`SafePeer::new` 里剥掉日志不安全字符 + 截断到 64 字节(一次); + // ② **输出层**:`emit_warn` 构造输出行前再统一剥一次(**幂等** ⇒ 不改变内容)。 if is_protocol_compatible(d) { return (true, false); } @@ -379,16 +426,44 @@ mod tests { warn_recorder::clear(); } - /// 固定路径(未声明协议版本)的**期望整行**。 + /// 固定路径(未声明协议版本)的**期望整行** —— **第二份**独立期望值(**拼接**写法)。 + /// + /// 🔴 固定路径的期望整行有**两份互相独立**的写法,彼此**不共用任何 helper**: + /// ① 本函数(**拼接**写法)—— 给子进程用例 + /// `stderr_really_receives_the_exact_warn_lines` 用; + /// ② `missing_declaration_message_states_header_and_version` 里**就地写死**的 + /// `format!` 字面量。 + /// 两份的**表达式结构不同**(拼接 vs `format!` 模板)⇒ 「同步改写生产模板 + 其中一份」 + /// 只能改到一边 ⇒ **另一边必然 RED** ⇒ 假通过被堵死。 /// /// 🔴 期望值必须与被测代码**独立**(这里硬编码 header 名与文案模板, /// 只用 `PROTOCOL_VERSION` 取本端版本)⇒ 否则「消息内容被改坏」这类变异会 /// 顺手把期望值一起改掉 ⇒ 假通过。 fn expected_missing_line() -> String { - format!( - "[tdc-connector] WARN 跨端请求未声明 X-Protocol-Version,按兼容期放行(本端 {})", - PROTOCOL_VERSION - ) + let mut s = String::from("[tdc-connector] WARN "); + s.push_str("跨端请求未声明 "); + s.push_str("X-Protocol-Version"); + s.push_str(",按兼容期放行(本端 "); + s.push_str(PROTOCOL_VERSION); + s.push(')'); + s + } + + /// `emit_warn` 里允许的「打印共享的那一行 `line`」的写法。 + /// + /// 🔴 宏名**运行时拼接** ⇒ 本文件源码里不会出现连续的 `eprint` + `ln` ⇒ 不会自匹配。 + fn accepted_output_forms() -> Vec { + let p = ["eprint", "ln"].concat(); + vec![ + format!("{}!(\"{}\", line)", p, "{}"), // eprintln!("{}", line) + format!("{}!(\"{{line}}\")", p), // eprintln!("{line}") + format!("{}!({{line}})", p), // eprintln!({line}) + ] + } + + /// 这段输出文本是不是「打印共享的那一行 `line`」的合法写法。 + fn is_shared_line_output(s: &str) -> bool { + accepted_output_forms().iter().any(|a| a == s) } /// 不兼容路径的**期望整行**(`peer` = 净化后的对端声明值)。 @@ -690,6 +765,18 @@ mod tests { assert_eq!(s2.len(), LOG_MAX_LEN - 1); } + #[test] + fn sanitize_truncation_boundary_is_pinned() { + // 62 字节 + 1 字节 + ANSI 序列 + 若干字节: + // ANSI 序列被**吃掉**(不产出内容、也不占预算)⇒ 仍能补满到 64 字节。 + let raw = format!("{}a\u{1b}[31m{}", "x".repeat(LOG_MAX_LEN - 2), "y".repeat(10)); + let s = sanitize_for_log(&raw); + assert_eq!(s.len(), LOG_MAX_LEN, "截断边界:ESC 序列被吃掉后仍能补满 64 字节"); + assert!(s.starts_with(&"x".repeat(LOG_MAX_LEN - 2)), "前缀必须保留"); + assert!(s.ends_with('y'), "结尾必须是被截断后剩下的内容"); + assert!(!s.contains('\u{1b}'), "ESC 不得残留"); + } + #[test] fn judgment_uses_raw_value_not_sanitized() { // 净化后是 "1.0"(major 相同 ⇒ 兼容),但判定必须用原值 ⇒ 原值不可解析 ⇒ 仍判不兼容 @@ -860,6 +947,21 @@ mod tests { assert_eq!(warn_recorder::emitted_count(), 2, "两个不同的 key ⇒ 两行 WARN"); } + #[test] + fn emitted_count_counts_raw_lines_not_distinct_lines() { + // 🔴 两个**不同 key**、**同样消息体** ⇒ 原始行数 = 2,相异行数 = 1。 + // 这里必须断言 2 ⇒ 「计数器被改成去重」会当场变红。 + let _g = test_guard(); + reset_warn_state(); + assert!(warn_once("test:count:a", "同样的消息体")); + assert!(warn_once("test:count:b", "同样的消息体")); + assert_eq!( + warn_recorder::emitted_count(), + 2, + "emitted_count 必须数「实际发出的行数」,不是相异行数" + ); + } + #[test] fn compatible_declaration_emits_no_warn_line() { // 副作用的**反向**:不该告警时就一行都不许打 @@ -906,6 +1008,43 @@ mod tests { assert_eq!(line, "[tdc-connector] WARN 内容", "整行内容必须逐字匹配"); } + #[test] + fn raw_message_from_sibling_module_cannot_forge_a_log_line() { + // 🔴 兄弟模块(`pub fn warn_once`)可以把未净化值传进来: + // 但输出层必须把它剥干净 ⇒ 伪造不了第二条日志行、也注入不了终端转义。 + let _g = test_guard(); + reset_warn_state(); + let raw = "跨端协议版本不兼容(对端 2.0\u{1b}[31m\nFORGED-LOG-LINE)"; + assert!(warn_once("test:raw-sibling", raw), "首次应真的告警"); + let line = warn_recorder::last().expect("应发出了一条 WARN"); + assert_eq!(warn_recorder::emitted_count(), 1, "伪造的换行不得变成第二条日志行"); + assert!(!line.contains('\u{1b}'), "ESC 不得进日志:{:?}", line); + assert!(!line.contains('\n') && !line.contains('\r'), "换行不得进日志:{:?}", line); + assert!(line.contains("FORGED-LOG-LINE"), "内容应保留(只剥不删):{:?}", line); + assert!(line.starts_with("[tdc-connector] WARN "), "前缀必须保留:{:?}", line); + } + + #[test] + fn scrub_for_log_does_not_truncate_long_messages() { + let long = "中".repeat(200); + let s = scrub_for_log(&long); + assert_eq!(s.len(), long.len(), "scrub 只剥不截"); + assert!(s.len() > LOG_MAX_LEN, "scrub 后的长度可以超过 64 字节"); + } + + #[test] + fn emit_warn_keeps_fixed_path_message_intact() { + // 🔴 固定路径消息整行**长于** `LOG_MAX_LEN`(64 字节)⇒ 输出层若用 + // `sanitize_for_log` 会被截断 ⇒ 这里钉住「整行未被截断」。 + let _g = test_guard(); + reset_warn_state(); + let _ = check_protocol_with_warn(None); + let line = warn_recorder::last().expect("应发出了一条 WARN"); + assert!(line.len() > LOG_MAX_LEN, "固定路径整行不得被截断到 64 字节:{:?}", line); + assert!(line.contains(PROTOCOL_VERSION_HEADER), "header 名必须在:{:?}", line); + assert!(line.ends_with(')'), "结尾不得被截断:{:?}", line); + } + #[test] fn missing_declaration_message_states_header_and_version() { // 🔴 消息**内容**必须被钉住:header 名、本端版本、二者顺序 @@ -913,10 +1052,17 @@ mod tests { reset_warn_state(); let _ = check_protocol_with_warn(None); let line = warn_recorder::last().expect("应发出了一条 WARN"); + // 🔴 **就地写死**的独立期望值(**不调用** `expected_missing_line()`): + // 固定路径的期望整行有**两份互相独立**的写法(本函数 = `format!` 模板; + // `expected_missing_line()` = 拼接),彼此**不共用任何 helper** + // ⇒ 「同步改写生产模板 + 其中一份」⇒ **另一边必然 RED**。 assert_eq!( line, - expected_missing_line(), - "固定路径告警行必须逐字匹配(含 header 名与本端版本)" + format!( + "[tdc-connector] WARN 跨端请求未声明 X-Protocol-Version,按兼容期放行(本端 {})", + PROTOCOL_VERSION + ), + "固定路径告警行必须逐字匹配(独立硬编码期望值,不得与生产模板同源)" ); } @@ -962,18 +1108,25 @@ mod tests { ); let at = hits[0]; let call_end = at + body[at..].find(';').expect("输出语句必须以分号结尾"); - let p = ["eprint", "ln"].concat(); - let accepted = [ - format!("{}!(\"{}\", line)", p, "{}"), - format!("{}!({{line}})", p), - ]; assert!( - accepted.iter().any(|a| a == &body[at..call_end]), + is_shared_line_output(&body[at..call_end]), "真实输出必须打印共享的那一行 `line`,实际:{:?}", &body[at..call_end] ); } + #[test] + fn accepted_output_forms_cover_every_legal_inline_form() { + let p = ["eprint", "ln"].concat(); + // 三种合法写法都必须被接受 + assert!(is_shared_line_output(&format!("{}!(\"{}\", line)", p, "{}"))); + assert!(is_shared_line_output(&format!("{}!(\"{{line}}\")", p))); + assert!(is_shared_line_output(&format!("{}!({{line}})", p))); + // 打错变量必须被拒绝 + assert!(!is_shared_line_output(&format!("{}!(\"{}\", message)", p, "{}"))); + assert!(!is_shared_line_output(&format!("{}!(\"{{}}\")", p))); + } + /// 子进程探针:**只在子进程里跑**(父用例用 `--exact ... --ignored --nocapture` 启动它)。 /// /// ⚠️ libtest 的输出捕获是**线程局部**的 ⇒ 父进程里普通线程的输出仍会被 libtest 吞掉