From 78575abf7adc07ec09092f4ba9c2973e2033d744 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:56:53 +0800 Subject: [PATCH 1/4] feat(guard): redact Chinese resident ID and bank card numbers out of the box Two built-in redaction rules, both on by default, in a new `personal` kind. Like the credential rules, they only take what can be checked by structure: - `cn-resident-id`: an 18-character resident ID number whose first two digits are a GB/T 2260 province-level code, whose digits 7-14 are a real date between 1900-01-01 and today (Beijing time), and whose last character is the ISO 7064 MOD 11-2 check character. The 15-digit format is not matched. - `bank-card`: a number that passes the Luhn check and whose prefix and length belong to UnionPay, Visa, Mastercard, American Express, JCB, Discover or Diners Club. Written as one run of digits, or in groups of four separated by a single space or a single hyphen (American Express also 4-6-5, Diners Club also 4-6-4). A short trailing group that breaks the number (an expiry month, a security code) is dropped and the rest checked again. The public test card numbers of Stripe, Braintree and Adyen are excluded; the list lives next to the network table. Both match whole tokens only, so a valid number inside a longer digit run or an encoded string is left alone. A token that is a valid ID number is never handed to the card rule, even when the ID rule is off. Their placeholders say what was there (`<>`, `<>`): built-in rules can now carry a placeholder label (`Builtin.label`), and restoration, streaming included, already works per label. Reported excerpts keep only the last four characters. Protocol: `Matcher` gains `cn-resident-id` (`born_since`) and `bank-card` (`networks`, with `CardNetwork` and `CardPrefix`); `SecretKind` gains `personal`. Rule sets built from `RuleSet::none()` (ThinkWatch Enterprise) are unaffected. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/src/lib.rs | 70 +- crates/tw-config/src/security.rs | 2 +- crates/tw-config/tests/manual/schema.rs | 4 +- crates/tw-control/src/security.rs | 40 + crates/tw-gateway/src/fixture.rs | 2 +- crates/tw-gateway/src/wire.rs | 1 + crates/tw-gateway/tests/m5_redact.rs | 85 +- crates/tw-gateway/tests/replay.rs | 2 +- crates/tw-guard/src/lib.rs | 8 +- crates/tw-guard/src/redact/rules.rs | 1144 ++++++++++++++++++++++- docs/config.md | 29 +- docs/config.zh-CN.md | 13 +- 12 files changed, 1342 insertions(+), 58 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 4e175a55..7d0b0c7f 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -246,6 +246,8 @@ slug_enum! { PrivateKeys = "private-keys", Jwt = "jwt", ConnStrings = "conn-strings", + /// 身份证号、银行卡号:个人信息,不是凭据 + Personal = "personal", /// 内网地址 Internal = "internal", /// 自定义规则找到的 @@ -3961,10 +3963,12 @@ pub struct SecretItem { pub rule: String, #[serde(default)] pub custom: bool, - /// 类别:`api-keys` / `private-keys` / `jwt` / `conn-strings` / `internal` / `custom` + /// 类别:`api-keys` / `private-keys` / `jwt` / `conn-strings` / `personal` / + /// `internal` / `custom` pub kind: SecretKind, /// **已打码。**报出来的东西一律打码 —— 「发现了 sk-ant-xxx」这句话本身 - /// 就是一次泄漏。内网地址和内部域名例外,它们不是凭据 + /// 就是一次泄漏。内网地址和内部域名例外,它们不是凭据;身份证号和卡号只留 + /// 最后四位(`…1234`) pub masked: String, pub count: u64, } @@ -4135,6 +4139,14 @@ pub enum Matcher { PrivateIp, /// 以这几个后缀结尾的域名 DomainSuffix { suffixes: Vec }, + /// 18 位的中华人民共和国居民身份证号码:头两位是省级行政区划代码,第 7–14 位 + /// 是 `born_since` 年 1 月 1 日到今天之间的真实日期,末位是对得上的 + /// ISO 7064 MOD 11-2 校验码(`0`–`9` 或 `X`)。15 位的老号码不认 + CnResidentId { born_since: u16 }, + /// 卡号:开头和位数属于其中一家卡组织,并且通过 Luhn 校验。连着写的,或者 + /// 四位一组、用一个空格或一个连字符隔开的(最后一组可以不足四位;American + /// Express 另有 4-6-5、Diners Club 另有 4-6-4)。公开的测试卡号不算 + BankCard { networks: Vec }, /// 正则表达式:工具调用审查的全部规则,和各项防护的自定义规则 Regex { pattern: String }, /// 不分大小写的子串:内容过滤的关键词规则 @@ -4143,6 +4155,25 @@ pub enum Matcher { Codepoints { ranges: Vec }, } +/// 一家卡组织认哪些卡号:以哪几段开头、一共几位。 +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct CardNetwork { + /// 英文名(`UnionPay`、`Visa` …)。界面按它查自己的名称表 + pub name: String, + pub prefixes: Vec, + /// 一共几位 + pub lengths: Vec, +} + +/// 卡号开头的一段,含两头、两头位数相同:`51`–`55`。只有一个数时两头相同。 +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "ts", derive(ts_rs::TS))] +pub struct CardPrefix { + pub from: u32, + pub to: u32, +} + /// 一条规则。 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -4446,6 +4477,41 @@ mod tests { assert_eq!(v["model"], "claude-sonnet-5"); } + #[test] + fn the_personal_number_matchers_say_what_they_check() { + // 界面按 `kind` 写成自己的话,号段和位数照着画 + let id = serde_json::to_value(Matcher::CnResidentId { born_since: 1900 }).unwrap(); + assert_eq!( + id, + serde_json::json!({ "kind": "cn-resident-id", "born_since": 1900 }) + ); + let card = serde_json::to_value(Matcher::BankCard { + networks: vec![CardNetwork { + name: "Mastercard".into(), + prefixes: vec![ + CardPrefix { from: 51, to: 55 }, + CardPrefix { + from: 2221, + to: 2720, + }, + ], + lengths: vec![16], + }], + }) + .unwrap(); + assert_eq!( + card, + serde_json::json!({ + "kind": "bank-card", + "networks": [{ + "name": "Mastercard", + "prefixes": [{ "from": 51, "to": 55 }, { "from": 2221, "to": 2720 }], + "lengths": [16], + }], + }) + ); + } + #[test] fn every_event_exposes_its_request_id() { // UI 靠 id 把四个事件缝成一行。 diff --git a/crates/tw-config/src/security.rs b/crates/tw-config/src/security.rs index 4a5abe57..4b599c29 100644 --- a/crates/tw-config/src/security.rs +++ b/crates/tw-config/src/security.rs @@ -140,7 +140,7 @@ pub struct CustomToolRule { pub disabled: bool, } -/// 出站脱敏:请求发出前,按规则查找凭据。拦截档的动作是**替换**。 +/// 出站脱敏:请求发出前,按规则查找凭据和个人号码。拦截档的动作是**替换**。 #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct RedactPolicy { diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 13b19b43..5cc1142e 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -916,8 +916,8 @@ pub fn sections() -> Vec
{ Kind::Obj("security.redact"), Def::Section, t( - "Outbound redaction: credentials found in a request are replaced before it leaves.", - "出站脱敏:请求发出前,把其中的凭据替换掉。", + "Outbound redaction: credentials, Chinese resident ID numbers and bank card numbers found in a request are replaced before it leaves.", + "出站脱敏:请求发出前,把其中的凭据、身份证号和银行卡号替换掉。", ), ), row( diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index ae914d92..53dfc39a 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -244,6 +244,21 @@ fn matcher(m: &tw_guard::redact::rules::Matcher) -> tw_api::Matcher { M::DomainSuffix { suffixes } => tw_api::Matcher::DomainSuffix { suffixes: suffixes.iter().map(|s| s.to_string()).collect(), }, + M::CnResidentId { born_since } => tw_api::Matcher::CnResidentId { born_since }, + M::BankCard { networks } => tw_api::Matcher::BankCard { + networks: networks + .iter() + .map(|n| tw_api::CardNetwork { + name: n.name.to_string(), + prefixes: n + .prefixes + .iter() + .map(|&(from, to)| tw_api::CardPrefix { from, to }) + .collect(), + lengths: n.lengths.to_vec(), + }) + .collect(), + }, } } @@ -920,6 +935,31 @@ mod tests { min_tail: 20 } ); + // 两条个人号码的规则出厂就开着,判据带着界面要画的细节 + let id = v.rules.iter().find(|r| r.id == "cn-resident-id").unwrap(); + assert!(id.enabled && id.on_by_default); + assert_eq!(id.kind, "personal"); + assert_eq!( + id.matcher, + tw_api::Matcher::CnResidentId { born_since: 1900 } + ); + let card = v.rules.iter().find(|r| r.id == "bank-card").unwrap(); + assert!(card.enabled && card.on_by_default); + let tw_api::Matcher::BankCard { networks } = &card.matcher else { + panic!("{:?}", card.matcher); + }; + let amex = networks + .iter() + .find(|n| n.name == "American Express") + .unwrap(); + assert_eq!( + amex.prefixes, + vec![ + tw_api::CardPrefix { from: 34, to: 34 }, + tw_api::CardPrefix { from: 37, to: 37 } + ] + ); + assert_eq!(amex.lengths, vec![15]); } #[test] diff --git a/crates/tw-gateway/src/fixture.rs b/crates/tw-gateway/src/fixture.rs index cc682ddf..6aef83f0 100644 --- a/crates/tw-gateway/src/fixture.rs +++ b/crates/tw-gateway/src/fixture.rs @@ -199,7 +199,7 @@ fn collect(v: &serde_json::Value, out: &mut Extracted) { /// 录一个用例。**脱敏在这一步做,不是事后。** /// /// 规则开全部内置的 —— 录制不该按用户此刻的配置决定脱什么,它要脱的是 -/// 「任何可能是凭据的东西」。 +/// 「任何可能是凭据或者个人号码的东西」。 pub fn record( name: &str, note: &str, diff --git a/crates/tw-gateway/src/wire.rs b/crates/tw-gateway/src/wire.rs index 0607cd13..b0029344 100644 --- a/crates/tw-gateway/src/wire.rs +++ b/crates/tw-gateway/src/wire.rs @@ -97,6 +97,7 @@ pub fn secret_kind(k: tw_guard::redact::rules::Kind) -> tw_api::SecretKind { Kind::PrivateKeys => tw_api::SecretKind::PrivateKeys, Kind::Jwt => tw_api::SecretKind::Jwt, Kind::ConnStrings => tw_api::SecretKind::ConnStrings, + Kind::Personal => tw_api::SecretKind::Personal, Kind::Internal => tw_api::SecretKind::Internal, Kind::Custom => tw_api::SecretKind::Custom, } diff --git a/crates/tw-gateway/tests/m5_redact.rs b/crates/tw-gateway/tests/m5_redact.rs index d6af207b..76d28e97 100644 --- a/crates/tw-gateway/tests/m5_redact.rs +++ b/crates/tw-gateway/tests/m5_redact.rs @@ -34,10 +34,11 @@ async fn start_upstream(sse: bool) -> (SocketAddr, Arc>>) { move |State(s): State>>>, body: bytes::Bytes| async move { *s.lock().unwrap() = body.to_vec(); let text = String::from_utf8_lossy(&body).to_string(); - // 把请求里出现的东西挑出来放进回答里 + // 把请求里出现的东西挑出来放进回答里:占位符(`<>`、 + // `<>` …),或者没换掉的原值 let echoed = text .split('"') - .find(|p| p.contains("<>,卡号 <>,"), + "{sent}" + ); + let joined: String = got + .lines() + .filter_map(|l| l.strip_prefix("data: ")) + .filter_map(|d| serde_json::from_str::(d).ok()) + .filter_map(|v| v["delta"]["text"].as_str().map(|s| s.to_string())) + .collect(); + assert_eq!(joined, format!("身份证 {id},卡号 {card},帮我填表")); + assert!(!got.contains("_NUMBER_"), "占位符漏给客户端了:{got}"); + + let mut items = None; + while let Ok(Ok(ev)) = tokio::time::timeout(Duration::from_secs(3), rx.recv()).await { + if let tw_api::Event::SecretsFound { items: it, .. } = ev { + items = Some(it); + break; + } + } + let mut items = items.expect("没发脱敏事件"); + items.sort_by(|a, b| a.rule.cmp(&b.rule)); + let reported: Vec<(&str, String, &str)> = items + .iter() + .map(|i| { + ( + i.rule.as_str(), + i.kind.slug().to_string(), + i.masked.as_str(), + ) + }) + .collect(); + assert_eq!( + reported, + vec![ + ("bank-card", "personal".to_string(), "…7894"), + ("cn-resident-id", "personal".to_string(), "…002X"), + ] + ); +} diff --git a/crates/tw-gateway/tests/replay.rs b/crates/tw-gateway/tests/replay.rs index 902fbc2b..e01b709a 100644 --- a/crates/tw-gateway/tests/replay.rs +++ b/crates/tw-gateway/tests/replay.rs @@ -52,7 +52,7 @@ fn no_fixture_carries_a_credential() { // 的用例不走导出那条路。 for (name, f) in load_all() { let dump = serde_yaml_ng::to_string(&f).unwrap(); - // 内置的凭据规则全开,内网地址不算(夹具里的 10.x 是示意) + // 内置规则全开(凭据和个人号码),内网地址不算(夹具里的 10.x 是示意) let all: Vec<&str> = tw_guard::redact::rules::BUILTINS .iter() .map(|b| b.id) diff --git a/crates/tw-guard/src/lib.rs b/crates/tw-guard/src/lib.rs index fbce7e5d..57a661fb 100644 --- a/crates/tw-guard/src/lib.rs +++ b/crates/tw-guard/src/lib.rs @@ -1,10 +1,10 @@ //! 防护:出站脱敏、对上游返回的工具调用的审查、藏在文本里的不可见字符、按关键词 //! 过滤请求,和回答的长度上限。 //! -//! **引擎在这里,规则集和配置各带各的。**桌面版脱的是开发者自己的 API key, -//! 企业版脱的是客户的身份证号和手机号;桌面版的规则写在 `config.yaml`,企业版 -//! 的在系统设置里。两边共用的是「怎么找、怎么换、怎么在流里换回来、怎么审查 -//! 一个工具调用」—— 这些和规则是什么、从哪来无关。 +//! **引擎在这里,规则集和配置各带各的。**桌面版脱的是开发者自己的 API key +//! (外加身份证号和银行卡号),企业版脱的是客户的身份证号和手机号;桌面版的 +//! 规则写在 `config.yaml`,企业版的在系统设置里。两边共用的是「怎么找、怎么换、 +//! 怎么在流里换回来、怎么审查一个工具调用」—— 这些和规则是什么、从哪来无关。 pub mod content; pub mod hidden; diff --git a/crates/tw-guard/src/redact/rules.rs b/crates/tw-guard/src/redact/rules.rs index 11bf40f8..58214270 100644 --- a/crates/tw-guard/src/redact/rules.rs +++ b/crates/tw-guard/src/redact/rules.rs @@ -1,9 +1,16 @@ -//! 认得出哪些东西是凭据。 +//! 认得出哪些东西是凭据,外加两种个人号码。 //! //! **桌面场景要脱的东西和企业完全不同。**企业关心合规 —— 客户的身份证 //! 号、手机号不能流到第三方模型。个人开发者关心的是:**我的 API key、 //! 私钥、内网地址,会不会被中转站顺走。**所以这套规则是凭据导向的, -//! 一条 PII 规则都没有。 +//! 手机号、邮箱、姓名这类个人信息一条都不收:它们没有能核对的结构,只能 +//! 按「长得像」去猜。 +//! +//! **身份证号和银行卡号是两个例外**,是产品上点名要的:一旦漏出去就收不 +//! 回来,而且都能在结构上核对 —— 身份证号有省级地区码、真实的出生日期和 +//! MOD 11-2 校验码,卡号有卡组织的号段、位数和 Luhn 校验 —— 达得到和凭据 +//! 规则同一道门槛。它们自成一类([`Kind::Personal`]),占位符写明是哪一种, +//! 报出去只留最后四位。 //! //! 贯穿全文件的一条:**宁可漏,不可吵。**一个天天误报的安全功能,用户 //! 第二天就关了 ——而关掉之后,它连该抓的那次也抓不到了。所以 @@ -37,6 +44,9 @@ pub enum Kind { Jwt, /// `postgres://user:pass@` 这类带口令的 URI。**只换口令那一段** ConnStrings, + /// 身份证号、银行卡号:个人信息,不是凭据。占位符写明是哪一种,报出去 + /// 只留最后四位 + Personal, /// RFC1918 地址、`.local` / `.internal` 域名 Internal, /// 用户自己写的规则 @@ -50,6 +60,7 @@ impl Kind { Kind::PrivateKeys => "private-keys", Kind::Jwt => "jwt", Kind::ConnStrings => "conn-strings", + Kind::Personal => "personal", Kind::Internal => "internal", Kind::Custom => "custom", } @@ -77,6 +88,24 @@ pub enum Matcher { PrivateIp, /// 以这几个后缀结尾的域名 DomainSuffix { suffixes: &'static [&'static str] }, + /// 18 位的中华人民共和国居民身份证号码:头两位是省级行政区划代码,第 7–14 位 + /// 是 `born_since` 年 1 月 1 日到今天之间的真实日期,末位是对得上的 + /// ISO 7064 MOD 11-2 校验码(`0`–`9` 或 `X`)。15 位的老号码不认 + CnResidentId { born_since: u16 }, + /// 卡号:开头和位数属于其中一家卡组织,并且通过 Luhn 校验。连着写的,或者 + /// 四位一组、用一个空格或一个连字符隔开的(最后一组可以不足四位;American + /// Express 另有 4-6-5、Diners Club 另有 4-6-4)。公开的测试卡号不算 + BankCard { networks: &'static [CardNetwork] }, +} + +/// 一家卡组织认哪些卡号。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CardNetwork { + pub name: &'static str, + /// 以哪几段开头,含两头、两头位数相同:`(51, 55)` 是 51 到 55,`(4, 4)` 就是 4 + pub prefixes: &'static [(u32, u32)], + /// 一共几位 + pub lengths: &'static [u8], } /// 一条内置规则。 @@ -91,6 +120,11 @@ pub struct Builtin { /// 文档里到处都是,而它的危害远小于一把 key,想脱的人自己开 pub on_by_default: bool, pub matcher: Matcher, + /// 占位符里的标签。`None` 用账本的默认标签(桌面版是 `TW_SECRET`)。 + /// + /// 个人号码写明是哪一种:模型看到 `<>` 才知道那里原来是个 + /// 身份证号,答得像样 + pub label: Option<&'static str>, } const fn prefix( @@ -105,6 +139,7 @@ const fn prefix( name, on_by_default: true, matcher: Matcher::Prefix { prefix, min_tail }, + label: None, } } @@ -115,6 +150,51 @@ const OPENAI_MIN: usize = 40; const INTERNAL_SUFFIXES: &[&str] = &[".local", ".internal", ".lan"]; +/// 18 位身份证号码的出生日期最早到哪一年。 +const BORN_SINCE: u16 = 1900; + +/// 认哪几家卡组织的卡号。**判据和界面上的说明用的是同一张表。** +/// +/// 号段只收各家公开的主号段:一串数字要同时落进号段、位数对得上、过得了 +/// Luhn,才算卡号。 +pub const CARD_NETWORKS: &[CardNetwork] = &[ + CardNetwork { + name: "UnionPay", + prefixes: &[(62, 62)], + lengths: &[16, 17, 18, 19], + }, + CardNetwork { + name: "Visa", + prefixes: &[(4, 4)], + lengths: &[16, 19], + }, + CardNetwork { + name: "Mastercard", + prefixes: &[(51, 55), (2221, 2720)], + lengths: &[16], + }, + CardNetwork { + name: "American Express", + prefixes: &[(34, 34), (37, 37)], + lengths: &[15], + }, + CardNetwork { + name: "JCB", + prefixes: &[(3528, 3589)], + lengths: &[16], + }, + CardNetwork { + name: "Discover", + prefixes: &[(6011, 6011), (644, 649), (65, 65)], + lengths: &[16], + }, + CardNetwork { + name: "Diners Club", + prefixes: &[(300, 305), (36, 36), (38, 38)], + lengths: &[14], + }, +]; + /// 全部内置规则,**按界面上的顺序**。 /// /// API 密钥那一段**只收前缀明确、长度有下限的**。代码里的 hash、base64 的 @@ -130,6 +210,7 @@ pub const BUILTINS: &[Builtin] = &[ matcher: Matcher::OpenaiLegacy { min_len: OPENAI_MIN, }, + label: None, }, prefix( "github-personal-token", @@ -175,6 +256,7 @@ pub const BUILTINS: &[Builtin] = &[ name: "Private key", on_by_default: true, matcher: Matcher::Pem, + label: None, }, Builtin { id: "jwt", @@ -182,6 +264,7 @@ pub const BUILTINS: &[Builtin] = &[ name: "JWT", on_by_default: true, matcher: Matcher::Jwt, + label: None, }, Builtin { id: "conn-string-password", @@ -189,6 +272,27 @@ pub const BUILTINS: &[Builtin] = &[ name: "Connection string password", on_by_default: true, matcher: Matcher::ConnString, + label: None, + }, + Builtin { + id: "cn-resident-id", + kind: Kind::Personal, + name: "Chinese resident ID number", + on_by_default: true, + matcher: Matcher::CnResidentId { + born_since: BORN_SINCE, + }, + label: Some("ID_NUMBER"), + }, + Builtin { + id: "bank-card", + kind: Kind::Personal, + name: "Bank card number", + on_by_default: true, + matcher: Matcher::BankCard { + networks: CARD_NETWORKS, + }, + label: Some("CARD_NUMBER"), }, Builtin { id: "internal-ip", @@ -196,6 +300,7 @@ pub const BUILTINS: &[Builtin] = &[ name: "Internal IP address", on_by_default: false, matcher: Matcher::PrivateIp, + label: None, }, Builtin { id: "internal-domain", @@ -205,6 +310,7 @@ pub const BUILTINS: &[Builtin] = &[ matcher: Matcher::DomainSuffix { suffixes: INTERNAL_SUFFIXES, }, + label: None, }, ]; @@ -212,6 +318,15 @@ pub fn builtin(id: &str) -> Option<&'static Builtin> { BUILTINS.iter().find(|b| b.id == id) } +/// 内置规则的一处命中。**标签照规则表上写的**,不在各个找的地方各写一遍。 +fn builtin_hit(id: &'static str, bytes: Range) -> Hit { + Hit { + bytes, + rule: Rule::Builtin(id), + label: builtin(id).and_then(|b| b.label).map(Arc::from), + } +} + /// 命中的是哪一条规则。 #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum Rule { @@ -498,11 +613,7 @@ fn private_keys(text: &str, out: &mut Vec) { continue; } }; - out.push(Hit { - bytes: begin..end, - rule: Rule::Builtin("private-key"), - label: None, - }); + out.push(builtin_hit("private-key", begin..end)); from = end; } } @@ -569,11 +680,7 @@ fn conn_strings(text: &str, out: &mut Vec) { && let Some(c) = colon && j > c + 1 { - out.push(Hit { - bytes: c + 1..j, - rule: Rule::Builtin("conn-string-password"), - label: None, - }); + out.push(builtin_hit("conn-string-password", c + 1..j)); } from = after; } @@ -621,6 +728,345 @@ fn internal_token(tok: &str, set: &RuleSet) -> Option<&'static str> { None } +// ---------------------------------------------------------------- 个人号码 + +/// 省级行政区划代码(GB/T 2260),身份证号码的头两位。 +const PROVINCES: [u8; 34] = [ + 11, 12, 13, 14, 15, // 华北 + 21, 22, 23, // 东北 + 31, 32, 33, 34, 35, 36, 37, // 华东 + 41, 42, 43, 44, 45, 46, // 中南 + 50, 51, 52, 53, 54, // 西南 + 61, 62, 63, 64, 65, // 西北 + 71, 81, 82, // 台湾、香港、澳门 +]; + +/// ISO 7064 MOD 11-2:前 17 位各乘对应的权重,加起来除以 11 的余数在 +/// [`ID_CHECK`] 里查出校验码。 +const ID_WEIGHTS: [u32; 17] = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]; +const ID_CHECK: &[u8; 11] = b"10X98765432"; + +/// 18 位居民身份证号码。`today` 写成 `YYYYMMDD`。 +/// +/// **地区码、日期、校验码缺一不可。**光看「18 位数字」的话,雪花 ID、订单号、 +/// 纳秒时间戳全是;地区码挡掉一部分,真实的日期再挡掉一大半,校验码最后只放过 +/// 十一分之一。 +fn resident_id(s: &[u8], today: u32) -> bool { + if s.len() != 18 || !s[..17].iter().all(u8::is_ascii_digit) { + return false; + } + let d = |i: usize| u32::from(s[i] - b'0'); + let num = |r: Range| r.fold(0, |v, i| v * 10 + d(i)); + if !PROVINCES.contains(&(num(0..2) as u8)) { + return false; + } + let (year, month, day) = (num(6..10), num(10..12), num(12..14)); + if year < u32::from(BORN_SINCE) + || !(1..=12).contains(&month) + || day == 0 + || day > days_in(year, month) + { + return false; + } + let sum: u32 = (0..17).map(|i| d(i) * ID_WEIGHTS[i]).sum(); + s[17].to_ascii_uppercase() == ID_CHECK[(sum % 11) as usize] + // 出生在今天以后的人还没有身份证号 + && year * 10_000 + month * 100 + day <= today +} + +/// 某年某月有几天。闰年是能被 4 整除而不能被 100 整除的,或者能被 400 整除的 +/// —— 1900 年没有 2 月 29 日,2000 年有。 +fn days_in(year: u32, month: u32) -> u32 { + match month { + 2 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 => 29, + 2 => 28, + 4 | 6 | 9 | 11 => 30, + _ => 31, + } +} + +/// 今天,写成 `YYYYMMDD`。**按北京时间**:身份证上的出生日期是按它记的。 +fn today_ymd() -> u32 { + let secs = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let (y, m, d) = civil((secs + 8 * 3600) / 86_400); + y * 10_000 + m * 100 + d +} + +/// 1970-01-01 之后的第 `days` 天是哪年哪月哪日(Howard Hinnant 的 +/// `civil_from_days`)。为了一个日期不值得引一个时间库。 +fn civil(days: u64) -> (u32, u32, u32) { + let z = days + 719_468; + let era = z / 146_097; + let doe = z % 146_097; + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = era * 400 + yoe + u64::from(m <= 2); + (y as u32, m as u32, d as u32) +} + +/// 卡号最多几位。 +const CARD_MAX: usize = 19; + +/// 公开的测试卡号。**开发者天天往代码、文档里贴它们**,换成占位符纯属打扰。 +/// +/// 不求全,只收最常被贴的那几张表,2026-10 对着各家的页面核对过: +/// +/// - Stripe(docs.stripe.com/testing):按卡组织、联名卡、拒付三张表,和最常用的 +/// 三张 3DS 卡; +/// - Braintree(developer.paypal.com/braintree/docs/guides/credit-cards/testing-go-live): +/// Valid card numbers 和 unsuccessful verification 两张表; +/// - Adyen(docs.adyen.com/development-resources/test-cards-and-credentials/test-card-numbers): +/// 3D Secure 2 那张表,一家卡组织一两张。 +/// +/// 按国家、风控、争议细分的几百张不收。**每一张都得是这条规则本来会认的** +/// (测试里钉着):认不出的用不着排除,列着只会让人以为它有用 —— Stripe 那张 +/// 16 位的 Diners Club(3056 9300 0902 0004)就是这样,这里的 Diners Club 只认 14 位。 +const TEST_CARDS: &[&str] = &[ + // Stripe:按卡组织 + "4242424242424242", + "4000056655665556", + "5555555555554444", + "2223003122003222", + "5200828282828210", + "5105105105105100", + "378282246310005", + "371449635398431", + "6011111111111117", + "6011000990139424", + "6011981111111113", + "36227206271667", + "6555900000604105", + "3566002020360505", + "6200000000000005", + "6200000000000047", + "6205500000000000004", + // Stripe:联名卡(Cartes Bancaires、eftpos) + "4000002500001001", + "5555552500001001", + "4000050360000001", + "5555050360000080", + // Stripe:拒付 + "4000000000000002", + "4000000000009995", + "4000000000009987", + "4000000000009979", + "4000000000000069", + "4000000000000127", + "4000000000000119", + "4000000000006975", + "4000000000000341", + // Stripe:3DS + "4000002500003155", + "4000002760003184", + "4000000000003220", + // Braintree:Valid card numbers(和上面重复的不再列) + "36259600000004", + "6011000991300009", + "3530111333300000", + "2223000048400011", + "4111111111111111", + "4005519200000004", + "4009348888881881", + "4012000033330026", + "4012000077777777", + "4012888888881881", + "4217651111111119", + "4500600000000061", + "6243030000000001", + "6221261111117766", + "6223164991230014", + // Braintree:unsuccessful verification + "4000111111111115", + "378734493671000", + "38520000009814", + // Adyen:3D Secure 2 + "4871049999999910", + "4035501428146300", + "4360000001000005", + "6250947000000014", + "6250946000000016", + "30569309025904", + "3566111111111113", + "5454545454545454", + "2222400010000008", + "4917610000000000", + "4166676667666746", +]; + +/// 一串数字属于哪家卡组织:位数对得上,开头落在它的号段里。 +fn card_network(d: &[u8]) -> Option<&'static CardNetwork> { + CARD_NETWORKS.iter().find(|n| { + // 先比位数:位数都对不上的话,开头那几位可能还没有这么长 + n.lengths.contains(&(d.len() as u8)) + && n.prefixes.iter().any(|&(from, to)| { + let k = from.checked_ilog10().map_or(1, |l| l as usize + 1); + let head = d[..k].iter().fold(0, |v, c| v * 10 + u32::from(c - b'0')); + (from..=to).contains(&head) + }) + }) +} + +/// Luhn 校验:从右数第二位起每隔一位乘 2(超过 9 的减 9),总和是 10 的倍数。 +fn luhn(d: &[u8]) -> bool { + let sum: u32 = d + .iter() + .rev() + .enumerate() + .map(|(i, c)| { + let x = u32::from(c - b'0'); + match (i % 2, x * 2) { + (0, _) => x, + (_, y) if y > 9 => y - 9, + (_, y) => y, + } + }) + .sum(); + sum % 10 == 0 +} + +/// 一段文本是不是一个卡号。`sep` 是分组用的那一种分隔符,`None` 是连着写的。 +/// +/// 分组只认两种写法:四位一组、最后一组可以不足四位(`6222 0212 3456 7894 123`), +/// 和 American Express、Diners Club 卡面上印的 4-6-5、4-6-4。**一个号码里只用一种 +/// 分隔符**:`6222-0212 3456-7894` 不算。 +/// +/// 数字抄在栈上的一个定长数组里,不分配 —— 每个请求体里每个像样的数字串都要过一遍。 +fn card_number(s: &str, sep: Option) -> bool { + let mut digits = [0u8; CARD_MAX]; + let mut n = 0; + let mut lens = [0usize; 5]; + let mut groups = 0; + for g in s.as_bytes().split(|&b| Some(b) == sep) { + if g.is_empty() + || groups == lens.len() + || n + g.len() > CARD_MAX + || !g.iter().all(u8::is_ascii_digit) + { + return false; + } + digits[n..n + g.len()].copy_from_slice(g); + n += g.len(); + lens[groups] = g.len(); + groups += 1; + } + let shape = &lens[..groups]; + let written = match shape { + [] => false, + [_] => sep.is_none(), + [head @ .., last] => { + sep.is_some() + && ((head.iter().all(|&l| l == 4) && (1..=4).contains(last)) + || shape == [4, 6, 5] + || shape == [4, 6, 4]) + } + }; + let d = &digits[..n]; + written && card_network(d).is_some() && luhn(d) && !TEST_CARDS.iter().any(|t| t.as_bytes() == d) +} + +/// 用一个空格隔开的几组数字:`6222 0212 3456 7894`。 +/// +/// 分词在空格处切开,这样的卡号到这里是一串 token,要接起来看。**只接隔着 +/// 正好一个空格的**:两个空格、换行、制表符隔开的是几个数,不是一个分组写的 +/// 号码。看的是接起来最长的那一整串 —— 从里面截一段去对的话,一张四位数的 +/// 表里每隔几行就「有」一张卡。 +#[derive(Default)] +struct Spaced { + /// 第一组的起点。`None`:眼下没有在接的 + start: Option, + /// 最后一组的起点 + last: usize, + /// 最后一组的终点 + end: usize, + groups: usize, + /// 最后一组后面跟着句号:这句话说完了,后面的数字不再接上来 + closed: bool, +} + +impl Spaced { + /// 下一个 token。`body` 是它去掉句末句号的那一段,从 `at` 开始。 + fn feed(&mut self, text: &str, at: usize, body: &str, dotted: bool, out: &mut Vec) { + // 一组最多六位:4-6-5 中间那组 + let group = (1..=6).contains(&body.len()) && body.bytes().all(|b| b.is_ascii_digit()); + if group + && !self.closed + && self.start.is_some() + && at == self.end + 1 + && text.as_bytes()[self.end] == b' ' + { + self.last = at; + self.end = at + body.len(); + self.groups += 1; + self.closed = dotted; + return; + } + self.finish(text, out); + if group { + *self = Spaced { + start: Some(at), + last: at, + end: at + body.len(), + groups: 1, + closed: dotted, + }; + } + } + + /// 这一串接完了:整串是一个卡号就记下来。 + /// + /// 不是的话,末尾那组不足四位时去掉它再看一次:卡号后面紧跟着的月份、安全码 + /// (`6222 0212 3456 7894 12/28`)不是号码的一部分。整串先看 —— 19 位的卡号 + /// 最后一组本来就只有三位。 + fn finish(&mut self, text: &str, out: &mut Vec) { + let Some(start) = self.start.take() else { + return; + }; + if self.groups < 2 { + return; + } + if card_number(&text[start..self.end], Some(b' ')) { + out.push(builtin_hit("bank-card", start..self.end)); + } else if self.groups > 2 + && self.end - self.last < 4 + && card_number(&text[start..self.last - 1], Some(b' ')) + { + out.push(builtin_hit("bank-card", start..self.last - 1)); + } + } +} + +/// 一个 token 是不是身份证号,或者连着写、用连字符分组写的卡号。`body` 是 +/// 去掉了句末句号的那一段,从 `at` 开始。 +fn personal_token( + body: &str, + at: usize, + want_id: bool, + want_card: bool, + today: u32, + out: &mut Vec, +) { + let b = body.as_bytes(); + // 最短的卡号也有 14 位。开头不是数字的(`-6222…`、`x6222…`)不是一个号码 + if b.len() < 14 || !b[0].is_ascii_digit() { + return; + } + let span = at..at + b.len(); + // 身份证号先认,认出来了就**不再往下猜**:甘肃的号码以 62 开头,有的碰巧也 + // 过得了 Luhn。关掉身份证号那条,是不要换身份证号,不是让它当成卡号换掉 + if resident_id(b, today) { + if want_id { + out.push(builtin_hit("cn-resident-id", span)); + } + } else if want_card && card_number(body, body.contains('-').then_some(b'-')) { + out.push(builtin_hit("bank-card", span)); + } +} + // ---------------------------------------------------------------- 自定义 /// 自定义规则的一处匹配,收成**在 JSON 字符串里换得安全**的一段。 @@ -679,31 +1125,33 @@ pub fn scan(text: &str, set: &RuleSet) -> Vec { conn_strings(text, &mut out); } let want_jwt = set.is_on("jwt"); + let want_id = set.is_on("cn-resident-id"); + let want_card = set.is_on("bank-card"); + // 一次扫描问一次时钟。只开卡号那条时也要问:认出是身份证号的不当卡号换 + let today = if want_id || want_card { today_ymd() } else { 0 }; + let mut spaced = Spaced::default(); for_each_token(text, |tok, span| { + if want_id || want_card { + // 句末的句号不是号码的一部分:`…卡号是 6222 0212 3456 7894.` + let body = tok.trim_end_matches('.'); + if want_card { + spaced.feed(text, span.start, body, body.len() < tok.len(), &mut out); + } + personal_token(body, span.start, want_id, want_card, today, &mut out); + } if let Some(id) = classify_token(tok, set) { - out.push(Hit { - bytes: span, - rule: Rule::Builtin(id), - label: None, - }); + out.push(builtin_hit(id, span)); return; } if want_jwt && looks_like_jwt(tok) { - out.push(Hit { - bytes: span, - rule: Rule::Builtin("jwt"), - label: None, - }); + out.push(builtin_hit("jwt", span)); return; } if let Some(id) = internal_token(tok, set) { - out.push(Hit { - bytes: span, - rule: Rule::Builtin(id), - label: None, - }); + out.push(builtin_hit(id, span)); } }); + spaced.finish(text, &mut out); custom_hits(text, set, &mut out); disjoint(out) } @@ -796,11 +1244,26 @@ pub fn scan_text(text: &str, set: &RuleSet) -> Vec { /// /// 内网地址和内部域名例外:它们不是凭据,而打码之后的 `…` 让人无从判断 /// 那条记录说的是哪台机器。 +/// +/// 身份证号和卡号只留最后四位:「留头 5」留下的正好是身份证号的地区码、卡号的 +/// 发卡行,而认出是哪一个号码,看最后四位就够了。 pub fn masked(rule: &Rule, value: &str) -> String { - if rule.kind() == Kind::Internal { - return value.to_string(); + match rule.kind() { + Kind::Internal => value.to_string(), + Kind::Personal => last_four(value), + _ => mask(value), } - mask(value) +} + +/// 只留最后四位:`…1234`。分组写的卡号跳过分隔符数,`… 7894 123` 留 `4123`。 +fn last_four(s: &str) -> String { + let n = s.bytes().filter(u8::is_ascii_alphanumeric).count(); + let tail: String = s + .chars() + .filter(char::is_ascii_alphanumeric) + .skip(n.saturating_sub(4)) + .collect(); + format!("…{tail}") } /// 留头 5 尾 4,中间省略:`sk-a…7f9c`。 @@ -1166,19 +1629,620 @@ mod tests { fn every_builtin_rule_describes_what_it_matches() { // 界面上的「匹配」一栏来自 `matcher`;它说的必须就是扫描用的判据。 for b in BUILTINS { - if let Matcher::Prefix { prefix, min_tail } = b.matcher { - let key = format!("{prefix}{}", "a1".repeat(min_tail)); - let hits = scan(&key, &RuleSet::only(&[b.id])); - assert_eq!(hits.len(), 1, "{} 认不出它自己说的形状:{key}", b.id); - let short = format!("{prefix}{}", "a".repeat(min_tail - 1)); - assert!( - scan(&short, &RuleSet::only(&[b.id])).is_empty(), - "{} 比它说的长度下限更短的也认了", - b.id - ); + let only = RuleSet::only(&[b.id]); + match b.matcher { + Matcher::Prefix { prefix, min_tail } => { + let key = format!("{prefix}{}", "a1".repeat(min_tail)); + let hits = scan(&key, &only); + assert_eq!(hits.len(), 1, "{} 认不出它自己说的形状:{key}", b.id); + let short = format!("{prefix}{}", "a".repeat(min_tail - 1)); + assert!( + scan(&short, &only).is_empty(), + "{} 比它说的长度下限更短的也认了", + b.id + ); + } + Matcher::CnResidentId { born_since } => { + let first = id_done(&format!("110105{born_since}0101001")); + assert_eq!(scan(&first, &only).len(), 1, "{first}"); + let earlier = id_done(&format!("110105{}1231001", born_since - 1)); + assert!(scan(&earlier, &only).is_empty(), "{earlier}"); + } + Matcher::BankCard { networks } => { + // 每一家的每一段号段的两头、每一种位数都认;位数短一位、长一位的不认 + for n in networks { + let (min, max) = (n.lengths[0], n.lengths[n.lengths.len() - 1]); + for &(from, to) in n.prefixes { + for p in [from, to] { + for &len in n.lengths { + let card = card_of(p, len); + assert_eq!( + scan(&card, &only).len(), + 1, + "{} 不认 {card}", + n.name + ); + } + for len in [min - 1, max + 1] { + let card = card_of(p, len); + assert!( + scan(&card, &only).is_empty(), + "{} 认了 {card}", + n.name + ); + } + } + } + } + } + _ => {} } } let ids: HashSet<&str> = BUILTINS.iter().map(|b| b.id).collect(); assert_eq!(ids.len(), BUILTINS.len(), "内置规则的 id 重复了"); } + + // ------------------------------------------------------------ 个人号码 + + /// 补上 ISO 7064 MOD 11-2 校验码。**照标准另写一遍**(权重是 2^(17-i) mod 11), + /// 不借被测的那张权重表 —— 借了的话,表抄错了这里也跟着错。 + fn id_done(first17: &str) -> String { + let sum: u32 = first17 + .bytes() + .enumerate() + .map(|(i, c)| u32::from(c - b'0') * (2u32.pow(17 - i as u32) % 11)) + .sum(); + let c = (12 - sum % 11) % 11; + let check = if c == 10 { + 'X' + } else { + char::from(b'0' + c as u8) + }; + format!("{first17}{check}") + } + + /// 补上 Luhn 校验位,同样另写一遍。 + fn luhn_done(body: &str) -> String { + let sum: u32 = body + .bytes() + .rev() + .enumerate() + .map(|(i, c)| { + let x = u32::from(c - b'0'); + if i % 2 == 0 { + (x * 2) / 10 + (x * 2) % 10 + } else { + x + } + }) + .sum(); + format!("{body}{}", (10 - sum % 10) % 10) + } + + /// 以 `prefix` 开头、一共 `len` 位、过得了 Luhn 的一个号码。中间填的不是 0: + /// `4` 后面一串 0 正好是 Stripe 的一张测试卡。 + fn card_of(prefix: u32, len: u8) -> String { + let mut body = prefix.to_string(); + let fill = b"8642097531"; + while body.len() < usize::from(len) - 1 { + body.push(char::from(fill[body.len() % fill.len()])); + } + luhn_done(&body) + } + + fn personal() -> RuleSet { + RuleSet::only(&["cn-resident-id", "bank-card"]) + } + + fn personal_found(text: &str) -> Vec<(String, String)> { + scan(text, &personal()) + .into_iter() + .map(|h| (h.rule.id().to_string(), text[h.bytes].to_string())) + .collect() + } + + #[test] + fn the_test_helpers_agree_with_published_numbers() { + // 两个补校验位的函数先对上公开的号码,后面的测试才站得住:GB 11643 里的 + // 示例号码,和 Stripe 的一张测试卡 + assert_eq!(id_done("11010519491231002"), "11010519491231002X"); + assert_eq!(id_done("44052418800101001"), "440524188001010014"); + assert_eq!(luhn_done("424242424242424"), "4242424242424242"); + assert_eq!(luhn_done("37828224631000"), "378282246310005"); + } + + #[test] + fn a_resident_id_number_is_replaced_and_comes_back() { + for id in [ + "11010519491231002X", + "11010519491231002x", + "110105199003071239", + // 2000 年有 2 月 29 日 + "310104200002294568", + "440306198510157896", + "650102190001010016", + // 台湾、香港、澳门 + "71000019991231444X", + "810000197001015558", + "820000201008083335", + ] { + let t = format!("身份证号:{id},请核对"); + assert_eq!( + personal_found(&t), + vec![("cn-resident-id".to_string(), id.to_string())], + "{t}" + ); + let r = crate::redact::replace::redact( + &t, + &RuleSet::defaults(), + crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), + ); + assert_eq!(r.text, "身份证号:<>,请核对", "{id}"); + assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), t); + } + } + + #[test] + fn an_id_number_that_does_not_check_out_is_left_alone() { + let today = today_ymd(); + let next_year = today / 10_000 + 1; + for (why, id) in [ + ("校验码不对", "110105199003071238".to_string()), + ("校验码不对", "11010519491231002Y".to_string()), + ("1900 年不是闰年", id_done("11010519000229001")), + ("2 月没有 30 日", id_done("11010519900230001")), + ("没有 13 月", id_done("11010519901301001")), + ("没有 0 日", id_done("11010519900100001")), + ("4 月没有 31 日", id_done("11010519900431001")), + ("1900 年以前", id_done("11010518991231001")), + ("还没出生", id_done(&format!("110105{next_year}0101001"))), + ("15 位的老号码", "110105491231002".to_string()), + ("17 位", "11010519491231002".to_string()), + ] { + assert!( + personal_found(&id).is_empty(), + "{why}:{id} → {:?}", + personal_found(&id) + ); + } + // 地区码不在 GB/T 2260 的省级名单里 —— 其余几样都对 + for code in [ + 10, 16, 20, 30, 38, 40, 47, 55, 60, 66, 70, 72, 80, 83, 90, 91, 99, + ] { + let id = id_done(&format!("{code}010519900307123")); + assert!(personal_found(&id).is_empty(), "地区码 {code}:{id}"); + } + } + + #[test] + fn the_birth_date_is_checked_against_today() { + // 今天出生的算,明天的不算 + let today = today_ymd(); + assert!(resident_id( + id_done(&format!("110105{today}001")).as_bytes(), + today + )); + assert!(!resident_id( + id_done(&format!("110105{today}001")).as_bytes(), + today - 1 + )); + } + + #[test] + fn day_counting_lands_on_real_dates() { + assert_eq!(civil(0), (1970, 1, 1)); + assert_eq!(civil(11_016), (2000, 2, 29)); + assert_eq!(civil(20_727), (2026, 10, 1)); + assert_eq!(days_in(1900, 2), 28); + assert_eq!(days_in(2000, 2), 29); + assert_eq!(days_in(2024, 2), 29); + assert_eq!(days_in(2026, 2), 28); + } + + #[test] + fn a_card_number_is_replaced_and_comes_back() { + for card in [ + "6222021234567894", + "62220212345678903", + "622202123456789012", + "6222021234567890128", + "4532015112830366", + "4532015112830360008", + "5500000000000004", + "2221000000000017", + "2720999999999996", + "340000000000009", + "3528000000000007", + "6011000000000004", + "6500000000000002", + "30000000000004", + "36000000000008", + ] { + let t = format!("卡号 {card} 尾号对一下"); + assert_eq!( + personal_found(&t), + vec![("bank-card".to_string(), card.to_string())], + "{t}" + ); + let r = crate::redact::replace::redact( + &t, + &RuleSet::defaults(), + crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), + ); + assert_eq!(r.text, "卡号 <> 尾号对一下", "{card}"); + assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), t); + } + } + + #[test] + fn a_card_number_that_does_not_check_out_is_left_alone() { + // 除了头两个,都是过得了 Luhn 的:挡住它们的是号段和位数 + for (why, card) in [ + ("Luhn 不对", "6222021234567895"), + ("Luhn 不对", "4532015112830367"), + ("Visa 没有 17 位的", "45320151128303665"), + ("Visa 没有 15 位的", "453201511283034"), + ("American Express 只有 15 位", "3400000000000000"), + ("Mastercard 只有 16 位", "550000000000004"), + ("Diners Club 只有 14 位", "3000000000000004"), + ("银联最短 16 位", "622202123456782"), + ("2220 不在 Mastercard 的号段里", "2220000000000018"), + ("2721 也不在", "2721000000000012"), + ("3527 不是 JCB", "3527000000000008"), + ("643 不是 Discover", "6430000000000007"), + ("306 不是 Diners Club", "30600000000001"), + ("没有哪家以 1 开头", "1000000000000008"), + ("位数超过 19", "62220212345678901234"), + ] { + assert!( + personal_found(card).is_empty(), + "{why}:{card} → {:?}", + personal_found(card) + ); + } + } + + #[test] + fn a_number_inside_a_longer_run_or_an_encoded_string_is_not_a_number() { + // 在 token 边界上认:更长的数字串、十六进制、base64 里的那一段不是一个号码 + let card = "6222021234567894"; + let id = "11010519491231002X"; + for t in [ + format!("9{card}"), + format!("{card}0"), + format!("1{id}"), + format!("{id}1"), + format!("0x{card}"), + format!("deadbeef{card}cafe"), + format!("sha256:9f86d081{id}884c7d659a2f"), + format!("data:image/png;base64,iVBORw0KGgo{card}AAAANSUhEUg=="), + format!("QUJD{id}RUZH"), + format!("v{card}"), + format!("{card}_backup"), + format!("-{card}"), + format!("{card}.5"), + ] { + assert!( + personal_found(&t).is_empty(), + "{t} → {:?}", + personal_found(&t) + ); + } + } + + #[test] + fn a_number_right_after_a_json_escape_or_a_chinese_colon_is_found() { + // 扫的是请求体:换行是 `\n`,Python 写的客户端把中文冒号写成 `:` + let card = "6222021234567894"; + let id = "11010519491231002X"; + for (t, rule, value) in [ + (format!(r"卡号:\n{card}\n谢谢"), "bank-card", card), + (format!(r"\t{card}"), "bank-card", card), + (format!("身份证号:{id}"), "cn-resident-id", id), + (format!(r"身份证号:{id}"), "cn-resident-id", id), + ( + format!("持卡人张三,卡号:{card},有效期至 2028 年"), + "bank-card", + card, + ), + (format!(r#"{{"card":"{card}","id":"{id}"}}"#), "", ""), + ] { + let got = personal_found(&t); + if rule.is_empty() { + // 两个都在 + assert_eq!(got.len(), 2, "{t} → {got:?}"); + continue; + } + assert_eq!(got, vec![(rule.to_string(), value.to_string())], "{t}"); + } + } + + #[test] + fn a_full_stop_after_a_number_does_not_hide_it() { + let card = "6222021234567894"; + let id = "11010519491231002X"; + assert_eq!( + personal_found(&format!("My card is {card}.")), + vec![("bank-card".to_string(), card.to_string())] + ); + assert_eq!( + personal_found(&format!("ID: {id}. Next")), + vec![("cn-resident-id".to_string(), id.to_string())] + ); + assert_eq!( + personal_found("Card 6222 0212 3456 7894..."), + vec![("bank-card".to_string(), "6222 0212 3456 7894".to_string())] + ); + } + + #[test] + fn a_card_written_in_groups_is_one_value() { + for card in [ + "6222 0212 3456 7894", + "6222-0212-3456-7894", + "6222 0212 3456 7890 128", + "6222-0212-3456-7890-128", + "6222 0212 3456 7890 3", + // American Express 4-6-5、Diners Club 4-6-4,和四位一组的写法 + "3400 000000 00009", + "3400 0000 0000 009", + "3000 000000 0004", + "3000-0000-0000-04", + ] { + let t = format!("卡号 {card},到期 12/28"); + assert_eq!( + personal_found(&t), + vec![("bank-card".to_string(), card.to_string())], + "{t}" + ); + let r = crate::redact::replace::redact( + &t, + &RuleSet::defaults(), + crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), + ); + assert_eq!(r.ledger.len(), 1, "{}", r.text); + assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), t); + } + } + + #[test] + fn grouping_has_to_be_regular_and_consistent() { + for t in [ + // 两种分隔符混着用 + "6222-0212 3456-7894", + "6222 0212-3456-7894", + // 两个空格、换行、制表符隔开的是几个数 + "6222 0212 3456 7894", + r"6222\n0212\n3456\n7894", + r"6222\t0212\t3456\t7894", + "6222--0212--3456--7894", + // 组不是四位一组 + "622 2021 2345 6789 4", + "62220 2123 4567 894", + "622202 1234567894", + "62220212 34567894", + "6222-021234567894", + // 一张四位数的表:截一段出来正好能过的那几行也不算 + "1234 5678 6222 0212 3456 7894 0000", + ] { + assert!( + personal_found(t).is_empty(), + "{t} → {:?}", + personal_found(t) + ); + } + } + + #[test] + fn a_month_or_a_security_code_right_after_a_card_is_not_part_of_it() { + // 卡号后面紧跟着的短数字(有效期的月份、安全码)不是号码的一部分 + for t in [ + "6222 0212 3456 7894 12/28", + "6222 0212 3456 7894 123", + "4532 0151 1283 0366 12/28 123", + ] { + let got = personal_found(t); + assert_eq!(got.len(), 1, "{t} → {got:?}"); + assert!(t.starts_with(&got[0].1), "{t} → {got:?}"); + assert_eq!(got[0].1.len(), 19, "{t} → {got:?}"); + } + } + + #[test] + fn public_test_cards_are_not_replaced() { + // 开发者天天往代码里贴它们,换掉纯属打扰。题目里点名的那几张, + // 连着写、分组写都不认 + for card in [ + "4242424242424242", + "4111111111111111", + "4012888888881881", + "4000056655665556", + "5555555555554444", + "5105105105105100", + "2223003122003222", + "5200828282828210", + "378282246310005", + "371449635398431", + "6011111111111117", + "6011000990139424", + "3056930009020004", + "36227206271667", + "3566002020360505", + "6200000000000005", + "6205500000000000004", + ] { + assert!(personal_found(card).is_empty(), "{card}"); + let spaced: Vec = card + .as_bytes() + .chunks(4) + .map(|c| String::from_utf8(c.to_vec()).unwrap()) + .collect(); + for sep in [" ", "-"] { + let t = spaced.join(sep); + assert!(personal_found(&t).is_empty(), "{t}"); + } + } + } + + #[test] + fn every_listed_test_card_is_one_the_rule_would_otherwise_take() { + // 认不出的用不着排除,列着只会让人以为它有用 + let mut seen = HashSet::new(); + for t in TEST_CARDS { + assert!(seen.insert(*t), "测试卡号列了两遍:{t}"); + let d = t.as_bytes(); + assert!( + card_network(d).is_some() && luhn(d), + "{t} 本来就认不出,不用列" + ); + } + } + + #[test] + fn numbers_that_merely_look_long_are_left_alone() { + // **宁可漏,不可吵。**这些都是请求里天天出现的长数字 + for t in [ + // 毫秒、微秒、纳秒时间戳 + "\"created\": 1727712345678", + "ts=1759300000000000", + "1759300000000000000", + // 雪花 ID:开头不属于任何一家,或者开头对得上、Luhn 过不了 + "tweet 1453987635477184512", + "id: 1846987139428634624", + "4123456789012345678", + "620000000000000001", + "622848012345678901", + // 订单号 + "订单号 202310011234567890", + "订单 20231001123456789 已发货", + "3456789012345678901", + "E202310011234567", + // 电话号码 + "13800138000", + "+86 138 0013 8000", + "+86-138-0013-8000", + "021-6234-5678", + "(021) 6234 5678", + "400-820-8820", + // UUID + "550e8400-e29b-41d4-a716-446655440000", + "12345678-1234-5678-1234-567812345678", + // JavaScript 的整数上限、版本号、IP + "9007199254740991", + "1.2.3.4567890123456", + ] { + assert!( + personal_found(t).is_empty(), + "误报了:{t} → {:?}", + personal_found(t) + ); + } + } + + #[test] + fn an_id_number_that_also_passes_luhn_stays_an_id_number() { + // 甘肃的号码以 62 开头,这一个碰巧也过得了 Luhn、位数也对得上银联 + let id = "620102198811110554"; + assert_eq!( + personal_found(id), + vec![("cn-resident-id".to_string(), id.to_string())] + ); + // 关掉身份证号那条,是不要换身份证号 —— 不是让它当成卡号换掉 + let no_id = RuleSet::build(&[], &["cn-resident-id".into()], []).unwrap(); + assert!(scan(id, &no_id).is_empty(), "{:?}", scan(id, &no_id)); + } + + #[test] + fn switching_one_personal_rule_off_leaves_the_other() { + let t = "身份证 11010519491231002X,卡号 6222 0212 3456 7894"; + let both = scan(t, &RuleSet::defaults()); + assert_eq!(both.len(), 2, "{both:?}"); + let no_id = RuleSet::build(&[], &["cn-resident-id".into()], []).unwrap(); + let got = scan(t, &no_id); + assert_eq!(got.len(), 1, "{got:?}"); + assert_eq!(got[0].rule, Rule::Builtin("bank-card")); + let no_card = RuleSet::build(&[], &["bank-card".into()], []).unwrap(); + let got = scan(t, &no_card); + assert_eq!(got.len(), 1, "{got:?}"); + assert_eq!(got[0].rule, Rule::Builtin("cn-resident-id")); + let neither = + RuleSet::build(&[], &["bank-card".into(), "cn-resident-id".into()], []).unwrap(); + assert!(scan(t, &neither).is_empty()); + } + + #[test] + fn a_rule_set_built_from_nothing_finds_no_personal_numbers() { + // 企业版从 `RuleSet::none()` 加自己的正则建规则集:新加的出厂规则不能 + // 混进去,否则它脱的东西就变了 + let t = "身份证 11010519491231002X,卡号 6222021234567894"; + assert!(scan(t, &RuleSet::none()).is_empty()); + let mine = RuleSet::none() + .with_labeled("email", r"[a-z]+@[a-z]+\.com", Some("EMAIL")) + .unwrap(); + assert!(scan_text(t, &mine).is_empty()); + } + + #[test] + fn a_reported_personal_number_keeps_only_its_last_four() { + // 「留头 5」留下的是身份证号的地区码、卡号的发卡行 + let id = Rule::Builtin("cn-resident-id"); + let card = Rule::Builtin("bank-card"); + assert_eq!(masked(&id, "11010519491231002X"), "…002X"); + assert_eq!(masked(&card, "6222021234567894"), "…7894"); + assert_eq!(masked(&card, "6222 0212 3456 7894"), "…7894"); + assert_eq!(masked(&card, "6222-0212-3456-7890-128"), "…0128"); + let t = "卡号 6222 0212 3456 7894,再说一遍:6222 0212 3456 7894"; + let f = findings(t, &scan(t, &RuleSet::defaults())); + assert_eq!(f.len(), 1, "{f:?}"); + assert_eq!(f[0].masked, "…7894"); + assert_eq!(f[0].count, 2); + assert_eq!(f[0].rule.kind(), Kind::Personal); + } + + #[test] + fn personal_placeholders_say_what_they_were_and_count_per_label() { + // 模型看到 `<>` 才知道那里是个身份证号;编号按标签各数各的, + // 和凭据的 `<>` 互不相干 + let key = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA"; + let body = serde_json::json!({ + "content": format!( + "key {key}\n身份证 11010519491231002X\n卡 6222 0212 3456 7894\n另一张 4532-0151-1283-0366\n身份证 11010519491231002X" + ) + }) + .to_string(); + let r = crate::redact::replace::redact( + &body, + &RuleSet::defaults(), + crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), + ); + let v: serde_json::Value = serde_json::from_str(&r.text).expect("换完不是合法 JSON"); + assert_eq!( + v["content"], + "key <>\n身份证 <>\n卡 <>\n另一张 <>\n身份证 <>" + ); + assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), body); + // 流式还原认得带标签的占位符,切成一个字符一段也拼得回来 + let mut s = crate::redact::stream::Restorer::new(&r.ledger); + let echoed = "你的卡号 <> 和身份证 <>。"; + let mut out = String::new(); + for c in echoed.chars() { + out.push_str(&s.process(&c.to_string())); + } + out.push_str(&s.flush()); + assert_eq!( + out, + "你的卡号 6222 0212 3456 7894 和身份证 11010519491231002X。" + ); + } + + #[test] + fn the_ui_test_box_marks_a_grouped_card_where_it_was_typed() { + // 界面上的「测试」扫的是编成请求体的样子,区间要换算回用户贴的原文 + let text = "第一行\n卡号:6222 0212 3456 7894\n身份证:11010519491231002X"; + let got: Vec<&str> = scan_plain(text, &RuleSet::defaults()) + .iter() + .map(|h| &text[h.bytes.clone()]) + .collect(); + assert_eq!(got, vec!["6222 0212 3456 7894", "11010519491231002X"]); + } } diff --git a/docs/config.md b/docs/config.md index 655d04d9..b6827ca4 100644 --- a/docs/config.md +++ b/docs/config.md @@ -584,7 +584,7 @@ does differs per guard, and each says so below. | Field | Type | Default | Description | |---|---|---|---| -| `redact` | object, [`security.redact`](#cfg-security-redact) | — | Outbound redaction: credentials found in a request are replaced before it leaves. | +| `redact` | object, [`security.redact`](#cfg-security-redact) | — | Outbound redaction: credentials, Chinese resident ID numbers and bank card numbers found in a request are replaced before it leaves. | | `inspect_tools` | object, [`security.inspect_tools`](#cfg-security-inspect_tools) | — | Tool-call inspection: dangerous commands in the tool calls a model returns cut the response off. | | `hidden_text` | object, [`security.hidden_text`](#cfg-security-hidden_text) | — | Hidden characters that people cannot see and models can read refuse the request. | | `content` | object, [`security.content`](#cfg-security-content) | — | Content filter: words or patterns in what the caller sends refuse the request. | @@ -593,8 +593,9 @@ does differs per guard, and each says so below. #### `security.redact` -Before a request leaves, credentials in it are looked for. Under `enforce` -they are replaced. +Before a request leaves, credentials in it are looked for, and so are +Chinese resident ID numbers and bank card numbers. Under `enforce` they are +replaced with placeholders, and put back where the answer repeats them. @@ -646,10 +647,32 @@ Built-in rules: | `private-key` | Private key | on | | `jwt` | JWT | on | | `conn-string-password` | Connection string password | on | +| `cn-resident-id` | Chinese resident ID number | on | +| `bank-card` | Bank card number | on | | `internal-ip` | Internal IP address | off | | `internal-domain` | Internal domain | off | +`cn-resident-id` and `bank-card` look for personal numbers rather than +credentials, and match only what checks out by structure: + +- `cn-resident-id`: an 18-character resident ID number of the People's + Republic of China whose first two digits are a province-level code, whose + date of birth is a real date between 1900-01-01 and today, and whose last + character is the right check character (ISO 7064 MOD 11-2). The old + 15-digit numbers are not matched. +- `bank-card`: a card number whose prefix and length belong to UnionPay, + Visa, Mastercard, American Express, JCB, Discover or Diners Club and which + passes the Luhn check, written as one run of digits or in groups of four + separated by single spaces or single hyphens (American Express also 4-6-5, + Diners Club also 4-6-4). The test card numbers published by Stripe, + Braintree and Adyen are not matched. + +A number that is part of a longer run of letters or digits is not matched. +The placeholders of these two rules say what was there (`<>`, +`<>`), and the security log shows only the last four +characters of what they found. + #### `security.inspect_tools` Tool calls a model returns are checked against the rules. Under `enforce`, diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 38093a1e..e3664649 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -461,7 +461,7 @@ pricing: | 字段 | 类型 | 默认值 | 说明 | |---|---|---|---| -| `redact` | 对象,见 [`security.redact`](#cfg-security-redact) | — | 出站脱敏:请求发出前,把其中的凭据替换掉。 | +| `redact` | 对象,见 [`security.redact`](#cfg-security-redact) | — | 出站脱敏:请求发出前,把其中的凭据、身份证号和银行卡号替换掉。 | | `inspect_tools` | 对象,见 [`security.inspect_tools`](#cfg-security-inspect_tools) | — | 工具调用审查:模型返回的工具调用中出现危险命令时切断响应。 | | `hidden_text` | 对象,见 [`security.hidden_text`](#cfg-security-hidden_text) | — | 人看不见、模型读得到的隐藏字符,出现时拒绝请求。 | | `content` | 对象,见 [`security.content`](#cfg-security-content) | — | 内容过滤:调用方发送的内容中出现指定的词或写法时拒绝请求。 | @@ -470,7 +470,7 @@ pricing: #### `security.redact` -请求发出前查找其中的凭据。`enforce` 下将其替换。 +请求发出前查找其中的凭据,以及居民身份证号和银行卡号。`enforce` 下将其替换为占位符,回答中重复出现时再换回原值。 @@ -522,10 +522,19 @@ pricing: | `private-key` | Private key | 开 | | `jwt` | JWT | 开 | | `conn-string-password` | Connection string password | 开 | +| `cn-resident-id` | Chinese resident ID number | 开 | +| `bank-card` | Bank card number | 开 | | `internal-ip` | Internal IP address | 关 | | `internal-domain` | Internal domain | 关 | +`cn-resident-id` 和 `bank-card` 查找的是个人号码而不是凭据,只认结构上核对得上的: + +- `cn-resident-id`:18 位的中华人民共和国居民身份证号码。前两位须是省级行政区划代码,出生日期须是 1900 年 1 月 1 日至今天之间的真实日期,末位须是正确的校验码(ISO 7064 MOD 11-2)。15 位的旧号码不认。 +- `bank-card`:卡号。开头和位数须属于银联、Visa、Mastercard、American Express、JCB、Discover 或 Diners Club,并通过 Luhn 校验;连续书写,或四位一组、以单个空格或单个连字符分隔均可(American Express 另认 4-6-5,Diners Club 另认 4-6-4)。Stripe、Braintree、Adyen 公开的测试卡号不认。 + +夹在更长的一串字母或数字中间的号码不认。占位符写明原来是什么(`<>`、`<>`),安全日志中只显示最后四位。 + #### `security.inspect_tools` 按规则检查模型返回的工具调用。`enforce` 下命中处置为 `cut` 的规则时切断响应,客户端拿不到可执行的完整调用。 From 02f845e49e4030e486cf788d3c09cecaebdcccb4 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:58:42 +0800 Subject: [PATCH 2/4] perf(guard): no allocation per token in the redaction scan Every token of every request body went through `looks_like_jwt`, which collected its dot-separated parts into a Vec, and `internal_token`, which lowercased the token into a new String even with the internal-domain rule off. `is_rfc1918` collected twice more when the internal-ip rule was on. The checks now count dots, compare suffixes case-insensitively in place and read the octets into a fixed array; what they match is unchanged, and a test now pins the internal-domain rule, which had none. On a 2 MB request body (code, Chinese prose, base64, UUIDs), the scan with the default rules goes from about 10.0 to 6.1 ms per MB, and with every built-in rule on from 12.0 to 6.9 ms per MB, so the two new personal-number rules leave the default scan faster than it was before them. Co-Authored-By: Claude Opus 5.5 --- crates/tw-guard/src/redact/rules.rs | 64 ++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 15 deletions(-) diff --git a/crates/tw-guard/src/redact/rules.rs b/crates/tw-guard/src/redact/rules.rs index 58214270..1d96edfc 100644 --- a/crates/tw-guard/src/redact/rules.rs +++ b/crates/tw-guard/src/redact/rules.rs @@ -631,13 +631,19 @@ fn is_b64url(s: &str) -> bool { /// 那个解码是必需的:光看「三段用点分开的 base64」会把版本号、文件路径、 /// 甚至 `a.b.c` 这种普通标识符全算上。 fn looks_like_jwt(tok: &str) -> bool { - let parts: Vec<&str> = tok.split('.').collect(); - if parts.len() != 3 || !parts.iter().all(|p| is_b64url(p)) || parts[0].len() < 8 { + // 先数点,不把三段收集起来:每个 token 都要过这一关,绝大多数在这里就回去了 + if tok.bytes().filter(|&b| b == b'.').count() != 2 || !tok.split('.').all(is_b64url) { + return false; + } + let Some((head, _)) = tok.split_once('.') else { + return false; + }; + if head.len() < 8 { return false; } use base64::Engine as _; let Ok(head) = - base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(parts[0].trim_end_matches('=')) + base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(head.trim_end_matches('=')) else { return false; }; @@ -689,15 +695,16 @@ fn conn_strings(text: &str, out: &mut Vec) { // ---------------------------------------------------------------- 内网标识 fn is_rfc1918(tok: &str) -> bool { - let p: Vec<&str> = tok.split('.').collect(); - if p.len() != 4 { - return false; + // 四段读进一个定长数组,不收集:开着这条时每个 token 都要过一遍 + let mut nums = [0u16; 4]; + let mut parts = tok.split('.'); + for n in &mut nums { + match parts.next().map(str::parse::) { + Some(Ok(v)) if v <= 255 => *n = v, + _ => return false, + } } - let nums: Vec = match p.iter().map(|x| x.parse::()).collect::>() { - Ok(v) => v, - Err(_) => return false, - }; - if nums.iter().any(|n| *n > 255) { + if parts.next().is_some() { return false; } match (nums[0], nums[1]) { @@ -717,11 +724,15 @@ fn internal_token(tok: &str, set: &RuleSet) -> Option<&'static str> { if set.is_on("internal-ip") && is_rfc1918(tok) { return Some("internal-ip"); } - let lower = tok.to_ascii_lowercase(); + // 后缀不分大小写地比,**不先转成小写**:每个 token 都要过这一关,转一次就是 + // 一次分配 + let t = tok.as_bytes(); if set.is_on("internal-domain") - && INTERNAL_SUFFIXES.iter().any(|s| lower.ends_with(s)) - && lower.len() > 7 - && lower.contains('.') + && t.len() > 7 + && t.contains(&b'.') + && INTERNAL_SUFFIXES.iter().any(|s| { + t.len() >= s.len() && t[t.len() - s.len()..].eq_ignore_ascii_case(s.as_bytes()) + }) { return Some("internal-domain"); } @@ -1496,6 +1507,29 @@ mod tests { assert!(found("127.0.0.1 和 8.8.8.8 和 172.32.0.1").is_empty()); } + #[test] + fn internal_domains_are_found_whatever_their_case() { + let set = RuleSet::only(&["internal-domain"]); + let got: Vec = scan( + "构建机 build.corp.internal、打印机 Printer.LOCAL、路由 gw.home.lan", + &set, + ) + .into_iter() + .map(|h| h.rule.id().to_string()) + .collect(); + assert_eq!(got, vec!["internal-domain"; 3]); + // 太短的、只是后缀的、后缀不在词尾的,都不算 + for t in [ + "a.lan", + ".local", + "local", + "x.internal.example.com", + "localhost", + ] { + assert!(scan(t, &set).is_empty(), "{t}"); + } + } + #[test] fn the_internal_rules_are_off_until_someone_turns_them_on() { // RFC1918 地址在代码和文档里到处都是,而它的危害远小于一把 key。 From 4a46d03149a623145fbe164c6155e7cc5a9edda7 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:28:08 +0800 Subject: [PATCH 3/4] fix(guard): leave JSON numbers alone when looking for personal numbers The scan runs on the raw JSON body. The credential rules never matched outside a string, since nothing there contains letters, but the number rules do: a tool call's input (`"input":{"order_id":6222021234567894}`) or a `seed` that happens to be a valid card number was replaced with an unquoted placeholder, and the request body was no longer JSON. The tokenizer now tells whether a token sits inside a JSON string (by counting unescaped quotes), and when the text is a JSON document the two personal rules only look inside strings. Text that is not JSON, such as a sample scanned directly, is looked at as before. Co-Authored-By: Claude Opus 5.5 --- crates/tw-guard/src/redact/rules.rs | 66 ++++++++++++++++++++++++++--- docs/config.md | 10 +++-- docs/config.zh-CN.md | 2 +- 3 files changed, 66 insertions(+), 12 deletions(-) diff --git a/crates/tw-guard/src/redact/rules.rs b/crates/tw-guard/src/redact/rules.rs index 1d96edfc..c94bf100 100644 --- a/crates/tw-guard/src/redact/rules.rs +++ b/crates/tw-guard/src/redact/rules.rs @@ -543,13 +543,17 @@ fn classify_token(tok: &str, set: &RuleSet) -> Option<&'static str> { /// 常在行首。`\t` 同理;`\uXXXX` 也一样(Python 写的客户端默认把中文 /// 都转成这种写法,`密钥:sk-…` 里的冒号就成了 `\uff1a`)。所以转义序列 /// 整个算作分隔。 -fn for_each_token(text: &str, mut f: impl FnMut(&str, Range)) { +/// +/// 回调的第三个参数说这个 token 在不在一个 JSON 字符串里面(数没转义的引号; +/// 文本是 JSON 时才有意义)。 +fn for_each_token(text: &str, mut f: impl FnMut(&str, Range, bool)) { let mut start: Option = None; + let mut quoted = false; let mut chars = text.char_indices().peekable(); while let Some((i, c)) = chars.next() { if c == '\\' { if let Some(s) = start.take() { - f(&text[s..i], s..i); + f(&text[s..i], s..i, quoted); } // 反斜杠后面那个字符是转义的一部分;`\u` 再带四位十六进制 if let Some((_, 'u')) = chars.next() { @@ -563,12 +567,17 @@ fn for_each_token(text: &str, mut f: impl FnMut(&str, Range)) { } if is_tok(c) { start.get_or_insert(i); - } else if let Some(s) = start.take() { - f(&text[s..i], s..i); + continue; + } + if let Some(s) = start.take() { + f(&text[s..i], s..i, quoted); + } + if c == '"' { + quoted = !quoted; } } if let Some(s) = start { - f(&text[s..], s..text.len()); + f(&text[s..], s..text.len(), quoted); } } @@ -1140,15 +1149,23 @@ pub fn scan(text: &str, set: &RuleSet) -> Vec { let want_card = set.is_on("bank-card"); // 一次扫描问一次时钟。只开卡号那条时也要问:认出是身份证号的不当卡号换 let today = if want_id || want_card { today_ymd() } else { 0 }; + // **个人号码只在 JSON 的字符串里找。**字符串外面的数字是 JSON 的数值:工具 + // 调用的参数(`"input":{"order_id":6222…}`)、`seed`。凭据规则在那儿天然认 + // 不出东西,号码规则却认得出 —— 而把一个数值换成占位符,整个请求体就不是 + // JSON 了。不是 JSON 的文本(直接拿来扫的一段话)不分里外 + let json = text.trim_start().starts_with(['{', '[', '"']); let mut spaced = Spaced::default(); - for_each_token(text, |tok, span| { - if want_id || want_card { + for_each_token(text, |tok, span, quoted| { + if (want_id || want_card) && (quoted || !json) { // 句末的句号不是号码的一部分:`…卡号是 6222 0212 3456 7894.` let body = tok.trim_end_matches('.'); if want_card { spaced.feed(text, span.start, body, body.len() < tok.len(), &mut out); } personal_token(body, span.start, want_id, want_card, today, &mut out); + } else if want_card { + // 字符串外面的东西把在接的那一串截断 + spaced.finish(text, &mut out); } if let Some(id) = classify_token(tok, set) { out.push(builtin_hit(id, span)); @@ -1991,6 +2008,41 @@ mod tests { } } + #[test] + fn a_number_outside_the_strings_of_a_body_is_a_json_number_and_left_alone() { + // 工具调用的参数、`seed` 是 JSON 的数值:换成占位符,整个请求体就不是 JSON 了 + let body = r#"{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"get_order","input":{"order_id":6222021234567894,"ids":[4532015112830366, 6222021234567894]}}]},{"role":"user","content":"他说\"卡号是 6222021234567894\",身份证 11010519491231002X"}],"seed":4532015112830366}"#; + let got = personal_found(body); + assert_eq!( + got, + vec![ + ("bank-card".to_string(), "6222021234567894".to_string()), + ( + "cn-resident-id".to_string(), + "11010519491231002X".to_string() + ), + ] + ); + let r = crate::redact::replace::redact( + body, + &RuleSet::defaults(), + crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), + ); + let v: serde_json::Value = serde_json::from_str(&r.text).expect("换完不是合法 JSON"); + assert_eq!(v["seed"], 4532015112830366u64); + assert_eq!( + v["messages"][0]["content"][0]["input"]["order_id"], + 6222021234567894u64 + ); + assert_eq!( + v["messages"][1]["content"], + "他说\"卡号是 <>\",身份证 <>" + ); + assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), body); + // 不是 JSON 的一段话不分里外 + assert_eq!(personal_found("order_id: 6222021234567894").len(), 1); + } + #[test] fn a_full_stop_after_a_number_does_not_hide_it() { let card = "6222021234567894"; diff --git a/docs/config.md b/docs/config.md index b6827ca4..7df73267 100644 --- a/docs/config.md +++ b/docs/config.md @@ -668,10 +668,12 @@ credentials, and match only what checks out by structure: Diners Club also 4-6-4). The test card numbers published by Stripe, Braintree and Adyen are not matched. -A number that is part of a longer run of letters or digits is not matched. -The placeholders of these two rules say what was there (`<>`, -`<>`), and the security log shows only the last four -characters of what they found. +A number that is part of a longer run of letters or digits is not matched, +and neither is one written as a JSON number in the request body (in a tool +call's arguments, for instance), since replacing it would leave the body +invalid JSON. The placeholders of these two rules say what was there +(`<>`, `<>`), and the security log shows only +the last four characters of what they found. #### `security.inspect_tools` diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index e3664649..0b7a0352 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -533,7 +533,7 @@ pricing: - `cn-resident-id`:18 位的中华人民共和国居民身份证号码。前两位须是省级行政区划代码,出生日期须是 1900 年 1 月 1 日至今天之间的真实日期,末位须是正确的校验码(ISO 7064 MOD 11-2)。15 位的旧号码不认。 - `bank-card`:卡号。开头和位数须属于银联、Visa、Mastercard、American Express、JCB、Discover 或 Diners Club,并通过 Luhn 校验;连续书写,或四位一组、以单个空格或单个连字符分隔均可(American Express 另认 4-6-5,Diners Club 另认 4-6-4)。Stripe、Braintree、Adyen 公开的测试卡号不认。 -夹在更长的一串字母或数字中间的号码不认。占位符写明原来是什么(`<>`、`<>`),安全日志中只显示最后四位。 +夹在更长的一串字母或数字中间的号码不认;请求体中以 JSON 数值写出的号码(例如工具调用的参数)也不认,替换它会使请求体不再是合法的 JSON。占位符写明原来是什么(`<>`、`<>`),安全日志中只显示最后四位。 #### `security.inspect_tools` From fe06e4ec739a4d331a531987d3adbbcfd41e4aa4 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Thu, 1 Oct 2026 18:51:18 +0800 Subject: [PATCH 4/4] fix(guard): personal-number placeholders carry the TW_ prefix too Every placeholder the desktop gateway writes starts with TW_ (<>), so a reader of the answer, or of the request detail, can tell the gateway's placeholders from text the model wrote. The two new labels now follow suit: <> and <>. Co-Authored-By: Claude Opus 5.5 --- crates/tw-gateway/tests/m5_redact.rs | 4 ++-- crates/tw-guard/src/redact/rules.rs | 18 +++++++++--------- docs/config.md | 2 +- docs/config.zh-CN.md | 2 +- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/crates/tw-gateway/tests/m5_redact.rs b/crates/tw-gateway/tests/m5_redact.rs index 76d28e97..95cfcf6f 100644 --- a/crates/tw-gateway/tests/m5_redact.rs +++ b/crates/tw-gateway/tests/m5_redact.rs @@ -35,7 +35,7 @@ async fn start_upstream(sse: bool) -> (SocketAddr, Arc>>) { *s.lock().unwrap() = body.to_vec(); let text = String::from_utf8_lossy(&body).to_string(); // 把请求里出现的东西挑出来放进回答里:占位符(`<>`、 - // `<>` …),或者没换掉的原值 + // `<>` …),或者没换掉的原值 let echoed = text .split('"') .find(|p| p.contains("<<") || p.contains("sk-ant-")) @@ -378,7 +378,7 @@ async fn id_and_card_numbers_leave_as_named_placeholders_and_come_back_whole() { "中转站看见了原值:{sent}" ); assert!( - sent.contains("身份证 <>,卡号 <>,"), + sent.contains("身份证 <>,卡号 <>,"), "{sent}" ); let joined: String = got diff --git a/crates/tw-guard/src/redact/rules.rs b/crates/tw-guard/src/redact/rules.rs index c94bf100..5ba2fb8c 100644 --- a/crates/tw-guard/src/redact/rules.rs +++ b/crates/tw-guard/src/redact/rules.rs @@ -122,7 +122,7 @@ pub struct Builtin { pub matcher: Matcher, /// 占位符里的标签。`None` 用账本的默认标签(桌面版是 `TW_SECRET`)。 /// - /// 个人号码写明是哪一种:模型看到 `<>` 才知道那里原来是个 + /// 个人号码写明是哪一种:模型看到 `<>` 才知道那里原来是个 /// 身份证号,答得像样 pub label: Option<&'static str>, } @@ -282,7 +282,7 @@ pub const BUILTINS: &[Builtin] = &[ matcher: Matcher::CnResidentId { born_since: BORN_SINCE, }, - label: Some("ID_NUMBER"), + label: Some("TW_ID_NUMBER"), }, Builtin { id: "bank-card", @@ -292,7 +292,7 @@ pub const BUILTINS: &[Builtin] = &[ matcher: Matcher::BankCard { networks: CARD_NETWORKS, }, - label: Some("CARD_NUMBER"), + label: Some("TW_CARD_NUMBER"), }, Builtin { id: "internal-ip", @@ -1828,7 +1828,7 @@ mod tests { &RuleSet::defaults(), crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), ); - assert_eq!(r.text, "身份证号:<>,请核对", "{id}"); + assert_eq!(r.text, "身份证号:<>,请核对", "{id}"); assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), t); } } @@ -1920,7 +1920,7 @@ mod tests { &RuleSet::defaults(), crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), ); - assert_eq!(r.text, "卡号 <> 尾号对一下", "{card}"); + assert_eq!(r.text, "卡号 <> 尾号对一下", "{card}"); assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), t); } } @@ -2036,7 +2036,7 @@ mod tests { ); assert_eq!( v["messages"][1]["content"], - "他说\"卡号是 <>\",身份证 <>" + "他说\"卡号是 <>\",身份证 <>" ); assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), body); // 不是 JSON 的一段话不分里外 @@ -2287,7 +2287,7 @@ mod tests { #[test] fn personal_placeholders_say_what_they_were_and_count_per_label() { - // 模型看到 `<>` 才知道那里是个身份证号;编号按标签各数各的, + // 模型看到 `<>` 才知道那里是个身份证号;编号按标签各数各的, // 和凭据的 `<>` 互不相干 let key = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA"; let body = serde_json::json!({ @@ -2304,12 +2304,12 @@ mod tests { let v: serde_json::Value = serde_json::from_str(&r.text).expect("换完不是合法 JSON"); assert_eq!( v["content"], - "key <>\n身份证 <>\n卡 <>\n另一张 <>\n身份证 <>" + "key <>\n身份证 <>\n卡 <>\n另一张 <>\n身份证 <>" ); assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), body); // 流式还原认得带标签的占位符,切成一个字符一段也拼得回来 let mut s = crate::redact::stream::Restorer::new(&r.ledger); - let echoed = "你的卡号 <> 和身份证 <>。"; + let echoed = "你的卡号 <> 和身份证 <>。"; let mut out = String::new(); for c in echoed.chars() { out.push_str(&s.process(&c.to_string())); diff --git a/docs/config.md b/docs/config.md index 7df73267..9157fe3d 100644 --- a/docs/config.md +++ b/docs/config.md @@ -672,7 +672,7 @@ A number that is part of a longer run of letters or digits is not matched, and neither is one written as a JSON number in the request body (in a tool call's arguments, for instance), since replacing it would leave the body invalid JSON. The placeholders of these two rules say what was there -(`<>`, `<>`), and the security log shows only +(`<>`, `<>`), and the security log shows only the last four characters of what they found. #### `security.inspect_tools` diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 0b7a0352..2df50c32 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -533,7 +533,7 @@ pricing: - `cn-resident-id`:18 位的中华人民共和国居民身份证号码。前两位须是省级行政区划代码,出生日期须是 1900 年 1 月 1 日至今天之间的真实日期,末位须是正确的校验码(ISO 7064 MOD 11-2)。15 位的旧号码不认。 - `bank-card`:卡号。开头和位数须属于银联、Visa、Mastercard、American Express、JCB、Discover 或 Diners Club,并通过 Luhn 校验;连续书写,或四位一组、以单个空格或单个连字符分隔均可(American Express 另认 4-6-5,Diners Club 另认 4-6-4)。Stripe、Braintree、Adyen 公开的测试卡号不认。 -夹在更长的一串字母或数字中间的号码不认;请求体中以 JSON 数值写出的号码(例如工具调用的参数)也不认,替换它会使请求体不再是合法的 JSON。占位符写明原来是什么(`<>`、`<>`),安全日志中只显示最后四位。 +夹在更长的一串字母或数字中间的号码不认;请求体中以 JSON 数值写出的号码(例如工具调用的参数)也不认,替换它会使请求体不再是合法的 JSON。占位符写明原来是什么(`<>`、`<>`),安全日志中只显示最后四位。 #### `security.inspect_tools`