From 4f65453df0d6e62796a66c84493aba3c88e82eff Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 12 Oct 2026 12:37:42 +0800 Subject: [PATCH 1/3] feat(redact): custom rules match text as written or by regex, case-sensitive on request A custom redaction rule now says how it matches: `match: contains` looks for the text as written (characters such as `.` and `*` have no special meaning), `match: regex` is a regular expression. `contains` is the default, so a word typed in as-is just works. `case_sensitive: true` tells capital letters from small ones; by default they are not told apart. - tw-guard: `Pattern` carries text, regex or not, and case; the rule set, the policy, the trial and the views use it. Code points are refused for redaction (`config.rule_match_bad`, `security.redact_match_bad`). - tw-api 47: `CustomRuleSave` and `SecurityTestRequest` take `match` and `case_sensitive` for redaction; `Matcher` `contains` / `regex` and `RuleSnapshot` say whether a rule is case-sensitive. - The configuration manual documents both fields. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/msg-codes.txt | 2 + crates/tw-api/src/lib.rs | 30 +++++- crates/tw-config/src/security.rs | 11 ++- crates/tw-config/src/validate.rs | 2 + crates/tw-config/tests/manual/schema.rs | 41 +++++++- crates/tw-control/src/security.rs | 75 +++++++++++++- crates/tw-control/tests/security.rs | 12 +-- crates/tw-control/tests/security_detail.rs | 4 +- crates/tw-gateway/src/guard/detail.rs | 29 ++++-- crates/tw-gateway/src/guard/detail/tests.rs | 1 + crates/tw-gateway/tests/m5_redact.rs | 2 + crates/tw-guard/src/lib.rs | 6 ++ crates/tw-guard/src/policy.rs | 104 +++++++++++++++++--- crates/tw-guard/src/redact/rules.rs | 84 +++++++++++----- crates/tw-guard/src/trial.rs | 19 +++- crates/tw-guard/src/view.rs | 66 +++++++++++-- crates/tw-store/src/recorder.rs | 1 + docs/config.md | 11 ++- docs/config.zh-CN.md | 10 +- 19 files changed, 426 insertions(+), 84 deletions(-) diff --git a/crates/tw-api/msg-codes.txt b/crates/tw-api/msg-codes.txt index fc92533d..365dae03 100644 --- a/crates/tw-api/msg-codes.txt +++ b/crates/tw-api/msg-codes.txt @@ -99,6 +99,7 @@ config.rotate.no_provider config.rotate.read_back_differs config.rule_codepoints_bad config.rule_label_bad +config.rule_match_bad config.rule_name_empty config.rule_name_taken config.rule_pattern_bad @@ -500,6 +501,7 @@ security.bad_pattern security.content_action_unknown security.no_action_of_its_own security.pattern_empty +security.redact_match_bad security.rule_name_empty security.unknown_action security.unknown_guard diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 5c0a719b..5c0014fc 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -900,7 +900,18 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// **46 起看得出密钥是账号登录换来的**:[`ProviderView`] 多了 `signed_in`([`ZaiFamily`])。 /// Z.ai / BigModel 的账号登录在它写的上游上记下 `signed_in: zai | bigmodel`;重新登录照旧 /// 写上,在界面里保存时密钥没变就留着,换成了别的密钥就去掉。手填的密钥和别的上游是 null。 -pub const CONTROL_API_VERSION: u32 = 46; +/// +/// **47 起出站脱敏的自定义规则能选怎么认、分不分大小写**:[`CustomRuleSave`] 和 +/// [`SecurityTestRequest`] 的 `match` 出站脱敏也认(`contains` 按原样找这段文字、`regex`; +/// 不给是 `contains`,**以前是正则**),多了 `case_sensitive`(不给是不分)。规则视图里 +/// 出站脱敏的自定义规则是 [`Matcher`] 的 `contains` 或 `regex`,两者都多了 +/// `case_sensitive`(工具调用审查的正则是 `true`)。安全日志的 [`RuleSnapshot`] 多了 +/// `case_sensitive`,出站脱敏的自定义规则也带 `matching`。码位交给出站脱敏是 400 +/// (`security.redact_match_bad`),配置里写了是 `config.rule_match_bad`。配置里不写 +/// `match` 的老规则从此按原样找。 +/// +/// 出站脱敏不再碰请求体的结构:键,和 id、类型、角色、工具名、模型名这些值。 +pub const CONTROL_API_VERSION: u32 = 47; #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "ts", derive(ts_rs::TS))] @@ -5897,9 +5908,13 @@ pub struct RuleSnapshot { /// 自定义规则写的样子,原样(正则、关键词、码位)。内置规则没有 #[serde(default, skip_serializing_if = "Option::is_none")] pub pattern: Option, - /// 内容过滤:这条规则怎么认(`contains` / `regex` / `codepoints`)。别的防护没有 + /// 自定义规则怎么认:内容过滤是 `contains` / `regex` / `codepoints`,出站脱敏是 + /// `contains` / `regex`。内置规则和工具调用审查没有 #[serde(default, skip_serializing_if = "Option::is_none")] pub matching: Option, + /// 出站脱敏的自定义规则:分大小写 + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub case_sensitive: bool, /// 认出它的 core 的版本 pub core_version: String, } @@ -6028,15 +6043,19 @@ pub struct ActionSave { #[cfg_attr(feature = "ts", derive(ts_rs::TS))] pub struct CustomRuleSave { pub name: String, - /// 正则;内容过滤按 `match`:要找的那段文字、正则,或者码位(`U+200B, U+E0000–U+E007F`) + /// 工具调用审查是正则;出站脱敏和内容过滤按 `match`:要找的那段文字、正则,或者码位 + /// (`U+200B, U+E0000–U+E007F`,只有内容过滤) pub pattern: String, /// 工具调用审查:`cut` / `record`;内容过滤:`block` / `strip` / `record`。不给按 `record` #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option, - /// 内容过滤才有:`contains`(不分大小写的子串)/ `regex` / `codepoints`。不给按 - /// `contains`。别的防护的自定义规则都是正则 + /// 怎么认。内容过滤:`contains`(不分大小写的子串)/ `regex` / `codepoints`;出站脱敏: + /// `contains`(按原样找这段文字)/ `regex`。不给按 `contains`。工具调用审查的都是正则 #[serde(rename = "match", default, skip_serializing_if = "Option::is_none")] pub matching: Option, + /// 出站脱敏才有:分大小写。不给是不分 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub case_sensitive: Option, /// 出站脱敏才有:占位符名称,`PROJECT` 换成 `<>`。大写字母开头,其余是 /// 大写字母、数字、下划线,最多 24 个字符。不给是 `SECRET` #[serde(default, skip_serializing_if = "Option::is_none")] @@ -6887,6 +6906,7 @@ mod tests { name: "plan".into(), pattern: Some("forbidden-plan".into()), matching: Some(ContentMatch::Contains), + case_sensitive: false, core_version: "0.67.1".into(), }; assert_eq!( diff --git a/crates/tw-config/src/security.rs b/crates/tw-config/src/security.rs index e11feec7..8f7cbd21 100644 --- a/crates/tw-config/src/security.rs +++ b/crates/tw-config/src/security.rs @@ -48,6 +48,11 @@ pub fn policy_msg(e: &PolicyError) -> Msg { "the placeholder name of custom redaction rule `{name}` is `{label}`; it has to be \ 1 to 24 capital letters, digits and underscores, starting with a letter" ), + PolicyError::BadMatch { name, matching } => msg!( + "config.rule_match_bad", name = name.clone(), matching = matching.slug() => + "custom redaction rule `{name}` matches by `{matching}`; redaction rules match by \ + contains or regex" + ), PolicyError::UnknownRule { guard, id } => msg!( "config.unknown_rule", guard = guard.slug(), rule = id.clone() => "security.{guard} names `{rule}`, which is not a built-in rule" @@ -89,9 +94,13 @@ mod tests { "config.rule_pattern_empty", ), ( - "redact:\n custom:\n - { name: a, pattern: '(' }", + "redact:\n custom:\n - { name: a, pattern: '(', match: regex }", "config.rule_pattern_bad", ), + ( + "redact:\n custom:\n - { name: a, pattern: x, match: codepoints }", + "config.rule_match_bad", + ), ( "content:\n custom:\n - { name: a, pattern: 'U+GG', match: codepoints }", "config.rule_codepoints_bad", diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index acb99286..f817d81d 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -1377,6 +1377,8 @@ groups: .map(|(n, pat)| crate::CustomRedactRule { name: n.to_string(), pattern: pat.to_string(), + matching: crate::ContentMatch::Regex, + case_sensitive: true, label: None, disabled: false, }) diff --git a/crates/tw-config/tests/manual/schema.rs b/crates/tw-config/tests/manual/schema.rs index 492655b5..3e59d24c 100644 --- a/crates/tw-config/tests/manual/schema.rs +++ b/crates/tw-config/tests/manual/schema.rs @@ -61,6 +61,16 @@ fn content_actions() -> Vec<&'static str> { fn content_matches() -> Vec<&'static str> { super::fields::() } +/// 出站脱敏认的那几种:码位只有内容过滤认 +fn redact_matches() -> Vec<&'static str> { + super::fields::() + .into_iter() + .filter(|m| { + let m: ContentMatch = serde_yaml_ng::from_str(m).unwrap(); + tw_guard::policy::redact_match("x", m, false).is_some() + }) + .collect() +} fn group_types() -> Vec<&'static str> { super::fields::() } @@ -1118,8 +1128,8 @@ pub fn sections() -> Vec
{ Kind::Objs("security.redact.custom[]"), Def::Is("[]"), t( - "Rules of your own: whatever a pattern matches is replaced like a credential.", - "自定义规则:正则匹配到的内容和凭据一样替换。", + "Rules of your own: whatever a rule matches is replaced like a credential.", + "自定义规则:匹配到的内容和凭据一样替换。", ), ), ], @@ -1133,15 +1143,36 @@ pub fn sections() -> Vec
{ "pattern", Kind::Str, Def::Required, - t("Regular expression.", "正则表达式。"), + t( + "The text to look for; a regular expression with `match: regex`.", + "要查找的文字;`match: regex` 时为正则表达式。", + ), + ), + row( + "match", + Kind::Enum(redact_matches), + Def::Is("contains"), + t( + "`contains`: `pattern` is looked for as written; characters such as `.` and `*` have no special meaning. `regex`: `pattern` is a regular expression.", + "`contains`:按原样查找 `pattern`,`.`、`*` 等字符没有特殊含义。`regex`:`pattern` 是正则表达式。", + ), + ), + row( + "case_sensitive", + Kind::Bool, + Def::Is("false"), + t( + "Tell capital letters from small ones. Off by default: `ABC` and `abc` both match.", + "区分大小写。默认不区分:`ABC` 和 `abc` 都会匹配。", + ), ), row( "label", Kind::Str, Def::Is("SECRET"), t( - "Placeholder name: what the pattern matches is replaced with `<>`, numbered per name. Capital letters, digits and underscores, starting with a letter, at most 24 characters.", - "占位符名称:正则匹配到的内容替换为 `<>`,每个名称各自编号。只能使用大写字母、数字和下划线,以字母开头,最多 24 个字符。", + "Placeholder name: what the rule matches is replaced with `<>`, numbered per name. Capital letters, digits and underscores, starting with a letter, at most 24 characters.", + "占位符名称:匹配到的内容替换为 `<>`,每个名称各自编号。只能使用大写字母、数字和下划线,以字母开头,最多 24 个字符。", ), ), row("disabled", Kind::Bool, Def::Is("false"), RULE_DISABLED), diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index 531101c2..f5da4eec 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -327,6 +327,8 @@ fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result Fail { PolicyError::BadPattern { guard, detail, .. } => bad_pattern(guard, detail), PolicyError::BadCodepoints { reason, .. } => bad_codepoints(reason), PolicyError::BadLabel { label, .. } => bad_label(label), + PolicyError::BadMatch { matching, .. } => bad_match(matching), // 只有一条规则的策略里不会有:名字重复由写文件那一步说,内置规则的 id 不在这里写 e @ (PolicyError::DuplicateName { .. } | PolicyError::UnknownRule { .. }) => { tw_config::policy_msg(&e) @@ -392,6 +395,14 @@ fn rule_fail(e: PolicyError) -> Fail { fail(StatusCode::BAD_REQUEST, m) } +/// 出站脱敏的规则按原样找或者按正则,码位只有内容过滤认 +fn bad_match(matching: tw_api::ContentMatch) -> tw_types::Msg { + msg!( + "security.redact_match_bad", matching = matching.slug() => + "A redaction rule matches by contains or regex, not `{matching}`." + ) +} + fn pattern_empty() -> tw_types::Msg { msg!("security.pattern_empty" => "The pattern is empty.") } @@ -522,6 +533,7 @@ fn trial_fail(guard: Guard, e: TrialError) -> Fail { TrialError::BadPattern { detail } => bad_pattern(guard, detail), TrialError::BadCodepoints { reason } => bad_codepoints(reason), TrialError::BadLabel { label } => bad_label(label), + TrialError::BadMatch { matching } => bad_match(matching), }; fail(StatusCode::BAD_REQUEST, m) } @@ -536,6 +548,7 @@ mod tests { pattern: pattern.into(), action: None, matching: None, + case_sensitive: None, label: None, enabled: true, base_version: None, @@ -565,6 +578,30 @@ mod tests { ) .unwrap(); assert!(!yaml(&m).contains("label"), "{}", yaml(&m)); + // 怎么认、分不分大小写:和出厂(按原样找、不分)不一样才写 + let m = custom_item( + Guard::Redact, + &tw_api::CustomRuleSave { + matching: Some(tw_api::ContentMatch::Regex), + case_sensitive: Some(true), + ..save("a", "x+") + }, + ) + .unwrap(); + assert_eq!( + yaml(&m), + "name: a\npattern: x+\nmatch: regex\ncase_sensitive: true\n" + ); + let m = custom_item( + Guard::Redact, + &tw_api::CustomRuleSave { + matching: Some(tw_api::ContentMatch::Contains), + case_sensitive: Some(false), + ..save("a", "x+") + }, + ) + .unwrap(); + assert_eq!(yaml(&m), "name: a\npattern: x+\n"); let m = custom_item( Guard::Redact, &tw_api::CustomRuleSave { @@ -612,7 +649,22 @@ mod tests { (Guard::Redact, save(" ", "x"), "security.rule_name_empty"), (Guard::Redact, save("a", ""), "security.pattern_empty"), (Guard::Content, save("a", " "), "security.pattern_empty"), - (Guard::Redact, save("a", "("), "security.bad_pattern"), + ( + Guard::Redact, + tw_api::CustomRuleSave { + matching: Some(tw_api::ContentMatch::Regex), + ..save("a", "(") + }, + "security.bad_pattern", + ), + ( + Guard::Redact, + tw_api::CustomRuleSave { + matching: Some(tw_api::ContentMatch::Codepoints), + ..save("a", "x") + }, + "security.redact_match_bad", + ), (Guard::InspectTools, save("a", "("), "security.bad_pattern"), ( Guard::Content, @@ -676,7 +728,26 @@ mod tests { pattern: Some(pattern.into()), ..Default::default() }; - assert_eq!(run(Guard::Redact, req("(")), "security.bad_pattern"); + assert_eq!( + run( + Guard::Redact, + tw_api::SecurityTestRequest { + matching: Some(tw_api::ContentMatch::Regex), + ..req("(") + } + ), + "security.bad_pattern" + ); + assert_eq!( + run( + Guard::Redact, + tw_api::SecurityTestRequest { + matching: Some(tw_api::ContentMatch::Codepoints), + ..req("x") + } + ), + "security.redact_match_bad" + ); assert_eq!(run(Guard::Redact, req("")), "security.pattern_empty"); assert_eq!( run( diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index 8033efd9..428128fd 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -540,7 +540,7 @@ async fn a_broken_pattern_is_refused_before_anything_is_written() { &b.app, "POST", "/security/redact/custom", - json!({ "name": "写坏了", "pattern": "(" }), + json!({ "name": "写坏了", "pattern": "(", "match": "regex" }), ) .await; assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); @@ -587,7 +587,7 @@ async fn trying_a_pattern_reports_where_it_matched_in_javascript_offsets() { &b.app, "POST", "/security/redact/test", - json!({ "sample": sample, "pattern": "corp_[A-Za-z0-9]{12}" }), + json!({ "sample": sample, "pattern": "corp_[A-Za-z0-9]{12}", "match": "regex" }), ) .await; assert_eq!(st, StatusCode::OK, "{v}"); @@ -605,7 +605,7 @@ async fn trying_a_pattern_reports_where_it_matched_in_javascript_offsets() { &b.app, "POST", "/security/redact/test", - json!({ "sample": "pw=hunter2\n下一行", "pattern": "pw=\\S+" }), + json!({ "sample": "pw=hunter2\n下一行", "pattern": "pw=\\S+", "match": "regex" }), ) .await; assert_eq!(v["hits"][0]["end"], 10, "{v}"); @@ -1181,7 +1181,7 @@ async fn a_custom_redaction_rule_carries_its_placeholder_name() { &b.app, "POST", "/security/redact/custom", - json!({ "name": "项目代号", "pattern": "Project-[A-Z]+", "label": "PROJECT" }), + json!({ "name": "项目代号", "pattern": "Project-[A-Z]+", "match": "regex", "label": "PROJECT" }), ) .await; assert_eq!(st, StatusCode::OK, "{v}"); @@ -1194,7 +1194,7 @@ async fn a_custom_redaction_rule_carries_its_placeholder_name() { &b.app, "PUT", "/security/redact/custom/项目代号", - json!({ "name": "项目代号", "pattern": "Project-[A-Z]+", "label": "SECRET" }), + json!({ "name": "项目代号", "pattern": "Project-[A-Z]+", "match": "regex", "label": "SECRET" }), ) .await; assert_eq!(st, StatusCode::OK, "{v}"); @@ -1218,7 +1218,7 @@ async fn a_custom_redaction_rule_carries_its_placeholder_name() { &b.app, "POST", "/security/redact/test", - json!({ "sample": "上线 Project-ORION", "pattern": "Project-[A-Z]+", "label": "PROJECT" }), + json!({ "sample": "上线 Project-ORION", "pattern": "Project-[A-Z]+", "match": "regex", "label": "PROJECT" }), ) .await; assert_eq!(st, StatusCode::OK, "{v}"); diff --git a/crates/tw-control/tests/security_detail.rs b/crates/tw-control/tests/security_detail.rs index 5f4d8987..956bb796 100644 --- a/crates/tw-control/tests/security_detail.rs +++ b/crates/tw-control/tests/security_detail.rs @@ -90,6 +90,7 @@ security: custom: - name: 公司令牌 pattern: 'corp_[A-Z0-9]{{12}}' + match: regex inspect_tools: mode: enforce content: @@ -284,6 +285,7 @@ async fn every_guard_logs_where_what_and_how_and_never_a_value() { ); let corp = by_rule(&events, "公司令牌"); assert_eq!(corp["rule_snapshot"]["pattern"], "corp_[A-Z0-9]{12}"); + assert_eq!(corp["rule_snapshot"]["matching"], "regex"); assert_eq!( corp["outcome_detail"]["placeholders"], json!(["<>"]) @@ -402,7 +404,7 @@ async fn a_rule_edited_afterwards_leaves_the_earlier_record_as_it_was() { &w.app, "PUT", "/security/redact/custom/公司令牌", - json!({"name": "公司令牌", "pattern": "corp_[A-Z]{6}[0-9]{6}"}), + json!({"name": "公司令牌", "pattern": "corp_[A-Z]{6}[0-9]{6}", "match": "regex"}), ) .await; assert_eq!(st, StatusCode::OK, "{v}"); diff --git a/crates/tw-gateway/src/guard/detail.rs b/crates/tw-gateway/src/guard/detail.rs index 450df3d3..3a476a88 100644 --- a/crates/tw-gateway/src/guard/detail.rs +++ b/crates/tw-gateway/src/guard/detail.rs @@ -391,16 +391,27 @@ fn secret_detail( .to_string(), pattern: None, matching: None, + case_sensitive: false, core_version: core_version(), }, - Rule::Custom(name) => RuleSnapshot { - builtin: false, - id: name.to_string(), - name: name.to_string(), - pattern: rules.custom_pattern(name).map(str::to_string), - matching: None, - core_version: core_version(), - }, + Rule::Custom(name) => { + let p = rules.custom_pattern(name); + RuleSnapshot { + builtin: false, + id: name.to_string(), + name: name.to_string(), + pattern: p.map(|p| p.text.clone()), + matching: p.map(|p| { + if p.regex { + tw_api::ContentMatch::Regex + } else { + tw_api::ContentMatch::Contains + } + }), + case_sensitive: p.is_some_and(|p| p.case_sensitive), + core_version: core_version(), + } + } }; let outcome_detail = if seen.replaced { OutcomeDetail::Replaced { @@ -526,6 +537,7 @@ pub fn content(src: &Screened<'_>, sc: &tw_guard::content::Screening) -> Vec Result { + bounded_with(pattern, false) +} + +/// [`bounded`],`ignore_case` 时不分大小写 +fn bounded_with(pattern: &str, ignore_case: bool) -> Result { regex::RegexBuilder::new(pattern) + .case_insensitive(ignore_case) .size_limit(1 << 20) .dfa_size_limit(1 << 20) .build() diff --git a/crates/tw-guard/src/policy.rs b/crates/tw-guard/src/policy.rs index 1cf1b9ad..7943a143 100644 --- a/crates/tw-guard/src/policy.rs +++ b/crates/tw-guard/src/policy.rs @@ -12,7 +12,9 @@ //! disable: [jwt] # 关掉出厂开着的内置规则 //! custom: //! - name: 内部项目号 # 名字也是标识,同一项里不许重名 -//! pattern: 'PRJ-\d{6}' # 正则 +//! pattern: 'PRJ-\d{6}' +//! match: regex # contains | regex;不写 = contains(按原样找这段文字) +//! case_sensitive: true # 可选;不写 = 不分大小写 //! label: PROJECT # 可选;占位符 <>;不写 = SECRET //! disabled: true # 可选 //! inspect_tools: @@ -57,7 +59,7 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use crate::content::{self, CodepointError, Codepoints}; -use crate::redact::rules::RuleSet; +use crate::redact::rules::{Pattern, RuleSet}; use crate::tools::rules as tool_rules; /// 一项防护的档位。 @@ -260,8 +262,15 @@ pub fn placeholder_label(label: &str) -> String { pub struct CustomRedactRule { /// 日志和界面上显示的名字,也是它的标识 pub name: String, - /// 正则表达式 + /// 要找的那段文字,或者正则(按 `match`) pub pattern: String, + /// `contains`:按原样找这段文字(**不写就是它**:用户填的多半就是那个词,`.`、`*` + /// 不该有特殊含义);`regex`:正则。码位只有内容过滤认 + #[serde(rename = "match", default, skip_serializing_if = "is_default")] + pub matching: ContentMatch, + /// 分大小写。不写是不分 + #[serde(default, skip_serializing_if = "is_false")] + pub case_sensitive: bool, /// 占位符里的标签:`PROJECT` 换成 `<>`。不写是 [`DEFAULT_LABEL`];写的 /// 就是它的,读进来也是不写(见 `label_or_default`) #[serde( @@ -415,6 +424,15 @@ pub enum PolicyError { BadLabel { name: String, label: String }, #[error("security.{guard} names `{id}`, which is not a built-in rule")] UnknownRule { guard: Guard, id: String }, + #[error( + "custom redaction rule `{name}` matches by `{}`; redaction rules match by contains or \ + regex", + .matching.slug() + )] + BadMatch { + name: String, + matching: ContentMatch, + }, } impl PolicyError { @@ -428,6 +446,7 @@ impl PolicyError { PolicyError::BadCodepoints { .. } => "rule_codepoints_bad", PolicyError::BadLabel { .. } => "rule_label_bad", PolicyError::UnknownRule { .. } => "unknown_rule", + PolicyError::BadMatch { .. } => "rule_match_bad", } } @@ -440,7 +459,7 @@ impl PolicyError { | PolicyError::BadPattern { guard, .. } | PolicyError::UnknownRule { guard, .. } => *guard, PolicyError::BadCodepoints { .. } => Guard::Content, - PolicyError::BadLabel { .. } => Guard::Redact, + PolicyError::BadLabel { .. } | PolicyError::BadMatch { .. } => Guard::Redact, } } } @@ -527,7 +546,7 @@ impl RedactPolicy { for c in self.custom.iter().filter(|c| !c.disabled) { let label = custom_redact(c)?; set = set - .with_labeled(&c.name, &c.pattern, label.as_deref()) + .with_rule(&c.name, redact_pattern(c)?, label.as_deref()) .map_err(|e| PolicyError::BadPattern { guard: Guard::Redact, name: e.name, @@ -538,6 +557,32 @@ impl RedactPolicy { } } +/// 一条自定义脱敏规则写的样子和怎么认。码位不是它认的写法 +fn redact_pattern(c: &CustomRedactRule) -> Result { + redact_match(&c.pattern, c.matching, c.case_sensitive).ok_or_else(|| PolicyError::BadMatch { + name: c.name.clone(), + matching: c.matching, + }) +} + +/// 出站脱敏认的写法:按原样找、正则。码位是 `None` +pub fn redact_match( + pattern: &str, + matching: ContentMatch, + case_sensitive: bool, +) -> Option { + let regex = match matching { + ContentMatch::Contains => false, + ContentMatch::Regex => true, + ContentMatch::Codepoints => return None, + }; + Some(Pattern { + text: pattern.to_string(), + regex, + case_sensitive, + }) +} + /// 一条自定义脱敏规则编得过吗;编得过的话,它在占位符里的标签(不写是 `None`,用 /// 账本的默认标签) fn custom_redact(c: &CustomRedactRule) -> Result, PolicyError> { @@ -547,11 +592,13 @@ fn custom_redact(c: &CustomRedactRule) -> Result, PolicyError> { name: c.name.clone(), }); } - crate::redact::rules::compile(&c.name, &c.pattern).map_err(|e| PolicyError::BadPattern { - guard: Guard::Redact, - name: c.name.clone(), - detail: e.detail, - })?; + redact_pattern(c)? + .compile(&c.name) + .map_err(|e| PolicyError::BadPattern { + guard: Guard::Redact, + name: c.name.clone(), + detail: e.detail, + })?; match &c.label { None => Ok(None), Some(l) if label_ok(l) => Ok(Some(placeholder_label(l))), @@ -877,9 +924,13 @@ content: "rule_pattern_empty", ), ( - "redact:\n custom:\n - { name: a, pattern: '(' }", + "redact:\n custom:\n - { name: a, pattern: '(', match: regex }", "rule_pattern_bad", ), + ( + "redact:\n custom:\n - { name: a, pattern: x, match: codepoints }", + "rule_match_bad", + ), ( "content:\n custom:\n - { name: a, pattern: '[', match: regex }", "rule_pattern_bad", @@ -973,7 +1024,7 @@ content: #[test] fn the_redact_policy_reaches_the_rules_with_labels() { let p: RedactPolicy = serde_yaml_ng::from_str( - "enable: [internal-ip]\ndisable: [jwt]\ncustom:\n - { name: 项目号, pattern: 'PRJ-\\d{6}', label: PROJECT }\n - { name: 停用的, pattern: zzz, disabled: true }\n - { name: 不写标签, pattern: 'corp_[a-z]{4}' }\n", + "enable: [internal-ip]\ndisable: [jwt]\ncustom:\n - { name: 项目号, pattern: 'PRJ-\\d{6}', match: regex, label: PROJECT }\n - { name: 停用的, pattern: zzz, disabled: true }\n - { name: 不写标签, pattern: 'corp_[a-z]{4}', match: regex }\n", ) .unwrap(); let rs = p.rules().unwrap(); @@ -988,6 +1039,35 @@ content: assert_eq!(r.text, "<> <> zzz"); } + /// 不写 `match` 是按原样找:用户填的多半就是那个词,`.`、`*` 不该有特殊含义。不写 + /// `case_sensitive` 是不分大小写 + #[test] + fn a_redact_rule_looks_for_its_text_as_written_unless_it_says_regex() { + let rules = |yaml: &str| { + serde_yaml_ng::from_str::(yaml) + .unwrap() + .rules() + .unwrap() + }; + let found = |rs: &RuleSet, text: &str| -> Vec { + crate::redact::rules::scan_plain(text, rs) + .iter() + .filter(|h| h.rule.custom()) + .map(|h| text[h.bytes.clone()].to_string()) + .collect() + }; + let plain = rules("custom:\n - { name: a, pattern: 'a.b*' }\n"); + assert_eq!(found(&plain, "a.b* A.B* axbb"), ["a.b*", "A.B*"]); + let exact = rules("custom:\n - { name: a, pattern: 'a.b*', case_sensitive: true }\n"); + assert_eq!(found(&exact, "a.b* A.B* axbb"), ["a.b*"]); + let regex = rules("custom:\n - { name: a, pattern: 'a.b+', match: regex }\n"); + assert_eq!(found(®ex, "a.b AXBB"), ["a.b", "AXBB"]); + let regex = rules( + "custom:\n - { name: a, pattern: 'a.b+', match: regex, case_sensitive: true }\n", + ); + assert_eq!(found(®ex, "a.b AXBB"), ["a.b"]); + } + #[test] fn the_tool_policy_reaches_the_rules() { let p = ToolPolicy { diff --git a/crates/tw-guard/src/redact/rules.rs b/crates/tw-guard/src/redact/rules.rs index 57aa0ba6..45aed111 100644 --- a/crates/tw-guard/src/redact/rules.rs +++ b/crates/tw-guard/src/redact/rules.rs @@ -392,6 +392,8 @@ pub struct Hit { pub struct Custom { pub name: Arc, pub re: regex::Regex, + /// 写的样子和怎么认([`Pattern`]),原样:安全日志记下命中那一刻的规则 + pub pattern: Pattern, /// 占位符里的标签(企业版的 `EMAIL`、`PHONE`)。`None` 用账本的默认标签 pub label: Option>, } @@ -404,19 +406,50 @@ pub struct BadPattern { pub detail: String, } +/// 一条自定义规则写的样子和怎么认。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pattern { + pub text: String, + /// 是正则;不是就按原样找这段文字 + pub regex: bool, + /// 分大小写 + pub case_sensitive: bool, +} + +impl Pattern { + /// 一段正则,分大小写 + pub fn regex(text: &str) -> Self { + Self { + text: text.to_string(), + regex: true, + case_sensitive: true, + } + } + + /// 编成正则:按原样找的那段文字先转义 + pub fn compile(&self, name: &str) -> Result { + if self.text.is_empty() { + return Err(BadPattern { + name: name.to_string(), + detail: "the pattern is empty".to_string(), + }); + } + let source = if self.regex { + self.text.clone() + } else { + regex::escape(&self.text) + }; + crate::bounded_with(&source, !self.case_sensitive).map_err(|e| BadPattern { + name: name.to_string(), + detail: e.to_string(), + }) + } +} + /// 编一条正则。**长度和编译后的大小都有上限** —— 这条正则要在每个请求体 /// 上跑,一个写得很大的正则不该拖慢每一个请求。 pub fn compile(name: &str, pattern: &str) -> Result { - if pattern.is_empty() { - return Err(BadPattern { - name: name.to_string(), - detail: "the pattern is empty".to_string(), - }); - } - crate::bounded(pattern).map_err(|e| BadPattern { - name: name.to_string(), - detail: e.to_string(), - }) + Pattern::regex(pattern).compile(name) } /// 这一次按哪些规则找。 @@ -484,11 +517,7 @@ impl RuleSet { set.on.remove(b.id); } for (name, pattern) in custom { - set.custom.push(Custom { - name: Arc::from(name), - re: compile(name, pattern)?, - label: None, - }); + set = set.with_labeled(name, pattern, None)?; } Ok(set) } @@ -498,16 +527,27 @@ impl RuleSet { self.with_labeled(name, pattern, None) } - /// 再加一条自定义规则,占位符用它自己的标签:`{{EMAIL_1}}` 里的 `EMAIL`。 + /// 再加一条正则写的自定义规则,占位符用它自己的标签:`{{EMAIL_1}}` 里的 `EMAIL`。 pub fn with_labeled( - mut self, + self, name: &str, pattern: &str, label: Option<&str>, + ) -> Result { + self.with_rule(name, Pattern::regex(pattern), label) + } + + /// 再加一条自定义规则:按原样找一段文字或者按正则,分不分大小写由 `pattern` 说。 + pub fn with_rule( + mut self, + name: &str, + pattern: Pattern, + label: Option<&str>, ) -> Result { self.custom.push(Custom { name: Arc::from(name), - re: compile(name, pattern)?, + re: pattern.compile(name)?, + pattern, label: label.map(Arc::from), }); Ok(self) @@ -517,13 +557,13 @@ impl RuleSet { self.on.contains(id) } - /// 名字是 `name` 的自定义规则的正则,**写的原样**(编译时没改过它)。没有这条规则是 - /// `None`。安全日志记下命中那一刻的规则:之后改了、删了,那一条说的还是当时那一版 - pub fn custom_pattern(&self, name: &str) -> Option<&str> { + /// 名字是 `name` 的自定义规则**写的样子和怎么认**。没有这条规则是 `None`。安全日志记下 + /// 命中那一刻的规则:之后改了、删了,那一条说的还是当时那一版 + pub fn custom_pattern(&self, name: &str) -> Option<&Pattern> { self.custom .iter() .find(|c| &*c.name == name) - .map(|c| c.re.as_str()) + .map(|c| &c.pattern) } /// 一条都没开。**调用方据此整条短路** —— 没有规则的话,找都不用找。 diff --git a/crates/tw-guard/src/trial.rs b/crates/tw-guard/src/trial.rs index ee356351..1c3d6a27 100644 --- a/crates/tw-guard/src/trial.rs +++ b/crates/tw-guard/src/trial.rs @@ -14,7 +14,7 @@ use serde::{Deserialize, Serialize}; use crate::content::{self, Codepoints, Scope}; use crate::policy::{ ContentAction, ContentMatch, ContentPolicy, Guard, PolicyError, RedactPolicy, Security, - ToolAction, ToolPolicy, label_ok, placeholder_label, + ToolAction, ToolPolicy, label_ok, placeholder_label, redact_match, }; use crate::redact::replace::{Ledger, Scheme}; use crate::redact::rules::RuleSet; @@ -28,12 +28,16 @@ pub const TRIAL: &str = "trial"; #[cfg_attr(feature = "ts", derive(ts_rs::TS), ts(rename = "SecurityTestRequest"))] pub struct TrialRequest { pub sample: String, - /// 只试这一条(正在编辑的规则):出站脱敏和工具调用审查是正则,内容过滤按 `match` + /// 只试这一条(正在编辑的规则):工具调用审查是正则,出站脱敏和内容过滤按 `match` #[serde(default, skip_serializing_if = "Option::is_none")] pub pattern: Option, - /// 内容过滤试 `pattern` 时怎么认:`contains` / `regex` / `codepoints`,不给按 `contains` + /// 试 `pattern` 时怎么认:内容过滤是 `contains` / `regex` / `codepoints`,出站脱敏是 + /// `contains` / `regex`。不给按 `contains` #[serde(rename = "match", default, skip_serializing_if = "Option::is_none")] pub matching: Option, + /// 出站脱敏试 `pattern` 时分不分大小写。不给是不分 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub case_sensitive: Option, /// 只试这一条内置规则(停用着的也能试) #[serde(default, skip_serializing_if = "Option::is_none")] pub rule: Option, @@ -101,6 +105,8 @@ pub enum TrialError { BadLabel { label: String }, #[error("`{}` is not something a {} rule does", .action.slug(), .guard.rule_noun())] BadAction { guard: Guard, action: RuleAction }, + #[error("redaction rules match by contains or regex, not `{}`", .matching.slug())] + BadMatch { matching: ContentMatch }, /// 现在的策略本身编不起来(绕过了校验写进去的) #[error(transparent)] Policy(#[from] PolicyError), @@ -115,6 +121,7 @@ impl TrialError { TrialError::BadCodepoints { .. } => "rule_codepoints_bad", TrialError::BadLabel { .. } => "rule_label_bad", TrialError::BadAction { .. } => "rule_action_bad", + TrialError::BadMatch { .. } => "rule_match_bad", TrialError::Policy(e) => e.code(), } } @@ -145,8 +152,11 @@ fn redact(p: &RedactPolicy, req: &TrialRequest) -> Result Some(placeholder_label(l)), Some(l) => return Err(TrialError::BadLabel { label: l.clone() }), }; + let matching = req.matching.unwrap_or_default(); + let pattern = redact_match(pattern, matching, req.case_sensitive.unwrap_or(false)) + .ok_or(TrialError::BadMatch { matching })?; RuleSet::none() - .with_labeled(TRIAL, pattern, label.as_deref()) + .with_rule(TRIAL, pattern, label.as_deref()) .map_err(|e| TrialError::BadPattern { detail: e.detail })? } (None, Some(id)) => { @@ -403,6 +413,7 @@ mod tests { let s = Security::default(); let mut q = req("编号 PRJ-123456 和 PRJ-654321"); q.pattern = Some(r"PRJ-\d{6}".into()); + q.matching = Some(ContentMatch::Regex); q.label = Some("PROJECT".into()); let r = run(Guard::Redact, &s, &q).unwrap(); assert_eq!( diff --git a/crates/tw-guard/src/view.rs b/crates/tw-guard/src/view.rs index c59eb7aa..a57641ce 100644 --- a/crates/tw-guard/src/view.rs +++ b/crates/tw-guard/src/view.rs @@ -16,11 +16,15 @@ use serde::{Deserialize, Serialize}; use crate::content::{self, Codepoints}; use crate::policy::{ - ContentAction, ContentPolicy, DEFAULT_LABEL, LABEL_PREFIX, Mode, RedactPolicy, Security, - ToolAction, ToolPolicy, + ContentAction, ContentMatch, ContentPolicy, DEFAULT_LABEL, LABEL_PREFIX, Mode, RedactPolicy, + Security, ToolAction, ToolPolicy, }; use crate::redact::rules as redact_rules; +fn is_false(b: &bool) -> bool { + !*b +} + /// 一条规则在第三档下做什么。工具调用审查是 `cut` / `record`,内容过滤是 `block` / /// `strip` / `record`;出站脱敏的规则命中即替换,没有这一项。 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] @@ -110,9 +114,19 @@ pub enum Matcher { /// 中国大陆手机号:11 位数字,`1` 开头、第二位是 `3`–`9`,前后不紧挨别的数字 CnMobilePhone, /// 正则表达式:工具调用审查的全部规则,和各项防护的自定义规则 - Regex { pattern: String }, - /// 不分大小写的子串:内容过滤的关键词规则 - Contains { text: String }, + Regex { + pattern: String, + /// 分大小写:工具调用审查的规则、写明了要分的出站脱敏自定义规则。内容过滤的不分 + #[serde(default, skip_serializing_if = "is_false")] + case_sensitive: bool, + }, + /// 子串,按原样找:内容过滤的关键词规则、出站脱敏的自定义规则 + Contains { + text: String, + /// 分大小写:写明了要分的出站脱敏自定义规则。内容过滤的不分 + #[serde(default, skip_serializing_if = "is_false")] + case_sensitive: bool, + }, /// 这几段码位里的字符,一项一个。内置规则是规范写法(`U+200B`、`U+E0000–U+E007F`), /// 自定义规则是它存着的写法(各项用 `, ` 连起来就是存着的那一份的意思) Codepoints { ranges: Vec }, @@ -271,8 +285,16 @@ pub fn redact(p: &RedactPolicy) -> GuardDetail { name: c.name.clone(), why: String::new(), kind: "custom".into(), - matcher: Matcher::Regex { - pattern: c.pattern.clone(), + matcher: match c.matching { + ContentMatch::Regex => Matcher::Regex { + pattern: c.pattern.clone(), + case_sensitive: c.case_sensitive, + }, + // 码位过不了校验,到不了这里;万一到了,照它写的样子当文字给 + _ => Matcher::Contains { + text: c.pattern.clone(), + case_sensitive: c.case_sensitive, + }, }, enabled: !c.disabled, on_by_default: true, @@ -304,6 +326,7 @@ pub fn inspect_tools(p: &ToolPolicy) -> GuardDetail { }, None => Matcher::Regex { pattern: r.pattern.clone(), + case_sensitive: true, }, }, enabled: !p.disable.contains(&r.id), @@ -321,6 +344,7 @@ pub fn inspect_tools(p: &ToolPolicy) -> GuardDetail { kind: "custom".into(), matcher: Matcher::Regex { pattern: c.pattern.clone(), + case_sensitive: true, }, enabled: !c.disabled, on_by_default: true, @@ -340,9 +364,11 @@ fn content_matcher(matching: content::Match, pattern: &str, custom: bool) -> Mat match matching { content::Match::Contains => Matcher::Contains { text: pattern.to_string(), + case_sensitive: false, }, content::Match::Regex => Matcher::Regex { pattern: pattern.to_string(), + case_sensitive: false, }, content::Match::Codepoints => Matcher::Codepoints { ranges: match Codepoints::parse(pattern) { @@ -462,12 +488,16 @@ mod tests { CustomRedactRule { name: "项目号".into(), pattern: r"PRJ-\d{6}".into(), + matching: ContentMatch::Regex, + case_sensitive: true, label: Some("PROJECT".into()), disabled: false, }, CustomRedactRule { name: "不写标签".into(), pattern: "x".into(), + matching: ContentMatch::Contains, + case_sensitive: false, label: None, disabled: true, }, @@ -601,7 +631,8 @@ mod tests { .unwrap() .matcher, Matcher::Contains { - text: "jailbreak".into() + text: "jailbreak".into(), + case_sensitive: false, } ); let mine = v.rules.last().unwrap(); @@ -630,12 +661,16 @@ mod tests { CustomRedactRule { name: "项目号".into(), pattern: r"PRJ-\d{6}".into(), + matching: ContentMatch::Regex, + case_sensitive: true, label: Some("PROJECT".into()), disabled: false, }, CustomRedactRule { name: "不写标签".into(), pattern: "x".into(), + matching: ContentMatch::Contains, + case_sensitive: false, label: None, disabled: true, }, @@ -720,8 +755,8 @@ mod tests { .collect() } let pattern = |m: &Matcher| match m { - Matcher::Regex { pattern } => (pattern.clone(), ContentMatch::Regex), - Matcher::Contains { text } => (text.clone(), ContentMatch::Contains), + Matcher::Regex { pattern, .. } => (pattern.clone(), ContentMatch::Regex), + Matcher::Contains { text, .. } => (text.clone(), ContentMatch::Contains), Matcher::Codepoints { ranges } => (ranges.join(", "), ContentMatch::Codepoints), other => panic!("自定义规则不会是 {other:?}"), }; @@ -739,6 +774,17 @@ mod tests { .map(|r| CustomRedactRule { name: r.id.clone(), pattern: pattern(&r.matcher).0, + matching: pattern(&r.matcher).1, + case_sensitive: matches!( + r.matcher, + Matcher::Regex { + case_sensitive: true, + .. + } | Matcher::Contains { + case_sensitive: true, + .. + } + ), label: r.label.clone(), disabled: !r.enabled, }) diff --git a/crates/tw-store/src/recorder.rs b/crates/tw-store/src/recorder.rs index 2c46e62f..8174a893 100644 --- a/crates/tw-store/src/recorder.rs +++ b/crates/tw-store/src/recorder.rs @@ -2208,6 +2208,7 @@ mod security_detail_tests { name: "公司令牌".into(), pattern: Some(pattern.into()), matching: None, + case_sensitive: false, core_version: "0.67.1".into(), }, outcome_detail: outcome, diff --git a/docs/config.md b/docs/config.md index 4320ddf0..a824eb64 100644 --- a/docs/config.md +++ b/docs/config.md @@ -759,7 +759,8 @@ Before a request leaves, the whole request (system prompt, earlier answers and tool calls included) is searched for credentials and personal information. Under `enforce` what is found is replaced with placeholders, and put back where the answer repeats them. Images, files and other base64 -payloads are not searched. +payloads are not searched, nor are field names and identifiers such as ids, +types, roles, tool names and model names. @@ -769,7 +770,7 @@ payloads are not searched. | `mode` | `off` \| `observe` \| `enforce` | `observe` | `off` does nothing; `observe` detects and records only, and changes nothing; `enforce` detects and acts. | | `enable` | list of strings | `[]` | Built-in rules to switch on that are off out of the box, by id. | | `disable` | list of strings | `[]` | Built-in rules to switch off, by id. | -| `custom` | list of [`security.redact.custom[]`](#cfg-security-redact-custom) | `[]` | Rules of your own: whatever a pattern matches is replaced like a credential. | +| `custom` | list of [`security.redact.custom[]`](#cfg-security-redact-custom) | `[]` | Rules of your own: whatever a rule matches is replaced like a credential. | @@ -778,8 +779,10 @@ payloads are not searched. | Field | Type | Default | Description | |---|---|---|---| | `name` | string | **required** | Name shown in logs and in the app; it identifies the rule and has to be unique within this guard. | -| `pattern` | string | **required** | Regular expression. | -| `label` | string | `SECRET` | Placeholder name: what the pattern matches is replaced with `<>`, numbered per name. Capital letters, digits and underscores, starting with a letter, at most 24 characters. | +| `pattern` | string | **required** | The text to look for; a regular expression with `match: regex`. | +| `match` | `contains` \| `regex` | `contains` | `contains`: `pattern` is looked for as written; characters such as `.` and `*` have no special meaning. `regex`: `pattern` is a regular expression. | +| `case_sensitive` | bool | `false` | Tell capital letters from small ones. Off by default: `ABC` and `abc` both match. | +| `label` | string | `SECRET` | Placeholder name: what the rule matches is replaced with `<>`, numbered per name. Capital letters, digits and underscores, starting with a letter, at most 24 characters. | | `disabled` | bool | `false` | Switches the rule off and keeps it in the file. | diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index 4934f04e..a8c23706 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -561,7 +561,7 @@ pricing: #### `security.redact` -请求发出前,在整个请求中(包括系统提示、之前的回答和工具调用)查找凭据和个人信息。`enforce` 下将其替换为占位符,回答中重复出现时再换回原值。图片、文件等 base64 内容不查。 +请求发出前,在整个请求中(包括系统提示、之前的回答和工具调用)查找凭据和个人信息。`enforce` 下将其替换为占位符,回答中重复出现时再换回原值。图片、文件等 base64 内容不查;字段名,以及 id、类型、角色、工具名、模型名等标识也不查。 @@ -571,7 +571,7 @@ pricing: | `mode` | `off` \| `observe` \| `enforce` | `observe` | `off` 不检测;`observe` 检测并记录,不改变任何行为;`enforce` 检测并处置。 | | `enable` | 字符串列表 | `[]` | 打开出厂时关着的内置规则,按 id。 | | `disable` | 字符串列表 | `[]` | 关掉内置规则,按 id。 | -| `custom` | 对象列表,见 [`security.redact.custom[]`](#cfg-security-redact-custom) | `[]` | 自定义规则:正则匹配到的内容和凭据一样替换。 | +| `custom` | 对象列表,见 [`security.redact.custom[]`](#cfg-security-redact-custom) | `[]` | 自定义规则:匹配到的内容和凭据一样替换。 | @@ -580,8 +580,10 @@ pricing: | 字段 | 类型 | 默认值 | 说明 | |---|---|---|---| | `name` | 字符串 | **必填** | 日志和应用里显示的名字,也是规则的标识;同一项防护里不能重名。 | -| `pattern` | 字符串 | **必填** | 正则表达式。 | -| `label` | 字符串 | `SECRET` | 占位符名称:正则匹配到的内容替换为 `<>`,每个名称各自编号。只能使用大写字母、数字和下划线,以字母开头,最多 24 个字符。 | +| `pattern` | 字符串 | **必填** | 要查找的文字;`match: regex` 时为正则表达式。 | +| `match` | `contains` \| `regex` | `contains` | `contains`:按原样查找 `pattern`,`.`、`*` 等字符没有特殊含义。`regex`:`pattern` 是正则表达式。 | +| `case_sensitive` | 布尔 | `false` | 区分大小写。默认不区分:`ABC` 和 `abc` 都会匹配。 | +| `label` | 字符串 | `SECRET` | 占位符名称:匹配到的内容替换为 `<>`,每个名称各自编号。只能使用大写字母、数字和下划线,以字母开头,最多 24 个字符。 | | `disabled` | 布尔 | `false` | 停用这条规则,规则本身留在文件里。 | From fdc059a21fd3705c4207a2c94bdfe5b6a815e752 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 12 Oct 2026 12:56:06 +0800 Subject: [PATCH 2/3] v0.71.0 Custom redaction rules match text as written or by regex, with an optional case switch; protocol 47. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 38 +++++++++++++++++++------------------- Cargo.toml | 2 +- release-notes/0.71.0.md | 18 ++++++++++++++++++ 3 files changed, 38 insertions(+), 20 deletions(-) create mode 100644 release-notes/0.71.0.md diff --git a/Cargo.lock b/Cargo.lock index db5f7397..99bb9d0c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3143,7 +3143,7 @@ dependencies = [ [[package]] name = "tw-api" -version = "0.70.1" +version = "0.71.0" dependencies = [ "serde", "serde_json", @@ -3154,7 +3154,7 @@ dependencies = [ [[package]] name = "tw-bedrock" -version = "0.70.1" +version = "0.71.0" dependencies = [ "aws-credential-types", "aws-sigv4", @@ -3175,7 +3175,7 @@ dependencies = [ [[package]] name = "tw-breaker" -version = "0.70.1" +version = "0.71.0" dependencies = [ "serde", "serde_json", @@ -3183,7 +3183,7 @@ dependencies = [ [[package]] name = "tw-config" -version = "0.70.1" +version = "0.71.0" dependencies = [ "blake3", "libc", @@ -3208,7 +3208,7 @@ dependencies = [ [[package]] name = "tw-control" -version = "0.70.1" +version = "0.71.0" dependencies = [ "axum", "base64", @@ -3251,7 +3251,7 @@ dependencies = [ [[package]] name = "tw-dialect" -version = "0.70.1" +version = "0.71.0" dependencies = [ "memchr", "serde", @@ -3260,7 +3260,7 @@ dependencies = [ [[package]] name = "tw-engine" -version = "0.70.1" +version = "0.71.0" dependencies = [ "chrono", "serde", @@ -3274,7 +3274,7 @@ dependencies = [ [[package]] name = "tw-gateway" -version = "0.70.1" +version = "0.71.0" dependencies = [ "arc-swap", "async-stream", @@ -3325,7 +3325,7 @@ dependencies = [ [[package]] name = "tw-guard" -version = "0.70.1" +version = "0.71.0" dependencies = [ "base64", "bytes", @@ -3341,7 +3341,7 @@ dependencies = [ [[package]] name = "tw-link" -version = "0.70.1" +version = "0.71.0" dependencies = [ "serde", "serde_json", @@ -3355,7 +3355,7 @@ dependencies = [ [[package]] name = "tw-observe" -version = "0.70.1" +version = "0.71.0" dependencies = [ "tokio", "tracing", @@ -3364,7 +3364,7 @@ dependencies = [ [[package]] name = "tw-plugin" -version = "0.70.1" +version = "0.71.0" dependencies = [ "libc", "rand 0.10.2", @@ -3379,7 +3379,7 @@ dependencies = [ [[package]] name = "tw-pricing" -version = "0.70.1" +version = "0.71.0" dependencies = [ "arc-swap", "flate2", @@ -3392,14 +3392,14 @@ dependencies = [ [[package]] name = "tw-secret" -version = "0.70.1" +version = "0.71.0" dependencies = [ "thiserror", ] [[package]] name = "tw-store" -version = "0.70.1" +version = "0.71.0" dependencies = [ "blake3", "bytes", @@ -3419,7 +3419,7 @@ dependencies = [ [[package]] name = "tw-types" -version = "0.70.1" +version = "0.71.0" dependencies = [ "serde", "serde_json", @@ -3428,7 +3428,7 @@ dependencies = [ [[package]] name = "tw-watch" -version = "0.70.1" +version = "0.71.0" dependencies = [ "libc", "notify", @@ -3439,7 +3439,7 @@ dependencies = [ [[package]] name = "tw-yaml" -version = "0.70.1" +version = "0.71.0" dependencies = [ "saphyr-parser", "serde_yaml_ng", @@ -3449,7 +3449,7 @@ dependencies = [ [[package]] name = "twcore" -version = "0.70.1" +version = "0.71.0" dependencies = [ "anyhow", "axum", diff --git a/Cargo.toml b/Cargo.toml index a657f92a..ac565cb6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -54,7 +54,7 @@ categories = ["network-programming", "web-programming::http-server"] # 二进制走 CalVer,crate 走 SemVer —— 两者是两回事,卖给不同的人。 # 这里是 crate 的版本。 -version = "0.70.1" +version = "0.71.0" [workspace.dependencies] # ── 内部 crate ─────────────────────────────────────────── diff --git a/release-notes/0.71.0.md b/release-notes/0.71.0.md new file mode 100644 index 00000000..355d1126 --- /dev/null +++ b/release-notes/0.71.0.md @@ -0,0 +1,18 @@ +This release keeps outbound redaction away from the structure of a request, so a rule can no longer break the ids a client sends back, and lets a custom redaction rule look for its text as written or by a regular expression, with or without telling capital letters from small ones. + +**Upgrade notes** + +- The control-plane protocol version (`CONTROL_API_VERSION`) goes from 46 to 47. ThinkWatch Lite connects only to a core with the same protocol version: ThinkWatch Lite 2026.10.16 includes 0.70.1 (protocol 46) and does not connect to 0.71.0. A server used with it stays on 0.70.1 until the app is updated to a release that includes 0.71.0; `sudo twcore upgrade --version 0.70.1 --restart` switches a server back. +- The request store's schema is unchanged; nothing is cleared. +- Configuration: a custom redaction rule takes two new optional keys, `match` (`contains` or `regex`) and `case_sensitive`. **A custom redaction rule without `match` is now looked for as written and ignores case**; before, every custom redaction rule was a case-sensitive regular expression. A rule written as a regular expression needs `match: regex`, and `case_sensitive: true` to keep telling cases apart. Existing configurations load unchanged. +- New message codes: `config.rule_match_bad`, `security.redact_match_bad`. +- Changed in the protocol: + - `CustomRuleSave` and `SecurityTestRequest`: `match` applies to redaction rules too (`contains` or `regex`; `contains` when not given); new `case_sensitive` (off when not given). + - `Matcher`: `contains` and `regex` gain `case_sensitive`. A custom redaction rule is shown as `contains` or `regex`; tool-call rules, which are regular expressions that tell cases apart, report `true`. + - `RuleSnapshot` gains `case_sensitive`; a custom redaction rule's snapshot now carries `matching`. + +**Redaction leaves the request's structure alone.** Rules were run over the whole request body, field names and identifiers included, so a custom rule matched inside the ids a client sends with its history: Codex sends ids such as `fco_` followed by a hexadecimal UUID, and a rule whose text could be spelled in hexadecimal turned one into `fco_…<>…`. The upstream rejected the request because the id contained characters an id cannot have, and since the history is sent again on every turn, every later turn of that conversation was rejected too. Rules now skip field names and the values of identifiers: `id` and any field ending in `_id` or `Id`, `type`, `role`, `name`, `namespace`, `model`, `status`, `object` and `phase`. What the client and the model wrote, tool arguments and tool results included, is searched as before. + +**Private keys stay within one text.** The private-key rule looked for the end of a key block anywhere after its first line. A header without an end in one message, such as a file read halfway or code that spells the marker, joined up with an end line in a later message, and everything in between, earlier turns included, was replaced by a single placeholder. The header and the end are now looked for within the same text. + +**Match by.** A custom redaction rule now says how it matches, as content rules already do: `contains` looks for the text exactly as written, so `.`, `*` and the like have no special meaning, and `regex` takes a regular expression. A rule matches regardless of case unless it sets `case_sensitive: true`. Code points remain a content-filter matcher only and are refused for redaction. The security log records how a custom redaction rule matched and whether it told cases apart when it found something. From bdd4f55482d643932d3aaccf3e3ce37a13ab7852 Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Mon, 12 Oct 2026 13:18:55 +0800 Subject: [PATCH 3/3] fix(redact): custom rules skip protocol identifiers only; built-in rules search them Pre-release review found the identifier skip list too broad: every rule, built-in ones included, skipped any `*_id` / `*Id` value, so a key under `aws_access_key_id` or a phone number under `user_id` in tool arguments was no longer replaced. Keys stay off-limits for every rule; the values of the protocol's own identifier keys (an explicit list, no suffix guessing) are skipped by custom rules only. Tool-call regexes that start with `(?i)` now report `case_sensitive: false`. Co-Authored-By: Claude Opus 5.5 --- crates/tw-api/src/lib.rs | 5 +- crates/tw-guard/src/redact/flow.rs | 93 +++++++++++++++++++++++------- crates/tw-guard/src/view.rs | 40 ++++++++++++- docs/config.md | 3 +- docs/config.zh-CN.md | 2 +- release-notes/0.71.0.md | 6 +- 6 files changed, 117 insertions(+), 32 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 5c0014fc..8430fe70 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -905,12 +905,13 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt"); /// [`SecurityTestRequest`] 的 `match` 出站脱敏也认(`contains` 按原样找这段文字、`regex`; /// 不给是 `contains`,**以前是正则**),多了 `case_sensitive`(不给是不分)。规则视图里 /// 出站脱敏的自定义规则是 [`Matcher`] 的 `contains` 或 `regex`,两者都多了 -/// `case_sensitive`(工具调用审查的正则是 `true`)。安全日志的 [`RuleSnapshot`] 多了 +/// `case_sensitive`(工具调用审查的正则开头写了 `(?i)` 的是 `false`,别的是 `true`)。安全日志的 [`RuleSnapshot`] 多了 /// `case_sensitive`,出站脱敏的自定义规则也带 `matching`。码位交给出站脱敏是 400 /// (`security.redact_match_bad`),配置里写了是 `config.rule_match_bad`。配置里不写 /// `match` 的老规则从此按原样找。 /// -/// 出站脱敏不再碰请求体的结构:键,和 id、类型、角色、工具名、模型名这些值。 +/// 出站脱敏不再碰请求体的键;自定义规则也不碰协议里的 id、类型、角色、工具名、模型名这些值 +/// (内置规则照找)。 pub const CONTROL_API_VERSION: u32 = 47; #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/tw-guard/src/redact/flow.rs b/crates/tw-guard/src/redact/flow.rs index 538f1b66..64641d32 100644 --- a/crates/tw-guard/src/redact/flow.rs +++ b/crates/tw-guard/src/redact/flow.rs @@ -10,7 +10,8 @@ //! - **base64 载荷**(图片、文件、推理签名、`data:` URI):一段编码过的图片里碰巧 //! 有一截像密钥的字母,换掉它换坏的是那张图,报出来的是一条没人看得懂的误报; //! - **我们自己的占位符**(见 [`hits`]); -//! - **请求体的结构**:键,和 id、类型、角色、工具名这些标识(见 [`untouched`])。 +//! - **请求体的结构**:键;自定义规则也不找协议里的 id、类型、角色、工具名、模型名 +//! (见 [`untouched`])。 //! //! # 观察档和替换档用同一套规则 //! @@ -44,7 +45,16 @@ pub fn hits(text: &str, rules: &RuleSet) -> Vec { off_placeholders(text, &mut hits); // 大多数请求一处都不命中:载荷在哪儿等有了命中再找 if !hits.is_empty() { - outside(&mut hits, untouched(text)); + let (everyone, custom) = untouched(text); + outside(&mut hits, everyone); + if hits.iter().any(|h| h.rule.custom()) && !custom.is_empty() { + let (mut mine, builtin): (Vec, Vec) = + hits.into_iter().partition(|h| h.rule.custom()); + outside(&mut mine, custom); + hits = builtin; + hits.extend(mine); + hits.sort_by_key(|h| h.bytes.start); + } } hits } @@ -217,21 +227,25 @@ const CARRIERS: &[&str] = &[ /// 图片、签名动辄上千 const PAYLOAD_MIN: usize = 256; -/// 不换的地方:base64 载荷(见 [`payload`]),和**请求体的结构** —— 每一个键、 -/// 标识一样东西的值([`structural`])。 +/// 不换的地方,两份:**哪条规则都不换的** —— base64 载荷(见 [`payload`])和每一个键; +/// **自定义规则不换的** —— 协议里标识一样东西的值([`structural`])。 +/// +/// 一个自定义规则 `abc123` 按子串找,会找进 Codex 的条目 id(`fco_019f…`,十六进制的 +/// UUID)里去:换成占位符之后上游以「id 里有别的字符」拒绝整个请求,而历史每一轮都整段 +/// 重发,这段对话从此每一轮都被拒。类型、工具名换掉同理。 /// -/// 规则找的是用户写的话。一个自定义规则 `abc123` 按子串找,会找进 Codex 的条目 id -/// (`fco_019f…`,十六进制的 UUID)里去:换成占位符之后上游以「id 里有别的字符」拒绝整个 -/// 请求,而历史每一轮都整段重发,这段对话从此每一轮都被拒。键、类型、工具名换掉同理。 -fn untouched(text: &str) -> Vec> { - let mut out = Vec::new(); +/// **内置规则照找这些值**:它们认的是有前缀、有格式的东西(`AKIA…`、号码),不会长在一个 +/// 十六进制的 id 里;而工具参数这种对象里,凭据和号码常常就写在 `aws_access_key_id`、 +/// `user_id` 这样的键下面。 +fn untouched(text: &str) -> (Vec>, Vec>) { + let (mut everyone, mut custom) = (Vec::new(), Vec::new()); json_strings(text, |s, key, is_key| match key { - _ if is_key => out.push(s), - Some(k) if structural(k) => out.push(s), - _ if payload(&text[s.clone()], key) => out.push(s), + _ if is_key => everyone.push(s), + _ if payload(&text[s.clone()], key) => everyone.push(s), + Some(k) if structural(k) => custom.push(s), _ => {} }); - out + (everyone, custom) } /// 一个值是不是 base64 载荷:[`CARRIERS`] 下面、长得像 base64 的,和任何地方的 @@ -240,16 +254,28 @@ fn payload(value: &str, key: Option<&str>) -> bool { data_uri(value) || (key.is_some_and(|k| CARRIERS.contains(&k)) && looks_base64(value)) } -/// 值是一个标识、不是一段话的那些键:各家的 id(`id`、`call_id`、`tool_use_id`、`toolUseId`、 -/// `previous_response_id`……)、条目和内容块的类型、角色、工具名、模型名。 +/// 各家协议里值是一个标识、不是一段话的那些键:条目和调用的 id、类型、角色、工具名、 +/// 模型名。**只认协议自己的键**,不按 `_id` 结尾去猜:工具参数里的 `user_id`、`order_id` +/// 是用户的数据。 fn structural(key: &str) -> bool { - key == "id" - || key.ends_with("_id") - || key.ends_with("Id") - || matches!( - key, - "type" | "role" | "name" | "namespace" | "model" | "status" | "object" | "phase" - ) + matches!( + key, + "id" | "call_id" + | "item_id" + | "tool_use_id" + | "tool_call_id" + | "toolUseId" + | "previous_response_id" + | "response_id" + | "type" + | "role" + | "name" + | "namespace" + | "model" + | "status" + | "object" + | "phase" + ) } /// `end` 是一个字符串的结尾(引号之前):它后面(跳过空白)是冒号的话,这个字符串是一个键 @@ -631,6 +657,29 @@ mod tests { assert_eq!(v["toolUse"]["toolUseId"], "abc123"); } + /// 工具参数这种对象里,凭据和号码就写在 `aws_access_key_id`、`user_id` 下面:内置规则 + /// 照找;自定义规则也照找不属于协议的 `*_id` + #[test] + fn credentials_under_id_like_keys_of_user_data_are_still_found() { + let rules = RuleSet::defaults().with_custom("工号", "E-\\d{6}").unwrap(); + let key = "AKIAABCDEFGHIJKLMNOP"; + let body = serde_json::json!({ + "messages": [{"role": "assistant", "content": [ + {"type": "tool_use", "id": "toolu_1", "name": "deploy", + "input": {"aws_access_key_id": key, "employee_id": "E-123456"}}, + ]}], + "metadata": {"user_id": key}, + }) + .to_string(); + let (out, _) = replace(Mode::Enforce, &rules, body.into(), &fresh()); + let v: serde_json::Value = serde_json::from_slice(&out).unwrap(); + let input = &v["messages"][0]["content"][0]["input"]; + assert_eq!(input["aws_access_key_id"], "<>"); + assert_eq!(input["employee_id"], "<>"); + assert_eq!(v["metadata"]["user_id"], "<>"); + assert_eq!(v["messages"][0]["content"][0]["id"], "toolu_1"); + } + #[test] fn a_short_value_under_a_payload_key_is_still_looked_at() { // 一把密钥写在 `data` 下面,照样要找:载荷是很长的那种 diff --git a/crates/tw-guard/src/view.rs b/crates/tw-guard/src/view.rs index a57641ce..a645bd96 100644 --- a/crates/tw-guard/src/view.rs +++ b/crates/tw-guard/src/view.rs @@ -116,7 +116,8 @@ pub enum Matcher { /// 正则表达式:工具调用审查的全部规则,和各项防护的自定义规则 Regex { pattern: String, - /// 分大小写:工具调用审查的规则、写明了要分的出站脱敏自定义规则。内容过滤的不分 + /// 分大小写:工具调用审查的规则(开头写了 `(?i)` 的除外)、写明了要分的出站脱敏 + /// 自定义规则。内容过滤的不分 #[serde(default, skip_serializing_if = "is_false")] case_sensitive: bool, }, @@ -326,7 +327,7 @@ pub fn inspect_tools(p: &ToolPolicy) -> GuardDetail { }, None => Matcher::Regex { pattern: r.pattern.clone(), - case_sensitive: true, + case_sensitive: !ignores_case(&r.pattern), }, }, enabled: !p.disable.contains(&r.id), @@ -344,7 +345,7 @@ pub fn inspect_tools(p: &ToolPolicy) -> GuardDetail { kind: "custom".into(), matcher: Matcher::Regex { pattern: c.pattern.clone(), - case_sensitive: true, + case_sensitive: !ignores_case(&c.pattern), }, enabled: !c.disabled, on_by_default: true, @@ -358,6 +359,18 @@ pub fn inspect_tools(p: &ToolPolicy) -> GuardDetail { } } +/// 工具调用审查的正则整条不分大小写:开头写着 `(?i)` 这样的标志 +fn ignores_case(pattern: &str) -> bool { + pattern + .strip_prefix("(?") + .and_then(|rest| rest.split_once([')', ':'])) + .is_some_and(|(flags, _)| { + // `-` 之后的是关掉的 + flags.chars().all(|c| "imsuxU-".contains(c)) + && flags.split('-').next().is_some_and(|on| on.contains('i')) + }) +} + /// 内容规则按什么认。码位:内置规则写成规范写法,自定义规则照它写的样子一项一项给 /// (界面拼回去存的就是这一份);写坏了的(绕过校验写进去的)整段原样给 fn content_matcher(matching: content::Match, pattern: &str, custom: bool) -> Matcher { @@ -511,6 +524,27 @@ mod tests { assert!(!r("不写标签").enabled && r("不写标签").custom); } + #[test] + fn a_regex_says_whether_it_tells_cases_apart() { + assert!(ignores_case(r"(?i)curl\s")); + assert!(ignores_case(r"(?im)x")); + assert!(ignores_case(r"(?i:rm)\s")); + assert!(!ignores_case(r"curl(?i)x")); + assert!(!ignores_case(r"(?-i)x")); + assert!(!ignores_case(r"(?m-i)x")); + assert!(!ignores_case(r"(?Pi)")); + let v = inspect_tools(&ToolPolicy::default()); + for r in &v.rules { + if let Matcher::Regex { + pattern, + case_sensitive, + } = &r.matcher + { + assert_eq!(*case_sensitive, !pattern.starts_with("(?i)"), "{pattern}"); + } + } + } + #[test] fn tool_rules_say_what_they_do_in_the_third_mode() { let v = inspect_tools(&ToolPolicy { diff --git a/docs/config.md b/docs/config.md index a824eb64..ff229257 100644 --- a/docs/config.md +++ b/docs/config.md @@ -759,7 +759,8 @@ Before a request leaves, the whole request (system prompt, earlier answers and tool calls included) is searched for credentials and personal information. Under `enforce` what is found is replaced with placeholders, and put back where the answer repeats them. Images, files and other base64 -payloads are not searched, nor are field names and identifiers such as ids, +payloads are not searched, nor are field names; custom rules also leave alone +the identifiers a protocol needs as they are, such as item and call ids, types, roles, tool names and model names. diff --git a/docs/config.zh-CN.md b/docs/config.zh-CN.md index a8c23706..4021405b 100644 --- a/docs/config.zh-CN.md +++ b/docs/config.zh-CN.md @@ -561,7 +561,7 @@ pricing: #### `security.redact` -请求发出前,在整个请求中(包括系统提示、之前的回答和工具调用)查找凭据和个人信息。`enforce` 下将其替换为占位符,回答中重复出现时再换回原值。图片、文件等 base64 内容不查;字段名,以及 id、类型、角色、工具名、模型名等标识也不查。 +请求发出前,在整个请求中(包括系统提示、之前的回答和工具调用)查找凭据和个人信息。`enforce` 下将其替换为占位符,回答中重复出现时再换回原值。图片、文件等 base64 内容不查,字段名也不查;自定义规则还不查协议要求原样保留的标识,如条目和调用的 id、类型、角色、工具名、模型名。 diff --git a/release-notes/0.71.0.md b/release-notes/0.71.0.md index 355d1126..a20dc0ea 100644 --- a/release-notes/0.71.0.md +++ b/release-notes/0.71.0.md @@ -4,14 +4,14 @@ This release keeps outbound redaction away from the structure of a request, so a - The control-plane protocol version (`CONTROL_API_VERSION`) goes from 46 to 47. ThinkWatch Lite connects only to a core with the same protocol version: ThinkWatch Lite 2026.10.16 includes 0.70.1 (protocol 46) and does not connect to 0.71.0. A server used with it stays on 0.70.1 until the app is updated to a release that includes 0.71.0; `sudo twcore upgrade --version 0.70.1 --restart` switches a server back. - The request store's schema is unchanged; nothing is cleared. -- Configuration: a custom redaction rule takes two new optional keys, `match` (`contains` or `regex`) and `case_sensitive`. **A custom redaction rule without `match` is now looked for as written and ignores case**; before, every custom redaction rule was a case-sensitive regular expression. A rule written as a regular expression needs `match: regex`, and `case_sensitive: true` to keep telling cases apart. Existing configurations load unchanged. +- Configuration: a custom redaction rule takes two new optional keys, `match` (`contains` or `regex`) and `case_sensitive`. **A custom redaction rule without `match` is now looked for as written and ignores case**; before, every custom redaction rule was a case-sensitive regular expression. Such a rule still loads and is not reported anywhere; it simply stops matching, and what it used to replace is sent as it is. Check every custom redaction rule before upgrading: one written as a regular expression needs `match: regex`, and `case_sensitive: true` to keep telling cases apart. Existing configurations load unchanged; a configuration that uses `match` or `case_sensitive` on a redaction rule does not load in 0.70.x. - New message codes: `config.rule_match_bad`, `security.redact_match_bad`. - Changed in the protocol: - `CustomRuleSave` and `SecurityTestRequest`: `match` applies to redaction rules too (`contains` or `regex`; `contains` when not given); new `case_sensitive` (off when not given). - - `Matcher`: `contains` and `regex` gain `case_sensitive`. A custom redaction rule is shown as `contains` or `regex`; tool-call rules, which are regular expressions that tell cases apart, report `true`. + - `Matcher`: `contains` and `regex` gain `case_sensitive`. A custom redaction rule is shown as `contains` or `regex`; a tool-call rule reports `true` unless its pattern starts with `(?i)`. - `RuleSnapshot` gains `case_sensitive`; a custom redaction rule's snapshot now carries `matching`. -**Redaction leaves the request's structure alone.** Rules were run over the whole request body, field names and identifiers included, so a custom rule matched inside the ids a client sends with its history: Codex sends ids such as `fco_` followed by a hexadecimal UUID, and a rule whose text could be spelled in hexadecimal turned one into `fco_…<>…`. The upstream rejected the request because the id contained characters an id cannot have, and since the history is sent again on every turn, every later turn of that conversation was rejected too. Rules now skip field names and the values of identifiers: `id` and any field ending in `_id` or `Id`, `type`, `role`, `name`, `namespace`, `model`, `status`, `object` and `phase`. What the client and the model wrote, tool arguments and tool results included, is searched as before. +**Redaction leaves the request's structure alone.** Rules were run over the whole request body, field names and identifiers included, so a custom rule matched inside the ids a client sends with its history: Codex sends ids such as `fco_` followed by a hexadecimal UUID, and a rule whose text could be spelled in hexadecimal turned one into `fco_…<>…`. The upstream rejected the request because the id contained characters an id cannot have, and since the history is sent again on every turn, every later turn of that conversation was rejected too. No rule looks inside field names any more. Custom rules also leave alone the values a protocol needs exactly as they are: `id`, `call_id`, `item_id`, `tool_use_id`, `tool_call_id`, `toolUseId`, `previous_response_id`, `response_id`, `type`, `role`, `name`, `namespace`, `model`, `status`, `object` and `phase`. Built-in rules still search those values, since a key or a number cannot be mistaken for a hexadecimal id, and every other value is searched by every rule as before, including fields such as `user_id` or `aws_access_key_id` inside tool arguments. **Private keys stay within one text.** The private-key rule looked for the end of a key block anywhere after its first line. A header without an end in one message, such as a file read halfway or code that spells the marker, joined up with an end line in a later message, and everything in between, earlier turns included, was replaced by a single placeholder. The header and the end are now looked for within the same text.