diff --git a/src/protocol.rs b/src/protocol.rs index 33f2efd..1fffc0d 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -19,6 +19,9 @@ //! 🔴 净化的**调用点**同样有保护:打进日志的 key 与消息体只接受 `SafePeer`(已净化的 //! 对端声明值),而 `SafePeer` 只能经 `SafePeer::new` 构造 ⇒ 调用点在**类型上**没法把 //! 未净化的对端值送进日志。 +//! +//! 🔴 净化的**出口**同样被封住:变量 key 的告警入口 `warn_once_variable` 是**模块私有** +//! ⇒ crate 内的兄弟模块既拿不到它,也没法用它把裸 `&str` 打进日志。 use std::collections::HashSet; use std::sync::{Mutex, MutexGuard, OnceLock}; @@ -105,32 +108,49 @@ fn claim_variable_key(set: &Mutex>, key: &str) -> bool { /// /// ⚠️ **调用方必须已在 `claim_*` 返回之后调用本函数** —— 集合锁在 `claim_*` 内部即释放; /// 本函数**绝不取集合锁**(不许持锁做 IO)。 +/// +/// 🔴 **完整输出行只构造一次**:真实输出与测试记录器共享**同一个**字符串 `line` +/// ⇒ 二者不可能分叉(不会一个记 A、一个打 B)。 +/// ⚠️ stable 没有可用的**进程内** stderr 捕获手段(`std::io::set_output_capture` 是 `#[unstable]`) +/// ⇒ 「这一行真的落到了 fd 2」由**子进程**用例实测;本函数只保证「那一行还在、且内容是共享的那一行」。 fn emit_warn(message: &str) { + let line = format!("[tdc-connector] WARN {}", message); + eprintln!("{}", line); #[cfg(test)] - warn_recorder::record(message); - eprintln!("[tdc-connector] WARN {}", message); + warn_recorder::record(&line); } /// 测试用的告警记录器:**只存在于测试构建**。 /// -/// stable 没有可用的 stderr 捕获手段(`std::io::set_output_capture` 是 `#[unstable]`), -/// 而「最终写出去的那条消息」必须被端到端断言 ⇒ 这里记录最近一条告警消息。 +/// 记录的是**真实输出行**(含 `[tdc-connector] WARN ` 前缀),与 `emit_warn` 共享同一个字符串。 +/// +/// 🔴 **线程局部**(`thread_local!`)⇒ libtest 每个用例一个线程 ⇒ 并行跑的用例之间 +/// **互不污染** ⇒ 「实际发出了几行」这类计数断言不会被别的模块的告警干扰。 #[cfg(test)] mod warn_recorder { - use std::sync::Mutex; + use std::cell::RefCell; - static LAST: Mutex> = Mutex::new(None); - - pub(super) fn record(message: &str) { - *LAST.lock().unwrap_or_else(|e| e.into_inner()) = Some(message.to_string()); + thread_local! { + static EMITTED: RefCell> = const { RefCell::new(Vec::new()) }; } + /// 记录一条**真实输出行**。 + pub(super) fn record(line: &str) { + EMITTED.with(|v| v.borrow_mut().push(line.to_string())); + } + + /// **实际发出的行数**(不是「登记了几个 key」—— 两者差别正是本模块的核心不变式)。 + pub(super) fn emitted_count() -> usize { + EMITTED.with(|v| v.borrow().len()) + } + + /// 最近一条发出的行。 pub(super) fn last() -> Option { - LAST.lock().unwrap_or_else(|e| e.into_inner()).clone() + EMITTED.with(|v| v.borrow().last().cloned()) } pub(super) fn clear() { - *LAST.lock().unwrap_or_else(|e| e.into_inner()) = None; + EMITTED.with(|v| v.borrow_mut().clear()); } } @@ -177,7 +197,8 @@ pub fn is_protocol_acceptable(declared: Option<&str>) -> bool { /// 同 key 只告警一次。返回 true = 本次真的告警了。 /// /// ⚠️ **key 必须是编译期常量**(与对端输入无关)—— 固定 key 永不受集合上限约束, -/// 任何时候都能告警。key 里含对端可控内容时请改用 `warn_once_variable`。 +/// 任何时候都能告警。key 里含对端可控内容时**只能**用模块内部的 +/// `warn_once_variable`(它收已净化的值,本模块外无出口)。 /// /// 对端派生的动态 key 走不通这条路(编译期拒绝): /// @@ -187,6 +208,15 @@ pub fn is_protocol_acceptable(declared: Option<&str>) -> bool { /// warn_once(&dynamic, "x"); /// ``` /// +/// 🔴 上面的 `compile_fail` 只保证「**动态 `String` 传不进来**」。 +/// ⚠️ 它对「**路径写错**」也会判通过(未解析的 import 同样是编译不过)⇒ +/// 必须有下面这条**正向** doctest 把 crate 路径钉死,否则 `compile_fail` 会假通过。 +/// +/// ```no_run +/// use tdc_connector::protocol::warn_once; +/// warn_once("protocol:missing", "x"); +/// ``` +/// /// ⚠️ **诚实限定**:`&'static str` 不是万无一失 —— `Box::leak` / `String::leak` 仍能造出 /// `&'static str`(Rust 类型系统的固有极限,doctest 也拦不住该形态)。 /// 真正的硬保证是**结构上的**:非测试代码里 `warn_once` 只有一处调用点 @@ -205,7 +235,12 @@ pub fn warn_once(key: &'static str, message: &str) -> bool { /// /// 用于 key 含对端可控内容(如声明的协议版本)的场景:对端即使灌爆集合, /// 也只是让**新的**变量告警不再产生,**不会**让固定 key 的告警失效。 -pub(crate) fn warn_once_variable(key: &str, message: &str) -> bool { +/// +/// 🔴 **模块私有**:变量 key 的告警是本模块的**内部实现细节**。 +/// 它收**裸 `&str`**(key 与消息体),若留 crate 级可见性,**兄弟模块**就能用它把 +/// **未净化**的对端字节直接打进日志 —— 那会绕过 `SafePeer` 这道 newtype 闸门。 +/// 降为模块私有后,crate 内**没有任何**调用点能构造未净化的变量告警。 +fn warn_once_variable(key: &str, message: &str) -> bool { if claim_variable_key(variable_warned_keys(), key) { emit_warn(message); true @@ -344,6 +379,26 @@ mod tests { warn_recorder::clear(); } + /// 固定路径(未声明协议版本)的**期望整行**。 + /// + /// 🔴 期望值必须与被测代码**独立**(这里硬编码 header 名与文案模板, + /// 只用 `PROTOCOL_VERSION` 取本端版本)⇒ 否则「消息内容被改坏」这类变异会 + /// 顺手把期望值一起改掉 ⇒ 假通过。 + fn expected_missing_line() -> String { + format!( + "[tdc-connector] WARN 跨端请求未声明 X-Protocol-Version,按兼容期放行(本端 {})", + PROTOCOL_VERSION + ) + } + + /// 不兼容路径的**期望整行**(`peer` = 净化后的对端声明值)。 + fn expected_incompatible_line(peer: &str) -> String { + format!( + "[tdc-connector] WARN 跨端协议版本不兼容(对端 {},本端 {}),请升级对端", + peer, PROTOCOL_VERSION + ) + } + #[test] fn parses_major_and_minor() { assert_eq!(parse_version("1.0"), Some((1, 0))); @@ -414,6 +469,12 @@ mod tests { lock_set(fixed_warned_keys()).contains("protocol:missing"), "公开 check_protocol 必须真的走告警通道(brief 契约:带一次性 WARN)" ); + // 🔴 集合里有 key **不等于**告警发出去了 ⇒ 还要断言**真的打出了一行** + assert_eq!( + warn_recorder::emitted_count(), + 1, + "固定路径必须真的打出一行 WARN(集合里有 key 不算数)" + ); } #[test] @@ -540,6 +601,12 @@ mod tests { assert!(warned <= 256, "洪水量必须封顶(brief 约定 256),实际 {} 条", warned); assert_eq!(WARN_ONCE_MAX_KEYS, 256, "上限是 brief 约定的 256"); assert!(lock_set(variable_warned_keys()).len() <= WARN_ONCE_MAX_KEYS); + // 🔴 布尔计数对了**不等于**副作用没放大:还要断言**实际打出的行数** + assert!( + warn_recorder::emitted_count() <= 256, + "实际打出的行数必须封顶(brief 约定 256),实际 {} 行", + warn_recorder::emitted_count() + ); } #[test] @@ -599,6 +666,8 @@ mod tests { #[test] fn sanitize_truncates_long_values() { + // 🔴 净化上限是 brief 约定的 64 **字节**(用字面量钉住 ⇒ 上限被放大/缩小都变红) + assert_eq!(LOG_MAX_LEN, 64, "净化上限是 brief 约定的 64 字节"); let long = "9".repeat(200); let s = sanitize_for_log(&long); assert_eq!(s.len(), LOG_MAX_LEN); @@ -695,9 +764,11 @@ mod tests { "变量 key 前缀身份:{}", key ); - assert!( - key.ends_with(peer.as_str()), - "变量 key 必须带上净化后的对端值:{}", + // 🔴 精确比对(不是 `ends_with`)——`ends_with` 在对端值为空时会退化成空断言 + assert_eq!( + key, + &format!("protocol:incompatible:{}", peer.as_str()), + "变量 key 必须**精确**等于「前缀 + 净化后的对端值」:{}", key ); assert!(!key.contains('\u{1b}'), "key 不得含 ESC:{}", key); @@ -712,19 +783,249 @@ mod tests { } #[test] - fn incompatible_warning_message_is_sanitized_end_to_end() { - // 最终**写出去的那条消息**必须被净化(不看纯函数,只看产物) + fn incompatible_warning_message_line_is_sanitized() { + // ⚠️ **不是端到端的 stderr 断言**:这里看的是**测试替身**(记录器)记下的那一行。 + // 「这一行真的落到了 fd 2」由 `stderr_really_receives_the_exact_warn_lines`(子进程)负责。 let _g = test_guard(); reset_warn_state(); let _ = check_protocol_with_warn(Some("2.0\u{1b}[31m\n伪造行\u{85}")); - let msg = warn_recorder::last().expect("应发出了一条 WARN"); - assert!(!msg.contains('\u{1b}'), "消息不得含 ESC:{:?}", msg); - assert!(!msg.contains('\n'), "消息不得含换行:{:?}", msg); - assert!(!msg.contains('\u{85}'), "消息不得含 NEL:{:?}", msg); + let line = warn_recorder::last().expect("应发出了一条 WARN"); + assert!(!line.contains('\u{1b}'), "消息不得含 ESC:{:?}", line); + assert!(!line.contains('\n'), "消息不得含换行:{:?}", line); + assert!(!line.contains('\u{85}'), "消息不得含 NEL:{:?}", line); assert!( - !msg.chars().any(|c| c.is_control()), + !line.chars().any(|c| c.is_control()), "消息不得含控制字符:{:?}", - msg + line + ); + // 🔴 整行必须**逐字**等于期望值(含前缀、对端净化值、本端版本、标签顺序) + assert_eq!( + line, + expected_incompatible_line("2.0伪造行"), + "告警整行必须逐字匹配(净化后对端值 = \"2.0伪造行\")" + ); + } + + // ---- 告警副作用:发不发 / 发几次 / 发什么 ---- + + #[test] + fn same_declaration_emits_exactly_one_warn_line() { + // 🔴 「同 key 只告警一次」必须在**输出次数**层被断言: + // 只断言布尔返回值(`warned`)不够 —— 副作用多发 4 倍时布尔值依然是对的。 + let _g = test_guard(); + reset_warn_state(); + for i in 0..5 { + let (allowed, warned) = check_protocol_with_warn(Some("8.8")); + assert!(!allowed, "major 不同 ⇒ 拒绝"); + if i == 0 { + assert!(warned, "第一次不兼容 ⇒ 应告警"); + } else { + assert!(!warned, "同一声明值只应告警一次(第 {} 次)", i + 1); + } + } + assert_eq!( + warn_recorder::emitted_count(), + 1, + "同一声明值只应真的打出一行 WARN" + ); + } + + #[test] + fn missing_declaration_emits_exactly_one_warn_line() { + let _g = test_guard(); + reset_warn_state(); + for i in 0..5 { + let (allowed, warned) = check_protocol_with_warn(None); + assert!(allowed, "未声明 ⇒ 兼容期放行"); + if i == 0 { + assert!(warned, "第一次未声明 ⇒ 应告警"); + } else { + assert!(!warned, "同一声明值只应告警一次(第 {} 次)", i + 1); + } + } + assert_eq!( + warn_recorder::emitted_count(), + 1, + "固定路径:同一声明值只应真的打出一行 WARN" + ); + } + + #[test] + fn distinct_warnings_emit_one_line_each() { + // 计数器必须**累加**(不是「置 1」)⇒ 两个不同的 key 必须打两行 + let _g = test_guard(); + reset_warn_state(); + assert!(warn_once("test:distinct:a", "A")); + assert!(warn_once("test:distinct:b", "B")); + assert_eq!(warn_recorder::emitted_count(), 2, "两个不同的 key ⇒ 两行 WARN"); + } + + #[test] + fn compatible_declaration_emits_no_warn_line() { + // 副作用的**反向**:不该告警时就一行都不许打 + let _g = test_guard(); + reset_warn_state(); + let (allowed, warned) = check_protocol_with_warn(Some("1.9")); + assert!(allowed, "同 major ⇒ 放行"); + assert!(!warned, "兼容的声明不该告警"); + assert_eq!( + warn_recorder::emitted_count(), + 0, + "兼容的声明不得打任何 WARN" + ); + } + + #[test] + fn flood_emitted_line_count_is_capped_at_256() { + // 🔴 「洪水量封顶」必须在**实际输出行数**层被断言 + // (不是布尔计数、不是集合长度 —— 那两个在副作用放大时依然是对的) + let _g = test_guard(); + reset_warn_state(); + for i in 0..1024 { + let _ = warn_once_variable(&format!("test:volume4:{}", i), "灌水"); + } + assert!( + warn_recorder::emitted_count() <= 256, + "实际打出的行数必须封顶(brief 约定 256),实际 {} 行", + warn_recorder::emitted_count() + ); + } + + #[test] + fn emitted_line_carries_the_warn_prefix() { + // 🔴 前缀是运维检索这条信号的方式(「老客户端还在线上」)⇒ 必须被钉住 + let _g = test_guard(); + reset_warn_state(); + warn_once("test:prefix:x", "内容"); + let line = warn_recorder::last().expect("应发出了一条 WARN"); + assert!( + line.starts_with("[tdc-connector] WARN "), + "告警行必须带 [tdc-connector] WARN 前缀:{:?}", + line + ); + assert_eq!(line, "[tdc-connector] WARN 内容", "整行内容必须逐字匹配"); + } + + #[test] + fn missing_declaration_message_states_header_and_version() { + // 🔴 消息**内容**必须被钉住:header 名、本端版本、二者顺序 + let _g = test_guard(); + reset_warn_state(); + let _ = check_protocol_with_warn(None); + let line = warn_recorder::last().expect("应发出了一条 WARN"); + assert_eq!( + line, + expected_missing_line(), + "固定路径告警行必须逐字匹配(含 header 名与本端版本)" + ); + } + + #[test] + fn incompatible_message_states_peer_and_local_version() { + // 🔴 「对端/本端」标签不可对调,且两个版本号都必须出现 + let msg = incompatible_message(&SafePeer::new("2.0")); + assert_eq!( + msg, + format!( + "跨端协议版本不兼容(对端 2.0,本端 {}),请升级对端", + PROTOCOL_VERSION + ), + "不兼容消息必须逐字匹配(对端 = 净化后的对端值,本端 = PROTOCOL_VERSION)" + ); + } + + // ---- 源级守卫 + 子进程真捕获:钉住「真实输出通道还在、且内容正确」 ---- + + /// 源级守卫:`emit_warn` 里必须**恰好一处**把共享的 `line` 打到标准错误。 + /// + /// 为什么需要它:记录器是**测试替身** ⇒ 真实输出整行被删掉时它照旧记录 + /// ⇒ 只靠记录器断言抓不到「告警通道整个消失」。 + /// + /// ⚠️ 本守卫是**文本**守卫:它钉住「那一行还在、且打印的是共享的 `line`」, + /// 但**不能**证明「这条输出真的落到了 fd 2」—— 那由子进程用例负责。 + #[test] + fn emit_warn_source_prints_the_shared_line_exactly_once() { + let src = include_str!("protocol.rs"); + let start = src.find("fn emit_warn(").expect("emit_warn 必须存在"); + let tail = &src[start..]; + let end = tail.find("\n}").expect("emit_warn 必须有函数体"); + let body = &tail[..end]; + + // 🔴 needle 在**运行时**拼接 ⇒ 本文件源码里不会出现连续的该词 ⇒ 不会自匹配 + let needle = ["eprint", "ln!"].concat(); + let hits: Vec = body.match_indices(needle.as_str()).map(|(i, _)| i).collect(); + assert_eq!( + hits.len(), + 1, + "emit_warn 里必须恰好一处真实标准错误输出:{:?}", + body + ); + 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]), + "真实输出必须打印共享的那一行 `line`,实际:{:?}", + &body[at..call_end] + ); + } + + /// 子进程探针:**只在子进程里跑**(父用例用 `--exact ... --ignored --nocapture` 启动它)。 + /// + /// ⚠️ libtest 的输出捕获是**线程局部**的 ⇒ 父进程里普通线程的输出仍会被 libtest 吞掉 + /// ⇒ 必须靠**子进程**才能看到真实的 fd 2。 + #[test] + #[ignore] + fn stderr_probe_helper() { + // 只负责在子进程里触发两条真实告警;断言全在父用例里做。 + let _ = check_protocol_with_warn(None); + let _ = check_protocol_with_warn(Some("9.9")); + } + + #[test] + fn stderr_really_receives_the_exact_warn_lines() { + let exe = std::env::current_exe().expect("应能拿到测试二进制路径"); + let out = std::process::Command::new(&exe) + .args([ + "--exact", + "protocol::tests::stderr_probe_helper", + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .output() + .expect("应能启动子进程"); + let stdout = String::from_utf8_lossy(&out.stdout).to_string(); + let stderr = String::from_utf8_lossy(&out.stderr).to_string(); + assert!( + stdout.contains("1 passed"), + "子进程必须真的跑到那条 helper 用例:stdout={:?}", + stdout + ); + + let missing = expected_missing_line(); + let incompatible = expected_incompatible_line("9.9"); + for line in [&missing, &incompatible] { + assert_eq!( + stderr.lines().filter(|l| *l == line.as_str()).count(), + 1, + "真实 stderr 里这一行必须恰好出现一次:{:?}\nstderr={:?}", + line, + stderr + ); + } + assert_eq!( + stderr + .lines() + .filter(|l| l.starts_with("[tdc-connector] WARN ")) + .count(), + 2, + "真实 stderr 里恰好两条 WARN 行:stderr={:?}", + stderr ); } }