diff --git a/Cargo.lock b/Cargo.lock index 21fb388d..09254c83 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1526,16 +1526,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "metrics" -version = "0.24.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2" -dependencies = [ - "portable-atomic", - "rapidhash", -] - [[package]] name = "mime" version = "0.3.17" @@ -1690,12 +1680,6 @@ dependencies = [ "universal-hash", ] -[[package]] -name = "portable-atomic" -version = "1.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" - [[package]] name = "potential_utf" version = "0.1.6" @@ -1871,15 +1855,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "rapidhash" -version = "4.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" -dependencies = [ - "rustversion", -] - [[package]] name = "regex" version = "1.13.1" @@ -2815,8 +2790,8 @@ dependencies = [ "tokio", "tw-api", "tw-engine", + "tw-guard", "tw-pricing", - "tw-redact", "tw-secret", "tw-types", "tw-yaml", @@ -2852,9 +2827,9 @@ dependencies = [ "tw-config", "tw-engine", "tw-gateway", + "tw-guard", "tw-observe", "tw-pricing", - "tw-redact", "tw-scan", "tw-secret", "tw-store", @@ -2930,10 +2905,9 @@ dependencies = [ "tw-config", "tw-dialect", "tw-engine", + "tw-guard", "tw-observe", "tw-pricing", - "tw-redact", - "tw-scan", "tw-secret", "tw-types", "tw-upstream", @@ -2941,6 +2915,20 @@ dependencies = [ "uuid", ] +[[package]] +name = "tw-guard" +version = "0.36.0" +dependencies = [ + "base64", + "regex", + "serde", + "serde_json", + "serde_yaml_ng", + "thiserror", + "tw-dialect", + "tw-secret", +] + [[package]] name = "tw-observe" version = "0.36.0" @@ -2963,30 +2951,6 @@ dependencies = [ "tw-types", ] -[[package]] -name = "tw-redact" -version = "0.36.0" -dependencies = [ - "base64", - "regex", - "serde", - "serde_json", - "thiserror", - "tw-secret", -] - -[[package]] -name = "tw-resil" -version = "0.36.0" -dependencies = [ - "futures", - "metrics", - "rand 0.10.2", - "tokio", - "tracing", - "tw-types", -] - [[package]] name = "tw-scan" version = "0.36.0" @@ -3002,6 +2966,7 @@ dependencies = [ "tracing", "tw-adopt", "tw-config", + "tw-guard", "tw-types", ] @@ -3095,6 +3060,7 @@ dependencies = [ "tw-config", "tw-control", "tw-gateway", + "tw-guard", "tw-observe", "tw-pricing", "tw-scan", diff --git a/Cargo.toml b/Cargo.toml index 2028a836..c30f42c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,6 @@ members = [ "crates/tw-types", "crates/tw-upstream", "crates/tw-wire", - "crates/tw-resil", "crates/tw-crypto", # ── 第二层 · 桌面网关(企业版永不依赖)──────────────── "crates/tw-api", @@ -16,7 +15,7 @@ members = [ "crates/tw-pricing", "crates/tw-adopt", "crates/tw-scan", - "crates/tw-redact", + "crates/tw-guard", "crates/tw-dialect", "crates/tw-engine", "crates/tw-observe", @@ -26,8 +25,6 @@ members = [ "bin/twcore", ] -# 其余 crate 在有内容时再加进来,不预先建空壳: -# tw-redact / tw-pricing / tw-engine / tw-guard / tw-store / tw-observe [workspace.package] edition = "2024" @@ -45,7 +42,6 @@ version = "0.36.0" tw-types = { path = "crates/tw-types" } tw-upstream = { path = "crates/tw-upstream" } tw-wire = { path = "crates/tw-wire" } -tw-resil = { path = "crates/tw-resil" } tw-crypto = { path = "crates/tw-crypto" } tw-api = { path = "crates/tw-api" } tw-secret = { path = "crates/tw-secret" } @@ -59,7 +55,7 @@ tw-store = { path = "crates/tw-store" } tw-pricing = { path = "crates/tw-pricing" } tw-adopt = { path = "crates/tw-adopt" } tw-scan = { path = "crates/tw-scan" } -tw-redact = { path = "crates/tw-redact" } +tw-guard = { path = "crates/tw-guard" } tw-dialect = { path = "crates/tw-dialect" } # ── 版本与企业版 workspace 对齐,便于反向依赖时不打架 ──── diff --git a/README.md b/README.md index 30011b5f..fa40b24b 100644 --- a/README.md +++ b/README.md @@ -43,10 +43,10 @@ Point a client (Claude Code, Codex, and friends) at a local port, and: ## Crate layers ``` -tw-types · tw-dialect · tw-wire · tw-upstream · tw-resil · tw-crypto ← shape fixed by the outside world -tw-engine · tw-pricing · tw-redact · tw-yaml · tw-secret ← domain logic -tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly -tw-gateway · tw-control ← data plane / control plane +tw-types · tw-dialect · tw-wire · tw-upstream · tw-crypto ← shape fixed by the outside world +tw-engine · tw-pricing · tw-guard · tw-yaml · tw-secret ← domain logic +tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← assembly +tw-gateway · tw-control ← data plane / control plane ``` The top two layers are stable against external reality — the server edition diff --git a/README.zh-CN.md b/README.zh-CN.md index fc9302e8..8d96caa6 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -38,10 +38,10 @@ cargo run -p twcore -- serve # 起网关和控制面 ## crate 分层 ``` -tw-types · tw-dialect · tw-wire · tw-upstream · tw-resil · tw-crypto ← 形状由外部现实决定 -tw-engine · tw-pricing · tw-redact · tw-yaml · tw-secret ← 领域逻辑 -tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配 -tw-gateway · tw-control ← 数据面 / 控制面 +tw-types · tw-dialect · tw-wire · tw-upstream · tw-crypto ← 形状由外部现实决定 +tw-engine · tw-pricing · tw-guard · tw-yaml · tw-secret ← 领域逻辑 +tw-config · tw-store · tw-scan · tw-adopt · tw-observe ← 装配 +tw-gateway · tw-control ← 数据面 / 控制面 ``` 上面两层对外部稳定,服务端版本直接依赖它们。下面两层是单机的实现 diff --git a/bin/twcore/Cargo.toml b/bin/twcore/Cargo.toml index 16b92cb7..8d4d5e7d 100644 --- a/bin/twcore/Cargo.toml +++ b/bin/twcore/Cargo.toml @@ -22,6 +22,7 @@ anyhow = { workspace = true } clap = { workspace = true } tw-adopt = { workspace = true } tw-scan = { workspace = true } +tw-guard = { workspace = true } tw-wire = { workspace = true } serde_yaml_ng = { workspace = true } tokio = { workspace = true } diff --git a/bin/twcore/src/main.rs b/bin/twcore/src/main.rs index 7b07b56c..9285b7e5 100644 --- a/bin/twcore/src/main.rs +++ b/bin/twcore/src/main.rs @@ -158,7 +158,7 @@ fn main() -> Result<()> { fn cmd_scan(_config: &Path, projects: Vec, inventory: bool) -> Result<()> { // **只用内置规则**,和应用里 MCP 页扫的是同一套。安全页上的规则只作用于 // 经过网关的请求 - let rules = tw_scan::rules::scan_rules(); + let rules = tw_guard::tools::rules::scan_rules(); let mut srcs = tw_scan::sources::user_level(&home()); for p in &projects { srcs.extend(tw_scan::sources::in_project(p)); @@ -630,7 +630,7 @@ fn cmd_check(path: &Path) -> Result<()> { // **本机的 http 不算明文过网。**报它是个假警报,而 // 假警报的代价是用户学会忽略这一栏的所有话( // 没有风险的时候要说「安全」,不是把话说满)。 - // tw-redact 的内网规则出于同一个理由排除回环。 + // tw-guard 的内网规则出于同一个理由排除回环。 let loopback = o.endpoint.starts_with("http://127.0.0.1") || o.endpoint.starts_with("http://localhost") || o.endpoint.starts_with("http://[::1]"); diff --git a/bin/twcore/tests/copy.rs b/bin/twcore/tests/copy.rs index 58180961..467873a1 100644 --- a/bin/twcore/tests/copy.rs +++ b/bin/twcore/tests/copy.rs @@ -252,14 +252,14 @@ fn product_text_is_written_not_spoken() { } // 内置扫描规则的说明会原样出现在发现和工具调用告警里 - let rules = root.join("crates/tw-config/data/rules.yaml"); + let rules = root.join("crates/tw-guard/data/rules.yaml"); for (n, l) in std::fs::read_to_string(&rules).unwrap().lines().enumerate() { let Some(why) = l.trim().strip_prefix("why:") else { continue; }; for w in SPOKEN.iter().filter(|w| why.contains(**w)) { found.push(format!( - "crates/tw-config/data/rules.yaml:{} 「{w}」 {why}", + "crates/tw-guard/data/rules.yaml:{} 「{w}」 {why}", n + 1 )); } diff --git a/crates/tw-config/Cargo.toml b/crates/tw-config/Cargo.toml index ac6f2509..27fdbd30 100644 --- a/crates/tw-config/Cargo.toml +++ b/crates/tw-config/Cargo.toml @@ -14,7 +14,7 @@ tw-types = { workspace = true } tw-api = { workspace = true } tw-secret = { workspace = true } # 校验要认得出配置里写到的内置脱敏规则 id -tw-redact = { workspace = true } +tw-guard = { workspace = true } regex = { workspace = true } tw-pricing = { workspace = true } # 凭据轮换要把一个标量写回 config.yaml。**span 补丁,不是 diff --git a/crates/tw-config/src/lib.rs b/crates/tw-config/src/lib.rs index 9701cfa9..19b03772 100644 --- a/crates/tw-config/src/lib.rs +++ b/crates/tw-config/src/lib.rs @@ -954,8 +954,8 @@ pub fn write(path: &Path, cfg: &Config) -> Result<(), WriteError> { pub use probes::{ClientProbes, ProbeAction}; pub use reload::{Rejected, Stage, try_parse}; pub use security::{ - BUILTIN_RULES, CustomRedactRule, CustomToolRule, Mode as SecurityMode, RedactPolicy, Security, - ToolAction, ToolPolicy, + CustomRedactRule, CustomToolRule, Mode as SecurityMode, RedactPolicy, Security, ToolAction, + ToolPolicy, }; // Billing 在本文件里定义,这里不必再导出 pub use store::{Fingerprint, Loaded, StoreError, version_of}; diff --git a/crates/tw-config/src/security.rs b/crates/tw-config/src/security.rs index e8d19788..b0c8909b 100644 --- a/crates/tw-config/src/security.rs +++ b/crates/tw-config/src/security.rs @@ -32,7 +32,6 @@ //! 不是数据,而且住在这里白捡了变更历史和一键回滚。 use std::collections::BTreeMap; -use std::sync::OnceLock; use serde::{Deserialize, Serialize}; @@ -188,33 +187,61 @@ impl RedactPolicy { } } -/// 内置规则的清单,编译进二进制。 +/// 工具调用审查的内置规则 id:tw-guard 内置规则里「危险命令」那一组。 /// -/// **放在这里而不是 tw-scan**:`config.yaml` 按 id 引用其中「危险命令」那一组 -/// (`security.inspect_tools` 的 `enable` / `disable` / `actions`),校验要认得出 -/// 这些 id,而 tw-scan 依赖本 crate、反过来引用不了。规则怎么编译、怎么匹配 -/// 仍然是 tw-scan 的事。 -pub const BUILTIN_RULES: &str = include_str!("../data/rules.yaml"); - -/// 工具调用审查的内置规则 id:[`BUILTIN_RULES`] 里「危险命令」那一组。 -fn tool_rule_ids() -> &'static [String] { - #[derive(Deserialize)] - struct File { - dangerous: Vec, +/// `config.yaml` 按 id 引用它们(`security.inspect_tools` 的 `enable` / +/// `disable` / `actions`),校验要认得出。 +fn tool_rule_ids() -> impl Iterator { + tw_guard::tools::rules::builtin() + .dangerous + .iter() + .map(|s| s.id.as_str()) +} + +impl ToolAction { + /// 一条内置规则出厂时在拦截档下做什么。 + pub fn factory(spec: &tw_guard::tools::rules::RuleSpec) -> Self { + if spec.high() { + ToolAction::Cut + } else { + ToolAction::Record + } } - #[derive(Deserialize)] - struct Spec { - id: String, +} + +impl ToolPolicy { + /// 这一份配置下的工具调用审查规则:内置的去掉停用的、按改过的处置走, + /// 再加上启用着的自定义规则。 + /// + /// 自定义规则的正则在配置校验时已经编过一次;这里再编失败只可能是有人绕过 + /// 了校验,照样当错误返回,不静默跳过。 + pub fn rules( + &self, + ) -> Result { + tw_guard::tools::rules::tool_rules( + &self.disable, + |id| self.cut(id), + self.custom + .iter() + .filter(|c| !c.disabled) + .map(|c| tw_guard::tools::rules::Custom { + name: &c.name, + pattern: &c.pattern, + cut: c.action == ToolAction::Cut, + }), + ) + } + + /// 只有一条内置规则,**不管它启用没有**,处置按这份配置走。安全页上 + /// 「试一条停用着的规则」用它。 + pub fn one_builtin(&self, id: &str) -> Option { + tw_guard::tools::rules::one_builtin(id, self.cut(id)) + } + + /// 用户改过这条内置规则的处置的话,改成了什么。 + fn cut(&self, id: &str) -> Option { + self.actions.get(id).map(|a| *a == ToolAction::Cut) } - static IDS: OnceLock> = OnceLock::new(); - IDS.get_or_init(|| { - serde_yaml_ng::from_str::(BUILTIN_RULES) - .expect("the built-in rules file parses, and a test keeps it so") - .dangerous - .into_iter() - .map(|s| s.id) - .collect() - }) } /// 两项防护。 @@ -238,14 +265,14 @@ impl Security { r.enable .iter() .chain(&r.disable) - .find(|id| tw_redact::rules::builtin(id).is_none()) + .find(|id| tw_guard::redact::rules::builtin(id).is_none()) .map(|id| ("redact", id.as_str())) .or_else(|| { t.enable .iter() .chain(&t.disable) .chain(t.actions.keys()) - .find(|id| !tool_rule_ids().contains(id)) + .find(|id| !tool_rule_ids().any(|t| t == id.as_str())) .map(|id| ("inspect_tools", id.as_str())) }) } @@ -294,6 +321,45 @@ mod tests { } } + /// 配置到规则的翻译:停用、改处置、自定义规则的启停,一样不能丢。 + #[test] + fn the_tool_policy_reaches_the_rules() { + let p = ToolPolicy { + disable: vec!["chmod-777".to_string()], + actions: [ + ("rm-rf-root".to_string(), ToolAction::Cut), + ("curl-pipe-sh".to_string(), ToolAction::Record), + ] + .into(), + custom: vec![ + CustomToolRule { + name: "删除集群资源".to_string(), + pattern: r"kubectl\s+delete".to_string(), + action: ToolAction::Cut, + disabled: false, + }, + CustomToolRule { + name: "停用的".to_string(), + pattern: "zzz".to_string(), + action: ToolAction::Cut, + disabled: true, + }, + ], + ..Default::default() + }; + let rs = p.rules().unwrap(); + let high = |id: &str| rs.rules.iter().find(|r| r.id == id).map(|r| r.high); + assert_eq!(high("chmod-777"), None, "停用的还在"); + assert_eq!(high("rm-rf-root"), Some(true)); + assert_eq!(high("curl-pipe-sh"), Some(false)); + assert_eq!(high("base64-decode-exec"), Some(true), "没改的照出厂"); + assert_eq!(high("删除集群资源"), Some(true)); + assert_eq!(high("停用的"), None, "停用的自定义规则还在"); + // 只试一条时也按改过的处置走,而且不管它停没停用 + assert!(p.one_builtin("rm-rf-root").unwrap().rules[0].high); + assert!(p.one_builtin("chmod-777").is_some()); + } + #[test] fn everything_ships_in_observe_mode() { // **这条测的是一个产品决定,不是一段逻辑。**默认值改成 Off 就 diff --git a/crates/tw-config/src/validate.rs b/crates/tw-config/src/validate.rs index 4cff06e6..6532bf2c 100644 --- a/crates/tw-config/src/validate.rs +++ b/crates/tw-config/src/validate.rs @@ -392,7 +392,7 @@ pub fn validate(cfg: &Config) -> Result<(), ValidationError> { /// 一组自定义规则:名字不空、不重复,正则编得过。 /// -/// 上限和数据面编译时一样(`tw_redact::rules::compile`):一条要在每个请求上 +/// 上限和数据面编译时一样(`tw_guard::redact::rules::compile`):一条要在每个请求上 /// 跑的正则,编出来的东西不能太大。 fn check_rules<'a>( what: &'static str, diff --git a/crates/tw-control/Cargo.toml b/crates/tw-control/Cargo.toml index 22048e61..606f0d0c 100644 --- a/crates/tw-control/Cargo.toml +++ b/crates/tw-control/Cargo.toml @@ -17,7 +17,7 @@ rand = { workspace = true } tw-config = { workspace = true } tw-adopt = { workspace = true } tw-scan = { workspace = true } -tw-redact = { workspace = true } +tw-guard = { workspace = true } bytes = { workspace = true } tw-engine = { workspace = true } tw-gateway = { workspace = true } diff --git a/crates/tw-control/src/replay.rs b/crates/tw-control/src/replay.rs index 275c8f1b..c6ccbc83 100644 --- a/crates/tw-control/src/replay.rs +++ b/crates/tw-control/src/replay.rs @@ -215,7 +215,7 @@ pub async fn run( // 回显还原之后再脱敏给人看。**两步都要**:还原是为了让内容和原来 // 那次可比,脱敏是因为这段文字会被复制进 issue - let restored = tw_redact::redact::restore(&text, &ledger); + let restored = tw_guard::redact::replace::restore(&text, &ledger); Ok(Json(tw_api::ReplayResult { provider: provider.name.clone(), status, diff --git a/crates/tw-control/src/scan.rs b/crates/tw-control/src/scan.rs index 03390a54..1dd99684 100644 --- a/crates/tw-control/src/scan.rs +++ b/crates/tw-control/src/scan.rs @@ -53,7 +53,7 @@ pub async fn scan( ) -> Json { // **只用内置规则。**安全页上的规则只作用于经过网关的请求:在那边停用 // 一条误报,不该让这边悄悄少查一样东西 - let rules = tw_scan::rules::scan_rules(); + let rules = tw_guard::tools::rules::scan_rules(); let mut sources = tw_scan::sources::user_level(&s.home); for proj in &p.project { @@ -130,7 +130,7 @@ pub fn spawn_watcher( let mut seen = tw_scan::watch::Seen::default(); // 先垫一次底:把此刻已经存在的那些记下来,它们不算「新出现」 // 内置规则,和打开页面时扫的是同一套 - let rules = tw_scan::rules::scan_rules(); + let rules = tw_guard::tools::rules::scan_rules(); let scan_now = |home: &std::path::Path| { tw_scan::report::scan(&tw_scan::sources::user_level(home), &rules) }; diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index a2fd4c79..9b27d128 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -118,8 +118,8 @@ pub fn view(cfg: &tw_config::Config) -> tw_api::SecurityDetail { } } -fn matcher(m: &tw_redact::rules::Matcher) -> tw_api::Matcher { - use tw_redact::rules::Matcher as M; +fn matcher(m: &tw_guard::redact::rules::Matcher) -> tw_api::Matcher { + use tw_guard::redact::rules::Matcher as M; match *m { M::Prefix { prefix, min_tail } => tw_api::Matcher::Prefix { prefix: prefix.to_string(), @@ -137,7 +137,7 @@ fn matcher(m: &tw_redact::rules::Matcher) -> tw_api::Matcher { } fn redact_view(p: &tw_config::RedactPolicy) -> tw_api::GuardDetail { - let mut rules: Vec = tw_redact::rules::BUILTINS + let mut rules: Vec = tw_guard::redact::rules::BUILTINS .iter() .map(|b| { let on = if b.on_by_default { @@ -180,7 +180,7 @@ fn redact_view(p: &tw_config::RedactPolicy) -> tw_api::GuardDetail { } fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail { - let builtin = &tw_scan::rules::builtin().dangerous; + let builtin = &tw_guard::tools::rules::builtin().dangerous; let mut rules: Vec = builtin .iter() .map(|r| tw_api::SecurityRuleView { @@ -198,11 +198,11 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail { p.actions .get(&r.id) .copied() - .unwrap_or_else(|| tw_scan::rules::factory_action(r)) + .unwrap_or_else(|| tw_config::ToolAction::factory(r)) .slug() .into(), ), - default_action: Some(tw_scan::rules::factory_action(r).slug().into()), + default_action: Some(tw_config::ToolAction::factory(r).slug().into()), }) .collect(); rules.extend(p.custom.iter().map(|c| tw_api::SecurityRuleView { @@ -307,8 +307,8 @@ async fn toggle_builtin( ) -> Result, Fail> { let guard = Guard::parse(&guard)?; let on_by_default = match guard { - Guard::Redact => tw_redact::rules::builtin(&id).map(|b| b.on_by_default), - Guard::Tools => tw_scan::rules::builtin() + Guard::Redact => tw_guard::redact::rules::builtin(&id).map(|b| b.on_by_default), + Guard::Tools => tw_guard::tools::rules::builtin() .dangerous .iter() .any(|r| r.id == id) @@ -368,13 +368,13 @@ async fn set_builtin_action( ), )); } - let spec = tw_scan::rules::builtin() + let spec = tw_guard::tools::rules::builtin() .dangerous .iter() .find(|r| r.id == id) .ok_or_else(|| unknown_rule(&id))?; let action = action_of(&req.action)?; - let factory = tw_scan::rules::factory_action(spec); + let factory = tw_config::ToolAction::factory(spec); let version = s .cfg .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { @@ -402,7 +402,7 @@ fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result Result Fail { +fn bad_pattern(e: tw_guard::redact::rules::BadPattern) -> Fail { fail( StatusCode::BAD_REQUEST, msg!( @@ -525,25 +525,25 @@ async fn test( let trial; let rules = match (&req.pattern, &req.rule) { (Some(p), _) => { - trial = tw_redact::rules::RuleSet::none() + trial = tw_guard::redact::rules::RuleSet::none() .with_custom(TRIAL, p) .map_err(bad_pattern)?; &trial } (None, Some(id)) => { - let b = tw_redact::rules::builtin(id).ok_or_else(|| unknown_rule(id))?; - trial = tw_redact::rules::RuleSet::only(&[b.id]); + let b = tw_guard::redact::rules::builtin(id).ok_or_else(|| unknown_rule(id))?; + trial = tw_guard::redact::rules::RuleSet::only(&[b.id]); &trial } (None, None) => rt.redact.as_ref(), }; // **按它在请求体里的样子找**,结论才和真的请求一致 - tw_redact::rules::scan_plain(&req.sample, rules) + tw_guard::redact::rules::scan_plain(&req.sample, rules) .into_iter() .map(|h| { let value = &req.sample[h.bytes.clone()]; tw_api::SecurityTestHit { - excerpt: tw_redact::rules::masked(&h.rule, value), + excerpt: tw_guard::redact::rules::masked(&h.rule, value), start: utf16_at(&req.sample, h.bytes.start), end: utf16_at(&req.sample, h.bytes.end), rule: h.rule.id().to_string(), @@ -558,8 +558,8 @@ async fn test( let rules = match (&req.pattern, &req.rule) { (Some(p), _) => { // 只要正则引擎那半句:规则名是这里临时起的,说出来只会让人困惑 - trial = tw_scan::rules::single(TRIAL, p, true).map_err( - |tw_scan::rules::RuleError::BadPattern { detail, .. }| { + trial = tw_guard::tools::rules::single(TRIAL, p, true).map_err( + |tw_guard::tools::rules::RuleError::BadPattern { detail, .. }| { fail( StatusCode::BAD_REQUEST, msg!( @@ -572,7 +572,11 @@ async fn test( &trial } (None, Some(id)) => { - trial = tw_scan::rules::one_builtin(id, &s.config().security.inspect_tools) + trial = s + .config() + .security + .inspect_tools + .one_builtin(id) .ok_or_else(|| unknown_rule(id))?; &trial } @@ -615,7 +619,7 @@ mod tests { #[test] fn every_builtin_redaction_rule_is_listed_with_its_default() { let v = redact_view(&Default::default()); - assert_eq!(v.rules.len(), tw_redact::rules::BUILTINS.len()); + assert_eq!(v.rules.len(), tw_guard::redact::rules::BUILTINS.len()); let ip = v.rules.iter().find(|r| r.id == "internal-ip").unwrap(); assert!(!ip.enabled && !ip.on_by_default); let key = v diff --git a/crates/tw-gateway/Cargo.toml b/crates/tw-gateway/Cargo.toml index 3fdb9a99..99b0ffeb 100644 --- a/crates/tw-gateway/Cargo.toml +++ b/crates/tw-gateway/Cargo.toml @@ -34,11 +34,10 @@ blake3 = { workspace = true } sha2 = { workspace = true } rand = { workspace = true } uuid = { workspace = true } -tw-redact = { workspace = true } +tw-guard = { workspace = true } tw-dialect = { workspace = true } tw-upstream = { workspace = true } tw-wire = { workspace = true } -tw-scan = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } tracing = { workspace = true } diff --git a/crates/tw-gateway/src/fixture.rs b/crates/tw-gateway/src/fixture.rs index 01320a8f..f1d117d5 100644 --- a/crates/tw-gateway/src/fixture.rs +++ b/crates/tw-gateway/src/fixture.rs @@ -210,9 +210,16 @@ pub fn record( let clean = |r: Recorded| -> Recorded { // 两道:先按凭据规则换成占位符(结构还在,值没了),再走一遍 // 通用打码兜住规则没认出来的 - let all: Vec<&str> = tw_redact::rules::BUILTINS.iter().map(|b| b.id).collect(); - let redacted = - tw_redact::redact::redact(&r.body, &tw_redact::rules::RuleSet::only(&all)).text; + let all: Vec<&str> = tw_guard::redact::rules::BUILTINS + .iter() + .map(|b| b.id) + .collect(); + let redacted = tw_guard::redact::replace::redact( + &r.body, + &tw_guard::redact::rules::RuleSet::only(&all), + tw_guard::redact::replace::Ledger::new(tw_guard::redact::replace::Scheme::SECRET), + ) + .text; Recorded { body: tw_secret::mask_body(&redacted), ..r diff --git a/crates/tw-gateway/src/guard.rs b/crates/tw-gateway/src/guard.rs index 23146fb1..8ef2eab8 100644 --- a/crates/tw-gateway/src/guard.rs +++ b/crates/tw-gateway/src/guard.rs @@ -1,6 +1,6 @@ //! 数据面守卫:出站脱敏的接线。 //! -//! 规则本身住在 [`tw_redact`] 里,这个文件只回答一个问题:**一个请求体该 +//! 规则本身住在 [`tw_guard::redact`] 里,这个文件只回答一个问题:**一个请求体该 //! 怎么处理。** //! //! # 全局的,对所有上游一视同仁 @@ -17,8 +17,8 @@ //! 转换过格式的,要换的是真正发出去的那一份。 use tw_config::SecurityMode as Mode; -use tw_redact::redact::Ledger; -use tw_redact::rules::{Finding, RuleSet}; +use tw_guard::redact::replace::{Ledger, Scheme}; +use tw_guard::redact::rules::{Finding, RuleSet}; /// 找一遍。**观察档和拦截档都找**,关闭时不找。 /// @@ -30,26 +30,26 @@ pub fn find(mode: Mode, rules: &RuleSet, body: &[u8]) -> Vec { let Ok(text) = std::str::from_utf8(body) else { return Vec::new(); }; - let hits = tw_redact::rules::scan(text, rules); - tw_redact::rules::findings(text, &hits) + let hits = tw_guard::redact::rules::scan(text, rules); + tw_guard::redact::rules::findings(text, &hits) } /// 拦截档下换掉要发出去的这一份。返回换过的体和还原用的账本;**不在拦截档、 /// 或者没找到东西时与进来时逐字节相同**,账本是空的。 pub fn replace(mode: Mode, rules: &RuleSet, body: bytes::Bytes) -> (bytes::Bytes, Ledger) { if !mode.acts() || rules.is_empty() { - return (body, Ledger::default()); + return (body, Ledger::new(Scheme::SECRET)); } // 按字节乱切一个非 UTF-8 的体,得到的是一份坏掉的请求 let Ok(text) = std::str::from_utf8(&body) else { - return (body, Ledger::default()); + return (body, Ledger::new(Scheme::SECRET)); }; - let hits = tw_redact::rules::scan(text, rules); + let hits = tw_guard::redact::rules::scan(text, rules); if hits.is_empty() { // 没命中就原样返回,连一次拷贝都不做 - return (body, Ledger::default()); + return (body, Ledger::new(Scheme::SECRET)); } - let r = tw_redact::redact::apply(text, &hits); + let r = tw_guard::redact::replace::apply(text, &hits, Ledger::new(Scheme::SECRET)); (bytes::Bytes::from(r.text), r.ledger) } diff --git a/crates/tw-gateway/src/lib.rs b/crates/tw-gateway/src/lib.rs index d89bd6e8..a5f2618a 100644 --- a/crates/tw-gateway/src/lib.rs +++ b/crates/tw-gateway/src/lib.rs @@ -29,7 +29,6 @@ pub mod probe; pub mod quote; pub mod server; pub mod session; -pub mod toolwall; pub mod translate; pub mod ws; diff --git a/crates/tw-gateway/src/server.rs b/crates/tw-gateway/src/server.rs index 81393e04..1d61dddb 100644 --- a/crates/tw-gateway/src/server.rs +++ b/crates/tw-gateway/src/server.rs @@ -121,9 +121,9 @@ pub struct Runtime { /// /// **和配置一起建、一起换**,而不是每个请求现编一次 —— 自定义规则是 /// 正则,摆在数据面上现编就是每个请求白付一次编译。 - pub redact: Arc, + pub redact: Arc, /// 工具调用审查的规则。同上。 - pub tools: Arc, + pub tools: Arc, } impl Runtime { @@ -165,7 +165,7 @@ impl Runtime { // 自定义规则的正则、内置规则的 id 在配置校验时已经查过一次,这里再 // 失败只可能是有人绕过了校验,照样拒绝这份配置 let sec = &config.security; - let redact = tw_redact::rules::RuleSet::build( + let redact = tw_guard::redact::rules::RuleSet::build( &sec.redact.enable, &sec.redact.disable, sec.redact.active_custom(), @@ -173,7 +173,7 @@ impl Runtime { .map_err(|e| { GatewayError::config(msg!("gw.config.security_rules", detail = e => "{detail}")) })?; - let tools = tw_scan::rules::tool_rules(&sec.inspect_tools).map_err(|e| { + let tools = sec.inspect_tools.rules().map_err(|e| { GatewayError::config(msg!("gw.config.security_rules", detail = e => "{detail}")) })?; Ok(Self { @@ -1710,7 +1710,8 @@ async fn pipeline( let mut attempts: Vec = Vec::new(); // 成功那一次的脱敏账本。**必须是成功那一次的** —— 每一跳发出去的体可能 // 转换过格式,占位符按那一份的顺序编号 - let mut used_ledger = tw_redact::redact::Ledger::default(); + let mut used_ledger = + tw_guard::redact::replace::Ledger::new(tw_guard::redact::replace::Scheme::SECRET); // 成功那一跳的转换。**必须是成功那一次的** —— 故障转移从 Anthropic 上游 // 切到 OpenAI 上游时,两跳转成的格式不一样;直通时是 None let mut used_session: Option = None; @@ -2223,7 +2224,14 @@ async fn pipeline( // // **没脱敏过就是个空壳**,`process` 直接把字节原样递出去 —— 绝大多数 // 请求走的是这条路,它不该为这个功能付任何延迟。 - let mut restorer = tw_redact::sse::Body::new(&used_ledger, is_sse); + // + // 还原看的是**上游的原话**(转换之前),所以按上游的格式认帧 + let upstream_dialect = session + .as_ref() + .map(|s| s.upstream) + .or_else(|| api.map(|a| a.dialect())) + .unwrap_or(tw_dialect::ir::Dialect::Anthropic); + let mut restorer = tw_guard::redact::sse::Body::new(&used_ledger, is_sse, upstream_dialect); // 流式转换器。**同格式时是 None,整段零成本。** // // 位置在还原**之后**:占位符是我们在出站时塞进去的,先换回真值再 @@ -2273,11 +2281,11 @@ async fn pipeline( let mut wall = if !inspect.detects() { None } else if client_sse { - Some(crate::toolwall::Wall::new(rt.tools.clone())) + Some(tw_guard::tools::wall::Wall::new(rt.tools.clone())) } else if client_json_stream { - Some(crate::toolwall::Wall::json_array(rt.tools.clone())) + Some(tw_guard::tools::wall::Wall::json_array(rt.tools.clone())) } else { - Some(crate::toolwall::Wall::json_body(rt.tools.clone())) + Some(tw_guard::tools::wall::Wall::json_body(rt.tools.clone())) }; /* 非流式要拦得住,body 就不能边收边发 —— 发出去了就收不回来。 @@ -2681,7 +2689,7 @@ pub(crate) fn because(why: &str) -> String { pub(crate) fn flagged( id: u64, provider: &str, - v: &crate::toolwall::Verdict, + v: &tw_guard::tools::wall::Verdict, blocked: bool, ) -> tw_api::Event { tw_api::Event::ToolCallFlagged { diff --git a/crates/tw-gateway/src/ws.rs b/crates/tw-gateway/src/ws.rs index d4aab015..2602d95f 100644 --- a/crates/tw-gateway/src/ws.rs +++ b/crates/tw-gateway/src/ws.rs @@ -108,18 +108,18 @@ pub struct Upstream { /// 它开始时的配置走多久,和普通请求按开始时的运行时走是同一个道理。 pub struct Rules { pub redact_mode: tw_config::SecurityMode, - pub redact: Arc, + pub redact: Arc, pub inspect_mode: tw_config::SecurityMode, - pub tools: Arc, + pub tools: Arc, } /// 一次连接里两个方向各自的状态。 struct Pipes { /// **整条连接一本账。**每帧各起一本的话,第二帧的 - /// `<>` 会和第一帧的撞车(见 `redact_into` 的注释) - ledger: tw_redact::redact::Ledger, + /// `<>` 会和第一帧的撞车(见 `tw_guard::redact::replace::apply` 的注释) + ledger: tw_guard::redact::replace::Ledger, /// 工具调用审查关着的时候没有它 - wall: Option, + wall: Option, rules: Rules, provider: String, id: u64, @@ -176,11 +176,11 @@ pub async fn proxy( } }; let mut p = Pipes { - ledger: tw_redact::redact::Ledger::default(), + ledger: tw_guard::redact::replace::Ledger::new(tw_guard::redact::replace::Scheme::SECRET), wall: rules .inspect_mode .detects() - .then(|| crate::toolwall::Wall::new(rules.tools.clone())), + .then(|| tw_guard::tools::wall::Wall::new(rules.tools.clone())), rules, provider: upstream.provider.name, id, @@ -337,10 +337,15 @@ async fn pump( at_ms: crate::server::now_ms(), }); if mode.acts() { - let r = tw_redact::redact::redact_into( + let r = tw_guard::redact::replace::redact( t.as_str(), &p.rules.redact, - std::mem::take(&mut p.ledger), + std::mem::replace( + &mut p.ledger, + tw_guard::redact::replace::Ledger::new( + tw_guard::redact::replace::Scheme::SECRET, + ), + ), ); p.ledger = r.ledger; UpMsg::Text(r.text.into()) @@ -376,7 +381,7 @@ async fn pump( }; let out = match m { UpMsg::Text(t) => { - let restored = tw_redact::redact::restore(t.as_str(), &p.ledger); + let restored = tw_guard::redact::replace::restore(t.as_str(), &p.ledger); let hits = match p.wall.as_mut() { Some(w) => w.feed(as_sse(&restored).as_bytes()), None => Vec::new(), diff --git a/crates/tw-gateway/tests/m5_redact.rs b/crates/tw-gateway/tests/m5_redact.rs index 2b8c776d..63a56f01 100644 --- a/crates/tw-gateway/tests/m5_redact.rs +++ b/crates/tw-gateway/tests/m5_redact.rs @@ -48,7 +48,7 @@ async fn start_upstream(sse: bool) -> (SocketAddr, Arc>>) { ); for c in echoed.chars() { out.push_str(&format!( - "event: content_block_delta\ndata: {{\"delta\":{{\"text\":{}}}}}\n\n", + "event: content_block_delta\ndata: {{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{{\"type\":\"text_delta\",\"text\":{}}}}}\n\n", serde_json::to_string(&c.to_string()).unwrap() )); } diff --git a/crates/tw-gateway/tests/replay.rs b/crates/tw-gateway/tests/replay.rs index 9683fbe0..902fbc2b 100644 --- a/crates/tw-gateway/tests/replay.rs +++ b/crates/tw-gateway/tests/replay.rs @@ -53,11 +53,15 @@ fn no_fixture_carries_a_credential() { for (name, f) in load_all() { let dump = serde_yaml_ng::to_string(&f).unwrap(); // 内置的凭据规则全开,内网地址不算(夹具里的 10.x 是示意) - let all: Vec<&str> = tw_redact::rules::BUILTINS.iter().map(|b| b.id).collect(); - let hits = tw_redact::rules::scan(&dump, &tw_redact::rules::RuleSet::only(&all)); + let all: Vec<&str> = tw_guard::redact::rules::BUILTINS + .iter() + .map(|b| b.id) + .collect(); + let hits = + tw_guard::redact::rules::scan(&dump, &tw_guard::redact::rules::RuleSet::only(&all)); let real: Vec<_> = hits .iter() - .filter(|h| h.rule.kind() != tw_redact::rules::Kind::Internal) + .filter(|h| h.rule.kind() != tw_guard::redact::rules::Kind::Internal) .map(|h| format!("{}({})", h.rule.id(), &dump[h.bytes.clone()])) .collect(); assert!(real.is_empty(), "{name} 里有凭据:{real:?}"); diff --git a/crates/tw-redact/Cargo.toml b/crates/tw-guard/Cargo.toml similarity index 63% rename from crates/tw-redact/Cargo.toml rename to crates/tw-guard/Cargo.toml index df98fd1a..2dab9434 100644 --- a/crates/tw-redact/Cargo.toml +++ b/crates/tw-guard/Cargo.toml @@ -1,11 +1,11 @@ [package] -name = "tw-redact" +name = "tw-guard" version.workspace = true edition.workspace = true rust-version.workspace = true license.workspace = true repository.workspace = true -description = "Outbound redaction: replace credentials with placeholders, and restore them when a response echoes them back" +description = "Guards shared by both gateways: outbound redaction and restoration, and inspection of the tool calls an upstream returns" [dependencies] serde = { workspace = true } @@ -14,6 +14,8 @@ serde_json = { workspace = true } regex = { workspace = true } thiserror = { workspace = true } tw-secret = { workspace = true } +serde_yaml_ng = { workspace = true } +tw-dialect = { workspace = true } [dev-dependencies] serde_json = { workspace = true } diff --git a/crates/tw-config/data/rules.yaml b/crates/tw-guard/data/rules.yaml similarity index 100% rename from crates/tw-config/data/rules.yaml rename to crates/tw-guard/data/rules.yaml diff --git a/crates/tw-guard/src/lib.rs b/crates/tw-guard/src/lib.rs new file mode 100644 index 00000000..39aa04bb --- /dev/null +++ b/crates/tw-guard/src/lib.rs @@ -0,0 +1,19 @@ +//! 防护:出站脱敏,和对上游返回的工具调用的审查。 +//! +//! **引擎在这里,规则集和配置各带各的。**桌面版脱的是开发者自己的 API key, +//! 企业版脱的是客户的身份证号和手机号;桌面版的规则写在 `config.yaml`,企业版 +//! 的在系统设置里。两边共用的是「怎么找、怎么换、怎么在流里换回来、怎么审查 +//! 一个工具调用」—— 这些和规则是什么、从哪来无关。 + +pub mod redact; +pub mod tools; + +/// 编一条调用方给的正则。**编译后的大小有上限**(NFA 和 DFA 各 1 MiB)—— +/// 这条正则要在每个请求上跑,而 `(a|aa){200}` 这种写法在默认的 10 MiB 上限下 +/// 要编好几秒、占几 MB,然后每个请求都付一遍。 +fn bounded(pattern: &str) -> Result { + regex::RegexBuilder::new(pattern) + .size_limit(1 << 20) + .dfa_size_limit(1 << 20) + .build() +} diff --git a/crates/tw-guard/src/redact/mod.rs b/crates/tw-guard/src/redact/mod.rs new file mode 100644 index 00000000..3c5b787f --- /dev/null +++ b/crates/tw-guard/src/redact/mod.rs @@ -0,0 +1,6 @@ +//! 出站脱敏:把敏感值换成占位符,响应回显时再换回来。 + +pub mod replace; +pub mod rules; +pub mod sse; +pub mod stream; diff --git a/crates/tw-redact/src/redact.rs b/crates/tw-guard/src/redact/replace.rs similarity index 51% rename from crates/tw-redact/src/redact.rs rename to crates/tw-guard/src/redact/replace.rs index 125636f5..5da9a609 100644 --- a/crates/tw-redact/src/redact.rs +++ b/crates/tw-guard/src/redact/replace.rs @@ -1,18 +1,38 @@ -//! 把凭据换成占位符,并记住怎么换回来。 +//! 把敏感值换成占位符,并记住怎么换回来。 //! //! **可逆替换,不是删除。**删掉的话模型看到半截连接串反而会瞎猜 —— //! 而「瞎猜」在一个正帮你调试 `.env` 的助手身上,比看不见更糟。 use std::collections::HashMap; -use crate::rules::{Hit, RuleSet}; +use crate::redact::rules::{Hit, RuleSet}; -/// 占位符长什么样:`<>`。 -pub const OPEN: &str = "<>`:开发者的 +/// 请求里满是 `{{ }}` 模板,用尖括号撞车的机会少得多。企业版是 +/// `{{EMAIL_1}}`:标签告诉模型「这里原来是个邮箱」,它才答得像样。 +/// +/// 开头那段必须是 ASCII:流式还原按字节找它,找到的位置要能直接切。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Scheme { + pub open: &'static str, + pub close: &'static str, + /// 规则没有自己的标签时用它 + pub label: &'static str, +} -pub fn placeholder(n: usize) -> String { - format!("{OPEN}{n}{CLOSE}") +impl Scheme { + /// 桌面版的:`<>` + pub const SECRET: Scheme = Scheme { + open: "<<", + close: ">>", + label: "TW_SECRET", + }; + + pub fn placeholder(&self, label: &str, n: usize) -> String { + format!("{}{label}_{n}{}", self.open, self.close) + } } /// 一次脱敏留下的账本。 @@ -21,17 +41,34 @@ pub fn placeholder(n: usize) -> String { /// 不同的占位符,会让模型以为那是三个不同的东西 —— 而它可能正在帮你 /// 对比「这两处的 key 是不是同一把」。 /// -/// 换了哪些、各几处不记在这里:那是 [`crate::rules::findings`] 从命中里 +/// **编号按标签各数各的**:`{{EMAIL_1}}`、`{{PHONE_1}}`,而不是 +/// `{{EMAIL_1}}`、`{{PHONE_2}}` —— 后者让模型以为漏了一个。 +/// +/// 换了哪些、各几处不记在这里:那是 [`crate::redact::rules::findings`] 从命中里 /// 算出来的,观察档(不换)和拦截档(换)报的是同一份。 -#[derive(Debug, Clone, Default)] +#[derive(Debug, Clone)] pub struct Ledger { + scheme: Scheme, /// 占位符 → 原值 back: HashMap, /// 原值 → 占位符,用来复用编号 seen: HashMap, + /// 每个标签发到几号了 + issued: HashMap, } impl Ledger { + pub fn new(scheme: Scheme) -> Self { + Self { + scheme, + back: HashMap::new(), + seen: HashMap::new(), + issued: HashMap::new(), + } + } + pub fn scheme(&self) -> Scheme { + self.scheme + } pub fn is_empty(&self) -> bool { self.back.is_empty() } @@ -42,6 +79,24 @@ impl Ledger { pub fn table(&self) -> &HashMap { &self.back } + /// 原值 → 占位符。在一处找到的值要换到别处去时用它(企业版在解码后的 + /// 请求上找,再换进原样转发的那一份)。 + pub fn replacements(&self) -> impl Iterator { + self.seen.iter().map(|(o, p)| (o.as_str(), p.as_str())) + } + + /// 这个值的占位符,头一次见就发一个新号。 + fn issue(&mut self, original: &str, label: &str) -> String { + if let Some(p) = self.seen.get(original) { + return p.clone(); + } + let n = self.issued.entry(label.to_string()).or_insert(0); + *n += 1; + let p = self.scheme.placeholder(label, *n); + self.back.insert(p.clone(), original.to_string()); + self.seen.insert(original.to_string(), p.clone()); + p + } } /// 脱敏的结果。 @@ -52,22 +107,17 @@ pub struct Redacted { pub ledger: Ledger, } -/// 把 `hits` 指的那些段换成占位符。 +/// 把 `hits` 指的那些段换成占位符,**接着 `ledger` 已有的编号**。 +/// +/// 一次请求里有很多段文本(多条消息、WebSocket 的多帧)时,它们必须记在同一本 +/// 账上:各起一本的话,第二段的 1 号会和第一段的撞车 —— 两个不同的值映射到 +/// 同一个占位符,还原时必然给错一个。**那不是会不会发生的问题,是第二段只要 +/// 命中一次就一定发生。** /// /// **从后往前替换。**从前往后的话,第一次替换就会让后面所有区间的偏移 /// 失效 —— 而那种错不会立刻炸,它会安静地切错一个字节,然后你拿到一份 /// 坏掉的 JSON。 -pub fn apply(text: &str, hits: &[Hit]) -> Redacted { - apply_into(text, hits, Ledger::default()) -} - -/// 同上,但**接着一本已有的账本编号**。 -/// -/// WebSocket 那条路要用它:一次连接里有很多帧,而每帧各起一本 -/// 账的话,第二帧的 `<>` 会和第一帧的撞车 —— 两个不同的 -/// 密钥映射到同一个占位符,还原时必然给错一个。**那不是会不会发生的 -/// 问题,是第二帧只要命中一次就一定发生。** -pub fn apply_into(text: &str, hits: &[Hit], mut ledger: Ledger) -> Redacted { +pub fn apply(text: &str, hits: &[Hit], mut ledger: Ledger) -> Redacted { if hits.is_empty() { return Redacted { text: text.to_string(), @@ -75,43 +125,67 @@ pub fn apply_into(text: &str, hits: &[Hit], mut ledger: Ledger) -> Redacted { }; } // 编号按出现的先后发:从后往前换,但先从前往后把号发完 - for h in hits { - let original = &text[h.bytes.clone()]; - if !ledger.seen.contains_key(original) { - let p = placeholder(ledger.back.len() + 1); - ledger.back.insert(p.clone(), original.to_string()); - ledger.seen.insert(original.to_string(), p); - } - } + let default = ledger.scheme.label; + let placeholders: Vec = hits + .iter() + .map(|h| { + ledger.issue( + &text[h.bytes.clone()], + h.label.as_deref().unwrap_or(default), + ) + }) + .collect(); let mut out = text.to_string(); - for h in hits.iter().rev() { - let ph = &ledger.seen[&text[h.bytes.clone()]]; + for (h, ph) in hits.iter().zip(&placeholders).rev() { out.replace_range(h.bytes.clone(), ph); } Redacted { text: out, ledger } } -/// 扫 + 换,一步到位。 -pub fn redact(text: &str, rules: &RuleSet) -> Redacted { - let hits = crate::rules::scan(text, rules); - apply(text, &hits) +/// 扫 + 换,一步到位。`text` 是 JSON 请求体(见 [`crate::redact::rules::scan`])。 +pub fn redact(text: &str, rules: &RuleSet, ledger: Ledger) -> Redacted { + let hits = crate::redact::rules::scan(text, rules); + apply(text, &hits, ledger) } -/// 扫 + 换,接着一本已有的账本编号。见 [`apply_into`]。 -pub fn redact_into(text: &str, rules: &RuleSet, ledger: Ledger) -> Redacted { - let hits = crate::rules::scan(text, rules); - apply_into(text, &hits, ledger) +/// 扫 + 换一段**纯文本**(见 [`crate::redact::rules::scan_plain`])。 +pub fn redact_plain(text: &str, rules: &RuleSet, ledger: Ledger) -> Redacted { + let hits = crate::redact::rules::scan_plain(text, rules); + apply(text, &hits, ledger) +} + +/// 扫 + 换一段**解码过的正文**(见 [`crate::redact::rules::scan_text`])。 +pub fn redact_text(text: &str, rules: &RuleSet, ledger: Ledger) -> Redacted { + let hits = crate::redact::rules::scan_text(text, rules); + apply(text, &hits, ledger) } /// 一次性还原(非流式响应、错误信息)。 +/// +/// 按 [`crate::redact::rules::scan`] / `scan_plain` 换下来的值里从来没有引号和 +/// 反斜杠,原样放回 JSON 字符串里也还是合法的 JSON。按 `scan_text` 换的可能有, +/// 整包 JSON 用 [`restore_json`]。 pub fn restore(text: &str, ledger: &Ledger) -> String { - if ledger.is_empty() || !text.contains(OPEN) { + swap(text, ledger, |s| s.to_string()) +} + +/// 一次性还原一份 **JSON 文本**:原值按 JSON 字符串转义之后再放回去 —— 一个 +/// 带引号的值原样塞回去,整份 JSON 就坏了。 +pub fn restore_json(text: &str, ledger: &Ledger) -> String { + swap(text, ledger, |s| { + let quoted = serde_json::to_string(s).unwrap_or_default(); + quoted[1..quoted.len().saturating_sub(1)].to_string() + }) +} + +fn swap(text: &str, ledger: &Ledger, put: impl Fn(&str) -> String) -> String { + if ledger.is_empty() || !text.contains(ledger.scheme.open) { return text.to_string(); } let mut out = text.to_string(); for (ph, original) in ledger.table() { if out.contains(ph.as_str()) { - out = out.replace(ph.as_str(), original); + out = out.replace(ph.as_str(), &put(original)); } } out @@ -120,7 +194,11 @@ pub fn restore(text: &str, ledger: &Ledger) -> String { #[cfg(test)] mod tests { use super::*; - use crate::rules::{BUILTINS, RuleSet}; + use crate::redact::rules::{BUILTINS, RuleSet}; + + fn l() -> Ledger { + Ledger::new(Scheme::SECRET) + } const KEY: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA"; @@ -133,7 +211,7 @@ mod tests { // **绝大多数请求一处都不命中**,而这个函数每个请求都要跑, // 所以它在「没命中」时必须是一次纯粹的拷贝。 let t = "帮我看看这个 .env 文件\n"; - let r = redact(t, &all()); + let r = redact(t, &all(), l()); assert_eq!(r.text, t); assert!(r.ledger.is_empty()); assert_eq!(restore(&r.text, &r.ledger), t); @@ -142,7 +220,7 @@ mod tests { #[test] fn a_key_becomes_a_placeholder_and_comes_back() { let t = format!("我的 key 是 {KEY},帮我看看"); - let r = redact(&t, &all()); + let r = redact(&t, &all(), l()); assert!(!r.text.contains(KEY), "{}", r.text); assert!(r.text.contains("<>"), "{}", r.text); assert_eq!(restore(&r.text, &r.ledger), t); @@ -156,7 +234,7 @@ mod tests { "messages": [{ "role": "user", "content": format!("keys:\n{KEY}\nthanks") }] }) .to_string(); - let r = redact(&body, &all()); + let r = redact(&body, &all(), l()); assert!(!r.text.contains(KEY), "{}", r.text); let v: serde_json::Value = serde_json::from_str(&r.text).expect("the body is still JSON"); assert_eq!( @@ -171,7 +249,7 @@ mod tests { // 一把 key 出现三次却换成三个不同的占位符,会让模型以为那是三个 // 不同的东西 —— 而它可能正在帮你对比「这两处是不是同一把」。 let t = format!("A={KEY}\nB={KEY}\nC={KEY}"); - let r = redact(&t, &all()); + let r = redact(&t, &all(), l()); assert_eq!(r.ledger.len(), 1, "{:?}", r.ledger); assert_eq!(r.text.matches("<>").count(), 3, "{}", r.text); assert_eq!(restore(&r.text, &r.ledger), t); @@ -181,7 +259,7 @@ mod tests { fn different_values_get_different_placeholders() { let other = "ghp_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; let t = format!("{KEY} 和 {other}"); - let r = redact(&t, &all()); + let r = redact(&t, &all(), l()); assert_eq!(r.ledger.len(), 2); assert_eq!(restore(&r.text, &r.ledger), t); } @@ -191,7 +269,7 @@ mod tests { // 从前往后替换的话,第一次替换就会让后面所有区间的偏移失效。 // 那种错不会立刻炸,它会安静地切错一个字节。 let t = format!("先 10.0.0.1 再 {KEY} 最后 postgres://u:pw@h/db"); - let r = redact(&t, &all()); + let r = redact(&t, &all(), l()); assert_eq!(r.ledger.len(), 3, "{}", r.text); assert_eq!(restore(&r.text, &r.ledger), t); // 连接串只换了口令,host 还看得见 @@ -203,7 +281,7 @@ mod tests { fn multibyte_text_around_a_hit_survives_intact() { // 这个项目已经被字节切片坑过三次。 let t = format!("很长的一段中文说明,中间夹着 {KEY},后面还有更多中文内容"); - let r = redact(&t, &all()); + let r = redact(&t, &all(), l()); assert!(r.text.starts_with("很长的一段中文说明"), "{}", r.text); assert!(r.text.ends_with("后面还有更多中文内容"), "{}", r.text); assert_eq!(restore(&r.text, &r.ledger), t); @@ -213,14 +291,14 @@ mod tests { fn the_first_value_gets_the_first_number() { // 编号按出现的先后发 —— 从后往前换不该把号也倒过来 let t = format!("{KEY} 然后 10.0.0.2"); - let r = redact(&t, &all()); + let r = redact(&t, &all(), l()); assert!(r.text.starts_with("<>"), "{}", r.text); assert!(r.text.ends_with("<>"), "{}", r.text); } #[test] fn restoring_text_that_has_no_placeholder_is_a_passthrough() { - let r = redact(&format!("k={KEY}"), &all()); + let r = redact(&format!("k={KEY}"), &all(), l()); assert_eq!(restore("模型说了点别的", &r.ledger), "模型说了点别的"); } @@ -228,7 +306,7 @@ mod tests { fn an_unknown_placeholder_is_left_alone() { // 模型自己编了一个 `<>` 出来 —— 我们不认识它, // 那就原样交给客户端,而不是猜一个值填进去。 - let r = redact(&format!("k={KEY}"), &all()); + let r = redact(&format!("k={KEY}"), &all(), l()); assert_eq!( restore("这是 <> 好吗", &r.ledger), "这是 <> 好吗" @@ -239,8 +317,12 @@ mod tests { // **第二帧只要命中一次就一定撞车** —— 两个不同的密钥映射到同一个 // 占位符,还原时必然给错一个(WebSocket 那条路) let kinds = RuleSet::only(&["anthropic-api-key"]); - let a = redact("我的 key 是 sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAA", &kinds); - let b = redact_into( + let a = redact( + "我的 key 是 sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAA", + &kinds, + l(), + ); + let b = redact( "另一把是 sk-ant-api03-BBBBBBBBBBBBBBBBBBBBBBBB", &kinds, a.ledger.clone(), @@ -263,9 +345,53 @@ mod tests { // 两个不同的东西 let kinds = RuleSet::only(&["anthropic-api-key"]); let k = "sk-ant-api03-SAMESAMESAMESAMESAME1"; - let a = redact(&format!("第一次 {k}"), &kinds); - let b = redact_into(&format!("第二次 {k}"), &kinds, a.ledger.clone()); + let a = redact(&format!("第一次 {k}"), &kinds, l()); + let b = redact(&format!("第二次 {k}"), &kinds, a.ledger.clone()); assert!(b.text.contains("<>"), "{}", b.text); assert_eq!(b.ledger.len(), 1, "同一个值占了两个编号"); } + + #[test] + fn labeled_placeholders_count_per_label() { + // `{{EMAIL_1}}`、`{{PHONE_1}}`,而不是 `{{PHONE_2}}` —— 后者让模型以为 + // 漏了一个 + let scheme = Scheme { + open: "{{", + close: "}}", + label: "PII", + }; + let rules = RuleSet::none() + .with_labeled("email", r"[a-z]+@[a-z]+\.com", Some("EMAIL")) + .unwrap() + .with_labeled("phone", r"1[3-9]\d{9}", Some("PHONE")) + .unwrap() + .with_custom("other", r"ID-\d+") + .unwrap(); + let t = "a@b.com 13800138000 c@d.com a@b.com ID-7"; + let r = redact_plain(t, &rules, Ledger::new(scheme)); + assert_eq!( + r.text, + "{{EMAIL_1}} {{PHONE_1}} {{EMAIL_2}} {{EMAIL_1}} {{PII_1}}" + ); + assert_eq!(restore(&r.text, &r.ledger), t); + let pairs: std::collections::HashMap<_, _> = r.ledger.replacements().collect(); + assert_eq!(pairs["c@d.com"], "{{EMAIL_2}}"); + } + + #[test] + fn decoded_text_is_matched_as_written_and_restored_into_json_escaped() { + // 正文上的 `password="x"`:截在引号处的话,换下来的只是 `password=`, + // 真值原样发出去 + let rules = RuleSet::none() + .with_labeled("pw", r#"password="[^"]*""#, Some("SECRET")) + .unwrap(); + let text = r#"用 password="hunter2" 登录"#; + let r = redact_text(text, &rules, l()); + assert_eq!(r.text, "用 <> 登录"); + // 回显在一份 JSON 里:放回去要转义,否则整份 JSON 就坏了 + let body = serde_json::json!({ "text": r.text }).to_string(); + let back: serde_json::Value = + serde_json::from_str(&restore_json(&body, &r.ledger)).expect("still JSON"); + assert_eq!(back["text"], text); + } } diff --git a/crates/tw-redact/src/rules.rs b/crates/tw-guard/src/redact/rules.rs similarity index 92% rename from crates/tw-redact/src/rules.rs rename to crates/tw-guard/src/redact/rules.rs index eee8068e..04920458 100644 --- a/crates/tw-redact/src/rules.rs +++ b/crates/tw-guard/src/redact/rules.rs @@ -245,6 +245,8 @@ pub struct Hit { /// 在原文里的字节区间 pub bytes: Range, pub rule: Rule, + /// 占位符里用的标签。`None` 用账本的默认标签 + pub label: Option>, } /// 一条编译好的自定义规则。 @@ -252,6 +254,8 @@ pub struct Hit { pub struct Custom { pub name: Arc, pub re: regex::Regex, + /// 占位符里的标签(企业版的 `EMAIL`、`PHONE`)。`None` 用账本的默认标签 + pub label: Option>, } /// 一个自定义规则的正则写错了。 @@ -271,13 +275,10 @@ pub fn compile(name: &str, pattern: &str) -> Result { detail: "the pattern is empty".to_string(), }); } - regex::RegexBuilder::new(pattern) - .size_limit(1 << 20) - .build() - .map_err(|e| BadPattern { - name: name.to_string(), - detail: e.to_string(), - }) + crate::bounded(pattern).map_err(|e| BadPattern { + name: name.to_string(), + detail: e.to_string(), + }) } /// 这一次按哪些规则找。 @@ -348,16 +349,28 @@ impl RuleSet { set.custom.push(Custom { name: Arc::from(name), re: compile(name, pattern)?, + label: None, }); } Ok(set) } /// 再加一条自定义规则。 - pub fn with_custom(mut self, name: &str, pattern: &str) -> Result { + pub fn with_custom(self, name: &str, pattern: &str) -> Result { + self.with_labeled(name, pattern, None) + } + + /// 再加一条自定义规则,占位符用它自己的标签:`{{EMAIL_1}}` 里的 `EMAIL`。 + pub fn with_labeled( + mut self, + name: &str, + pattern: &str, + label: Option<&str>, + ) -> Result { self.custom.push(Custom { name: Arc::from(name), re: compile(name, pattern)?, + label: label.map(Arc::from), }); Ok(self) } @@ -488,6 +501,7 @@ fn private_keys(text: &str, out: &mut Vec) { out.push(Hit { bytes: begin..end, rule: Rule::Builtin("private-key"), + label: None, }); from = end; } @@ -558,6 +572,7 @@ fn conn_strings(text: &str, out: &mut Vec) { out.push(Hit { bytes: c + 1..j, rule: Rule::Builtin("conn-string-password"), + label: None, }); } from = after; @@ -639,6 +654,7 @@ fn custom_hits(text: &str, set: &RuleSet, out: &mut Vec) { out.push(Hit { bytes, rule: Rule::Custom(c.name.clone()), + label: c.label.clone(), }); } } @@ -668,6 +684,7 @@ pub fn scan(text: &str, set: &RuleSet) -> Vec { out.push(Hit { bytes: span, rule: Rule::Builtin(id), + label: None, }); return; } @@ -675,6 +692,7 @@ pub fn scan(text: &str, set: &RuleSet) -> Vec { out.push(Hit { bytes: span, rule: Rule::Builtin("jwt"), + label: None, }); return; } @@ -682,13 +700,18 @@ pub fn scan(text: &str, set: &RuleSet) -> Vec { out.push(Hit { bytes: span, rule: Rule::Builtin(id), + label: None, }); } }); custom_hits(text, set, &mut out); + disjoint(out) +} + +/// 排好序、去掉重叠的。**重叠的只留第一个。**私钥块里的 base64 会被 token +/// 扫描当成别的东西,两段嵌在一起替换会把偏移彻底搞乱。同一个起点上留长的那段。 +fn disjoint(mut out: Vec) -> Vec { out.sort_by_key(|h| (h.bytes.start, std::cmp::Reverse(h.bytes.end))); - // **重叠的只留第一个。**私钥块里的 base64 会被 token 扫描当成别的 - // 东西,两段嵌在一起替换会把偏移彻底搞乱。同一个起点上留长的那段 let mut kept: Vec = Vec::with_capacity(out.len()); for h in out { if kept.last().is_some_and(|p| p.bytes.end > h.bytes.start) { @@ -737,11 +760,37 @@ pub fn scan_plain(text: &str, set: &RuleSet) -> Vec { (end > start).then_some(Hit { bytes: start..end, rule: h.rule, + label: h.label, }) }) .collect() } +/// 扫一段**解码过的正文**:自定义规则按正则本来的意思匹配。 +/// +/// 和 [`scan_plain`] 的差别只在自定义规则上。桌面版扫的是线上那份 JSON,所以 +/// 自定义规则的命中止于引号和反斜杠(见 `json_safe`);而一个先解码请求、在 +/// 正文上找、再把结果带回去的调用方(企业版)看到的就是正文,`password="x"` +/// 截成 `password=` 只会让真值漏出去。它换下来的值可能带引号,整包还原时要用 +/// [`crate::redact::replace::restore_json`]。 +pub fn scan_text(text: &str, set: &RuleSet) -> Vec { + let builtins = RuleSet { + on: set.on.clone(), + custom: Vec::new(), + }; + let mut out = scan_plain(text, &builtins); + for c in &set.custom { + for m in c.re.find_iter(text).filter(|m| !m.is_empty()) { + out.push(Hit { + bytes: m.range(), + rule: Rule::Custom(c.name.clone()), + label: c.label.clone(), + }); + } + } + disjoint(out) +} + /// 报出去的样子。**一律打码** —— 「发现了 sk-ant-xxx」这句话本身就是一次 /// 泄漏,它会进日志、进界面、被复制到 issue 里。 /// @@ -799,6 +848,13 @@ mod tests { .collect() } + #[test] + fn a_pattern_that_compiles_into_something_huge_is_refused() { + // 默认上限下它能编过,然后每个请求都付几毫秒 + assert!(compile("大", "(a|aa|aaa){5000}").is_err()); + assert!(compile("正常", r"corp_[A-Za-z0-9]{12}").is_ok()); + } + #[test] fn the_prefixed_keys_are_found_whole() { let t = "我的 key 是 sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA,别外传"; @@ -881,10 +937,14 @@ mod tests { assert_eq!(got.len(), 1, "{got:?}"); assert_eq!(got[0].0, "private-key"); // 换掉之后 JSON 还得是合法的 - let r = crate::redact::redact(body, &all()); + let r = crate::redact::replace::redact( + body, + &all(), + crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), + ); serde_json::from_str::(&r.text).expect("换完不是合法 JSON"); // 而且能一字不差地换回来 - assert_eq!(crate::redact::restore(&r.text, &r.ledger), body); + assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), body); } #[test] @@ -997,12 +1057,16 @@ mod tests { "content": "pw=hunter2\n下一行 \"引号\" pw=abc\"def" })) .unwrap(); - let r = crate::redact::redact(&body, &set); + let r = crate::redact::replace::redact( + &body, + &set, + crate::redact::replace::Ledger::new(crate::redact::replace::Scheme::SECRET), + ); let v: serde_json::Value = serde_json::from_str(&r.text).expect("换完不是合法 JSON"); let content = v["content"].as_str().unwrap(); assert!(content.starts_with("<>\n下一行"), "{content}"); assert!(content.contains("<>\"def"), "{content}"); - assert_eq!(crate::redact::restore(&r.text, &r.ledger), body); + assert_eq!(crate::redact::replace::restore(&r.text, &r.ledger), body); } #[test] diff --git a/crates/tw-guard/src/redact/sse.rs b/crates/tw-guard/src/redact/sse.rs new file mode 100644 index 00000000..1029fa3a --- /dev/null +++ b/crates/tw-guard/src/redact/sse.rs @@ -0,0 +1,993 @@ +//! 在流里把占位符换回来。 +//! +//! # 为什么不能在原始字节上做 +//! +//! ```text +//! data: {"delta":{"text":"<<"}} +//! data: {"delta":{"text":"TW_SEC"}} +//! data: {"delta":{"text":"RET_1>>"}} +//! ``` +//! +//! 占位符在**解码后的正文里**是连续的,在线路上不是 —— 中间隔着 +//! `"}}\n\ndata: {"delta":{"text":"`。模型按 token 吐字,一个占位符会被切成 +//! 五到八段,这不是边角情况,是常态。所以要拆出每一帧,找到装正文的那个字段, +//! 解码之后再还原。 +//! +//! # 按格式、按路 +//! +//! **一条流里不止一路正文。**Anthropic 一个内容块一路,工具参数又是一路; +//! Chat 的正文和每个工具调用的参数各是一路。扣住的尾巴只能接回它自己那一路: +//! 正文块末尾扣住的 `< u64 { + match self { + Lane::Text(k) => k >> 32, + Lane::Args(k) => k, + } + } +} + +/// 一帧里的一处正文:哪一路、在哪个字段。 +struct Field { + lane: Lane, + path: Vec, +} + +#[derive(Debug, Clone)] +enum Seg { + Key(&'static str), + Idx(usize), +} + +fn at<'a>(v: &'a mut Value, path: &[Seg]) -> Option<&'a mut String> { + let mut cur = v; + for s in path { + cur = match (s, cur) { + (Seg::Key(k), Value::Object(m)) => m.get_mut(*k)?, + (Seg::Idx(i), Value::Array(a)) => a.get_mut(*i)?, + _ => return None, + }; + } + match cur { + Value::String(s) => Some(s), + _ => None, + } +} + +/// 哪几路在这一帧结束。 +enum Close { + None, + Lanes(Vec), + /// Responses 的 `output_item.done`:这一项的所有路 + Output(u64), + All, +} + +/// 补出来的一帧,要**先于**它前面那一帧发出去。 +#[derive(Debug, Clone, PartialEq)] +pub struct Synth { + pub event: Option, + pub data: Value, +} + +/// 一帧改写的结果。 +#[derive(Debug, Default)] +pub struct Rewritten { + /// 这一帧本身改了没有。没改的话调用方可以原样转发它的字节 + pub changed: bool, + /// 要先于这一帧发出去的补帧 + pub before: Vec, +} + +struct Open { + restorer: Restorer, + /// 这一路最近的一帧。补帧时从它身上抄 id、index 这些 + last: Value, +} + +/// 一条流上、按帧的还原器。 +pub struct FrameRestorer { + dialect: Dialect, + ledger: Ledger, + oneshot: Restorer, + lanes: BTreeMap, +} + +impl FrameRestorer { + /// `dialect` 是**这条流**的格式:还原放在转换之前就是上游的格式,放在转换 + /// 之后就是客户端的格式。 + pub fn new(ledger: &Ledger, dialect: Dialect) -> Self { + Self { + dialect, + ledger: ledger.clone(), + oneshot: Restorer::new(ledger), + lanes: BTreeMap::new(), + } + } + + /// 没东西要还原。**调用方据此整条短路。** + pub fn is_noop(&self) -> bool { + self.ledger.is_empty() + } + + /// 改写一帧。帧本身就地改,返回要先于它发出去的补帧。 + pub fn frame(&mut self, v: &mut Value) -> Rewritten { + let mut out = Rewritten::default(); + if self.is_noop() { + return out; + } + // 完整的占位符,不管在哪个字段里:`output_text.done` 带着整段正文、 + // Gemini 的函数调用参数整个在一帧里 + out.changed |= walk(v, &self.oneshot); + // 流着的正文,按路扣住半截的 + let fields = fields(self.dialect, v); + for f in &fields { + let open = self.lanes.entry(f.lane).or_insert_with(|| Open { + restorer: Restorer::new(&self.ledger), + last: Value::Null, + }); + open.last = v.clone(); + if let Some(s) = at(v, &f.path) { + let next = open.restorer.process(s); + out.changed |= next != *s; + *s = next; + } + } + // 这一帧结束了哪几路:扣住的尾巴在它之前补出来。那一路的正文就在 + // 这一帧里的话(Gemini 最后一帧常常既有正文又有 finishReason),直接 + // 接在那个字段后面 + let closing: Vec = match close(self.dialect, v) { + Close::None => Vec::new(), + Close::Lanes(l) => l, + Close::Output(oi) => self + .lanes + .keys() + .copied() + .filter(|l| l.output_index() == oi) + .collect(), + Close::All => self.lanes.keys().copied().collect(), + }; + for lane in closing { + let Some(mut open) = self.lanes.remove(&lane) else { + continue; + }; + let tail = open.restorer.flush(); + if tail.is_empty() { + continue; + } + match fields.iter().rev().find(|f| f.lane == lane) { + Some(f) => { + if let Some(s) = at(v, &f.path) { + s.push_str(&tail); + out.changed = true; + } + } + None => out.before.push(synth(self.dialect, lane, &open.last, tail)), + } + } + out + } + + /// 碰到不是 JSON 的帧(`[DONE]`),或者流结束了:所有扣住的尾巴补成帧。 + /// + /// **丢掉它就是丢掉模型说过的字**,而那比多一帧难看得多。 + pub fn drain(&mut self) -> Vec { + let lanes = std::mem::take(&mut self.lanes); + lanes + .into_iter() + .filter_map(|(lane, mut open)| { + let tail = open.restorer.flush(); + (!tail.is_empty()).then(|| synth(self.dialect, lane, &open.last, tail)) + }) + .collect() + } +} + +/// 在一帧的每个字符串上做一次性还原,跳过 [`UNTOUCHED`] 下面的。返回改了没有。 +fn walk(v: &mut Value, r: &Restorer) -> bool { + match v { + Value::String(s) => { + let next = r.oneshot(s); + let changed = next != *s; + *s = next; + changed + } + Value::Array(items) => items.iter_mut().fold(false, |c, i| walk(i, r) | c), + Value::Object(m) => m + .iter_mut() + .filter(|(k, _)| !UNTOUCHED.contains(&k.as_str())) + .fold(false, |c, (_, i)| walk(i, r) | c), + _ => false, + } +} + +fn kind(v: &Value) -> Option<&str> { + v.get("type").and_then(Value::as_str) +} + +fn u(v: &Value, k: &str) -> u64 { + v.get(k).and_then(Value::as_u64).unwrap_or(0) +} + +/// 一帧里流着的正文在哪几个字段。 +fn fields(d: Dialect, v: &Value) -> Vec { + use Seg::{Idx, Key}; + let mut out = Vec::new(); + match d { + Dialect::Anthropic => { + if kind(v) == Some("content_block_delta") { + let i = u(v, "index"); + match v.pointer("/delta/type").and_then(Value::as_str) { + Some("text_delta") => out.push(Field { + lane: Lane::Text(i), + path: vec![Key("delta"), Key("text")], + }), + Some("input_json_delta") => out.push(Field { + lane: Lane::Args(i), + path: vec![Key("delta"), Key("partial_json")], + }), + _ => {} + } + } + } + Dialect::Chat => { + let Some(delta) = v.pointer("/choices/0/delta") else { + return out; + }; + if delta.get("content").is_some_and(Value::is_string) { + out.push(Field { + lane: Lane::Text(0), + path: vec![Key("choices"), Idx(0), Key("delta"), Key("content")], + }); + } + if let Some(calls) = delta.get("tool_calls").and_then(Value::as_array) { + for (k, c) in calls.iter().enumerate() { + if c.pointer("/function/arguments") + .is_some_and(Value::is_string) + { + let i = c.get("index").and_then(Value::as_u64).unwrap_or(k as u64); + out.push(Field { + lane: Lane::Args(i), + path: vec![ + Key("choices"), + Idx(0), + Key("delta"), + Key("tool_calls"), + Idx(k), + Key("function"), + Key("arguments"), + ], + }); + } + } + } + } + Dialect::Responses => match kind(v) { + Some("response.output_text.delta") => out.push(Field { + lane: Lane::Text(u(v, "output_index") << 32 | u(v, "content_index")), + path: vec![Key("delta")], + }), + Some("response.function_call_arguments.delta") => out.push(Field { + lane: Lane::Args(u(v, "output_index")), + path: vec![Key("delta")], + }), + _ => {} + }, + Dialect::Gemini => { + let Some(parts) = v + .pointer("/candidates/0/content/parts") + .and_then(Value::as_array) + else { + return out; + }; + for (j, p) in parts.iter().enumerate() { + let thought = p.get("thought").and_then(Value::as_bool) == Some(true); + if !thought && p.get("text").is_some_and(Value::is_string) { + out.push(Field { + lane: Lane::Text(0), + path: vec![ + Key("candidates"), + Idx(0), + Key("content"), + Key("parts"), + Idx(j), + Key("text"), + ], + }); + } + } + } + // 从来不是任何一边要还原的流:客户端不说它,桌面版也不接它。 + // 完整的占位符照样由 `walk` 还原 + Dialect::Bedrock => {} + } + out +} + +fn close(d: Dialect, v: &Value) -> Close { + match d { + Dialect::Anthropic => match kind(v) { + Some("content_block_stop") => { + let i = u(v, "index"); + Close::Lanes(vec![Lane::Text(i), Lane::Args(i)]) + } + Some("message_stop") | Some("error") => Close::All, + _ => Close::None, + }, + Dialect::Chat => { + let done = v + .pointer("/choices/0/finish_reason") + .is_some_and(|f| !f.is_null()); + if done { Close::All } else { Close::None } + } + Dialect::Responses => match kind(v) { + Some("response.output_text.done") => Close::Lanes(vec![Lane::Text( + u(v, "output_index") << 32 | u(v, "content_index"), + )]), + Some("response.function_call_arguments.done") => { + Close::Lanes(vec![Lane::Args(u(v, "output_index"))]) + } + Some("response.output_item.done") => Close::Output(u(v, "output_index")), + Some("response.completed") + | Some("response.incomplete") + | Some("response.failed") + | Some("error") => Close::All, + _ => Close::None, + }, + Dialect::Gemini => { + let done = v + .pointer("/candidates/0/finishReason") + .is_some_and(|f| !f.is_null()); + if done { Close::All } else { Close::None } + } + Dialect::Bedrock => Close::None, + } +} + +/// 一路扣住的尾巴补成一帧,形状照着那一路自己的格式。 +fn synth(d: Dialect, lane: Lane, last: &Value, tail: String) -> Synth { + let copy = |keys: &[&str]| { + let mut m = serde_json::Map::new(); + for k in keys { + if let Some(x) = last.get(*k) { + m.insert(k.to_string(), x.clone()); + } + } + m + }; + match (d, lane) { + (Dialect::Anthropic, Lane::Text(i)) => Synth { + event: Some("content_block_delta".into()), + data: json!({ + "type": "content_block_delta", + "index": i, + "delta": { "type": "text_delta", "text": tail }, + }), + }, + (Dialect::Anthropic, Lane::Args(i)) => Synth { + event: Some("content_block_delta".into()), + data: json!({ + "type": "content_block_delta", + "index": i, + "delta": { "type": "input_json_delta", "partial_json": tail }, + }), + }, + (Dialect::Chat, lane) => { + let delta = match lane { + Lane::Text(_) => json!({ "content": tail }), + Lane::Args(i) => json!({ + "tool_calls": [{ "index": i, "function": { "arguments": tail } }], + }), + }; + let mut m = copy(&["id", "object", "created", "model", "system_fingerprint"]); + m.insert( + "choices".into(), + json!([{ "index": 0, "delta": delta, "finish_reason": null }]), + ); + Synth { + event: None, + data: Value::Object(m), + } + } + (Dialect::Responses, Lane::Text(k)) => Synth { + event: Some("response.output_text.delta".into()), + data: json!({ + "type": "response.output_text.delta", + "item_id": last.get("item_id").cloned().unwrap_or(Value::Null), + "output_index": k >> 32, + "content_index": k & 0xffff_ffff, + "delta": tail, + }), + }, + (Dialect::Responses, Lane::Args(oi)) => Synth { + event: Some("response.function_call_arguments.delta".into()), + data: json!({ + "type": "response.function_call_arguments.delta", + "item_id": last.get("item_id").cloned().unwrap_or(Value::Null), + "output_index": oi, + "delta": tail, + }), + }, + (Dialect::Gemini, _) => { + let mut m = copy(&["modelVersion", "responseId"]); + m.insert( + "candidates".into(), + json!([{ "content": { "role": "model", "parts": [{ "text": tail }] }, "index": 0 }]), + ); + Synth { + event: None, + data: Value::Object(m), + } + } + // `fields` 从不给 Bedrock 开路,走不到这里 + (Dialect::Bedrock, _) => Synth { + event: None, + data: Value::String(tail), + }, + } +} + +/// 补帧写成 SSE。 +pub fn write(s: &Synth) -> String { + let data = serde_json::to_string(&s.data).unwrap_or_default(); + match &s.event { + Some(e) => format!("event: {e}\ndata: {data}\n\n"), + None => format!("data: {data}\n\n"), + } +} + +/// 一条 SSE 字节流上的还原器。 +pub struct SseRestorer { + frames: FrameRestorer, + /// 还没收齐的那一帧 + partial: Vec, +} + +impl SseRestorer { + pub fn new(ledger: &Ledger, dialect: Dialect) -> Self { + Self { + frames: FrameRestorer::new(ledger, dialect), + partial: Vec::new(), + } + } + pub fn is_noop(&self) -> bool { + self.frames.is_noop() + } + + pub fn process(&mut self, chunk: &[u8]) -> Vec { + if self.is_noop() { + return chunk.to_vec(); + } + self.partial.extend_from_slice(chunk); + let mut out = Vec::new(); + // 帧之间用空行分隔。**收不齐就等下一块** —— 半帧转发出去, + // 客户端那边会当成一帧解析失败 + while let Some(end) = find_frame_end(&self.partial) { + let frame: Vec = self.partial.drain(..end).collect(); + out.extend_from_slice(&self.rewrite(&frame)); + } + out + } + + /// 流结束了:没收尾的最后一帧照样改写,扣住的尾巴补成帧。 + pub fn flush(&mut self) -> Vec { + let mut out = Vec::new(); + if !self.partial.is_empty() { + let frame: Vec = std::mem::take(&mut self.partial); + out.extend_from_slice(&self.rewrite(&frame)); + } + for s in self.frames.drain() { + out.extend_from_slice(write(&s).as_bytes()); + } + out + } + + /// 改写一帧。**看不懂就原样转发。** + fn rewrite(&mut self, frame: &[u8]) -> Vec { + let Ok(text) = std::str::from_utf8(frame) else { + return frame.to_vec(); + }; + // 多行 `data:` 按规范用换行连起来 + let data: Vec<&str> = text + .split_inclusive('\n') + .filter_map(|l| l.trim_end_matches(['\n', '\r']).strip_prefix("data:")) + .map(|d| d.strip_prefix(' ').unwrap_or(d)) + .collect(); + if data.is_empty() { + return frame.to_vec(); + } + let Ok(mut v) = serde_json::from_str::(&data.join("\n")) else { + // `[DONE]` 这类:流就要结束了,扣住的尾巴得赶在它前面 + let mut out: Vec = self + .frames + .drain() + .iter() + .flat_map(|s| write(s).into_bytes()) + .collect(); + out.extend_from_slice(frame); + return out; + }; + let r = self.frames.frame(&mut v); + let mut out: Vec = r + .before + .iter() + .flat_map(|s| write(s).into_bytes()) + .collect(); + if !r.changed { + out.extend_from_slice(frame); + return out; + } + // 只换 `data:` 那一行,别的行(`event:`、`id:`、注释)原样留着 + let json = serde_json::to_string(&v).unwrap_or_default(); + let mut wrote = false; + for line in text.split_inclusive('\n') { + if line.trim_end_matches(['\n', '\r']).starts_with("data:") { + if !wrote { + out.extend_from_slice(b"data: "); + out.extend_from_slice(json.as_bytes()); + // 把这一行原来的换行接回去 + out.extend_from_slice( + &line.as_bytes()[line.trim_end_matches(['\n', '\r']).len()..], + ); + wrote = true; + } + continue; + } + out.extend_from_slice(line.as_bytes()); + } + out + } +} + +/// 一帧到哪儿结束(含分隔的空行)。 +fn find_frame_end(buf: &[u8]) -> Option { + // `\n\n` 或者 `\r\n\r\n` + buf.windows(2) + .position(|w| w == b"\n\n") + .map(|i| i + 2) + .or_else(|| buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4)) +} + +/// 一条响应流上的还原器,按内容类型分派。 +/// +/// **SSE 和非流式是两件不同的事**:前者的占位符散落在几十帧里,后者 +/// 整个躺在一份 JSON 里。合成一个「通用」的实现只会让两边都做不对 —— +/// 第一版就是那么写的,SSE 那半从来没还原成功过。 +pub enum Body { + Sse(Box), + Whole(crate::redact::stream::ByteRestorer), +} + +impl Body { + pub fn new(ledger: &Ledger, is_sse: bool, dialect: Dialect) -> Self { + if is_sse { + Body::Sse(Box::new(SseRestorer::new(ledger, dialect))) + } else { + Body::Whole(crate::redact::stream::ByteRestorer::new(ledger)) + } + } + pub fn is_noop(&self) -> bool { + match self { + Body::Sse(r) => r.is_noop(), + Body::Whole(r) => r.is_noop(), + } + } + pub fn process(&mut self, chunk: &[u8]) -> Vec { + match self { + Body::Sse(r) => r.process(chunk), + Body::Whole(r) => r.process(chunk), + } + } + pub fn flush(&mut self) -> Vec { + match self { + Body::Sse(r) => r.flush(), + Body::Whole(r) => r.flush(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::redact::replace::{Scheme, redact}; + use crate::redact::rules::RuleSet; + + const KEY: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA"; + + fn ledger() -> Ledger { + redact( + &format!("k={KEY}"), + &RuleSet::only(&["anthropic-api-key"]), + Ledger::new(Scheme::SECRET), + ) + .ledger + } + + fn named(event: &str, v: Value) -> String { + format!("event: {event}\ndata: {v}\n\n") + } + + fn data(v: Value) -> String { + format!("data: {v}\n\n") + } + + fn delta(text: &str) -> String { + delta_at(0, text) + } + + fn delta_at(i: u64, text: &str) -> String { + named( + "content_block_delta", + json!({"type":"content_block_delta","index":i,"delta":{"type":"text_delta","text":text}}), + ) + } + + fn args_at(i: u64, s: &str) -> String { + named( + "content_block_delta", + json!({"type":"content_block_delta","index":i,"delta":{"type":"input_json_delta","partial_json":s}}), + ) + } + + fn stop(i: u64) -> String { + named( + "content_block_stop", + json!({"type":"content_block_stop","index":i}), + ) + } + + fn run(d: Dialect, frames: &[String]) -> String { + let l = ledger(); + let mut r = SseRestorer::new(&l, d); + let mut raw = Vec::new(); + for f in frames { + raw.extend_from_slice(&r.process(f.as_bytes())); + } + raw.extend_from_slice(&r.flush()); + String::from_utf8(raw).unwrap() + } + + fn values(out: &str) -> Vec { + out.lines() + .filter_map(|l| l.strip_prefix("data: ")) + .filter_map(|d| serde_json::from_str::(d).ok()) + .collect() + } + + /// Anthropic:按内容块拼出 (index, 正文, 参数) + fn blocks(out: &str) -> BTreeMap { + let mut m: BTreeMap = BTreeMap::new(); + for v in values(out) { + if v["type"] != "content_block_delta" { + continue; + } + let e = m.entry(v["index"].as_u64().unwrap()).or_default(); + if let Some(s) = v["delta"]["text"].as_str() { + e.0.push_str(s); + } + if let Some(s) = v["delta"]["partial_json"].as_str() { + e.1.push_str(s); + } + } + m + } + + #[test] + fn a_placeholder_spread_over_one_character_per_frame_comes_back_whole() { + // **这是第一版当场失败的那个用例。**模型按 token 吐字,一个 + // 占位符会被切成五到八段 —— 不是边角情况,是常态。 + let frames: Vec = "你的 key 是 <> 对吗" + .chars() + .map(|c| delta(&c.to_string())) + .collect(); + let out = run(Dialect::Anthropic, &frames); + assert_eq!(blocks(&out)[&0].0, format!("你的 key 是 {KEY} 对吗")); + } + + #[test] + fn a_tool_call_argument_is_restored_too() { + // **用户说「把我的 key 写进 .env」的时候,占位符从这里流过去。** + // 不还原的话,客户端真的会把占位符写进文件。 + let frames: Vec = [r#"{"content":"KEY=<>"}"#] + .iter() + .map(|s| args_at(1, s)) + .collect(); + let out = run(Dialect::Anthropic, &frames); + assert_eq!(blocks(&out)[&1].1, format!(r#"{{"content":"KEY={KEY}"}}"#)); + } + + #[test] + fn a_tail_held_at_the_end_of_a_block_stays_in_that_block() { + // 正文块末尾扣住的 `<>"); + let bytes = whole.as_bytes(); + let mid = bytes.len() / 2; + assert!(r.process(&bytes[..mid]).is_empty(), "半帧就发出去了"); + assert!(String::from_utf8_lossy(&r.process(&bytes[mid..])).contains(KEY)); + } + + #[test] + fn frames_we_do_not_understand_pass_through_byte_for_byte() { + // 心跳、ping、没见过的事件类型 —— 「看不懂就重写一下」是在拿 + // 用户的流冒险。 + let l = ledger(); + let mut r = SseRestorer::new(&l, Dialect::Anthropic); + for raw in [ + ": 心跳\n\n", + "event: ping\ndata: {\"type\":\"ping\"}\n\n", + "event: message_start\r\ndata:{\"type\":\"message_start\",\"message\":{\"id\":\"m\"}}\r\n\r\n", + "data: [DONE]\n\n", + ] { + assert_eq!( + String::from_utf8(r.process(raw.as_bytes())).unwrap(), + raw, + "改写了不该改的帧" + ); + } + } + + #[test] + fn a_stream_that_ends_mid_placeholder_still_delivers_the_text() { + // 丢掉它就是丢掉模型说过的字。补一帧比丢字难看得多,但正确。 + let out = run(Dialect::Anthropic, &[delta("结果是 <>"); + assert_eq!(String::from_utf8(r.process(raw.as_bytes())).unwrap(), raw); + } + + #[test] + fn thinking_is_left_exactly_as_the_upstream_signed_it() { + // 改一个字,下一轮请求就被上游拒绝 + let raw = named( + "content_block_delta", + json!({"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"<>"}}), + ); + assert_eq!(run(Dialect::Anthropic, std::slice::from_ref(&raw)), raw); + } + + fn chat(delta: Value, finish: Value) -> String { + data(json!({ + "id":"c1","object":"chat.completion.chunk","created":1,"model":"m", + "choices":[{"index":0,"delta":delta,"finish_reason":finish}], + })) + } + + #[test] + fn a_chat_stream_gets_its_text_and_its_tool_arguments_back() { + let frames = vec![ + chat(json!({"content":"key 是 <>"}), Value::Null), + chat( + json!({"tool_calls":[{"index":0,"id":"t","function":{"name":"write","arguments":"{\"v\":\"<>\"}"}}]}), + Value::Null, + ), + chat(json!({}), json!("tool_calls")), + "data: [DONE]\n\n".to_string(), + ]; + let out = run(Dialect::Chat, &frames); + let vs = values(&out); + let text: String = vs + .iter() + .filter_map(|v| v["choices"][0]["delta"]["content"].as_str()) + .collect(); + let args: String = vs + .iter() + .filter_map(|v| { + v["choices"][0]["delta"]["tool_calls"][0]["function"]["arguments"].as_str() + }) + .collect(); + assert_eq!(text, format!("key 是 {KEY}")); + assert_eq!(args, format!(r#"{{"v":"{KEY}"}}"#)); + } + + #[test] + fn a_chat_tail_is_written_as_a_chat_chunk() { + // 以前补的一律是 Anthropic 的 delta —— Chat 客户端不认识它,那几个字就丢了 + let frames = vec![ + chat(json!({"content":"结果是 <> 吗"}), + ), + ev( + "response.output_text.done", + json!({"type":"response.output_text.done","item_id":"m1","output_index":0,"content_index":0,"text":"是 <> 吗"}), + ), + ev( + "response.function_call_arguments.delta", + json!({"type":"response.function_call_arguments.delta","item_id":"f1","output_index":1,"delta":"{\"k\":\"<>\"}"}), + ), + ev( + "response.function_call_arguments.done", + json!({"type":"response.function_call_arguments.done","item_id":"f1","output_index":1,"arguments":"{\"k\":\"<>\"}"}), + ), + ]; + let out = run(Dialect::Responses, &frames); + let vs = values(&out); + let joined = |t: &str| -> String { + vs.iter() + .filter(|v| v["type"] == t) + .filter_map(|v| v["delta"].as_str()) + .collect() + }; + assert_eq!(joined("response.output_text.delta"), format!("是 {KEY} 吗")); + assert_eq!( + joined("response.function_call_arguments.delta"), + format!(r#"{{"k":"{KEY}"}}"#) + ); + assert!(!out.contains("<>"), "{out}"); + } + + #[test] + fn a_gemini_stream_whose_last_frame_carries_text_and_the_finish() { + let frame = |text: &str, finish: Option<&str>| { + let mut c = json!({"content":{"role":"model","parts":[{"text":text}]},"index":0}); + if let Some(f) = finish { + c["finishReason"] = json!(f); + } + data(json!({"candidates":[c],"modelVersion":"g"})) + }; + let frames = vec![ + frame("key: <> 结束 <>"}}} + ]},"index":0}]})); + let out = run(Dialect::Gemini, &[raw]); + assert!(out.contains(KEY), "{out}"); + } + + #[test] + fn what_gets_replaced_never_carries_a_quote_so_restoring_keeps_json_valid() { + // 整包响应原样放回、不转义,靠的就是这一条:一条跨过引号的自定义规则, + // 换下来的那段止于引号之前 + let rules = RuleSet::none().with_custom("q", r#"id=\S+"#).unwrap(); + let body = r#"{"text":"id=abc\"x"}"#; + let r = redact(body, &rules, Ledger::new(Scheme::SECRET)); + assert!( + r.ledger + .table() + .values() + .all(|v| !v.contains('"') && !v.contains('\\')) + ); + let mut b = Body::new(&r.ledger, false, Dialect::Chat); + let mut out = b.process(r.text.as_bytes()); + out.extend(b.flush()); + assert_eq!(String::from_utf8(out).unwrap(), body); + } +} diff --git a/crates/tw-redact/src/stream.rs b/crates/tw-guard/src/redact/stream.rs similarity index 73% rename from crates/tw-redact/src/stream.rs rename to crates/tw-guard/src/redact/stream.rs index 4004802e..185d17b9 100644 --- a/crates/tw-redact/src/stream.rs +++ b/crates/tw-guard/src/redact/stream.rs @@ -1,11 +1,10 @@ //! 流式还原:占位符被切在两个 chunk 中间时怎么办。 //! -//! 做法和企业版的 `PiiStreamRestorer` 一样:**扣住尾部那段「还可能长成 -//! 占位符」的内容不发**,等下一个 chunk 到了再判断。 +//! **扣住尾部那段「还可能长成占位符」的内容不发**,等下一个 chunk 到了再判断。 //! -//! # 一处必须改掉的地方 +//! # 判据:必须是账本里某个占位符的前缀 //! -//! 企业版的判据是「最右边那个 `{{` 之后没有 `}}` 就全扣住」。照搬到 +//! 企业版最早的判据是「最右边那个 `{{` 之后没有 `}}` 就全扣住」。照搬到 //! `<>` 上会**当场坏掉**: //! //! ```text @@ -13,56 +12,15 @@ //! cat <>` 或者流 -//! 结束 —— 用户看到的是**响应卡住**。而这是个给写代码的人用的网关, -//! 「响应里有 `<<`」不是边角情况,是常态。 +//! `<<` 之后的所有内容会一直扣着,直到某处出现 `>>` 或者流结束 —— 用户看到的 +//! 是**响应卡住**。`{{` 也一样:Jinja、Handlebars、Vue 的模板里到处都是。 //! -//! 所以判据换成:**扣住的那一段必须是占位符的一个合法前缀**。 -//! `<< x` 里 `<<` 后面是空格,一眼就不可能长成 `<>` 也原样过去。扣住的长度因此天然封顶在最长的那个 +//! 占位符上 —— 几十个字节。 -use crate::redact::{CLOSE, Ledger, OPEN}; - -/// 扣住的字节数上限。`<>`,几十字节封顶。 -const MAX_HOLD: usize = 48; - -/// `tail` 有没有可能是某个占位符的开头。 -/// -/// 文法就是 `<>`。 -fn viable_prefix(tail: &[u8]) -> bool { - if tail.len() > MAX_HOLD { - return false; - } - let open = OPEN.as_bytes(); - let close = CLOSE.as_bytes(); - // 还在 `<` 或者 `>>` - let after = &rest[digits..]; - digits > 0 && after.len() < close.len() && after == &close[..after.len()] -} - -/// 从哪个字节开始必须扣住。返回 `buf.len()` 表示全都能发。 -fn hold_from(buf: &[u8]) -> usize { - let window = buf.len().saturating_sub(MAX_HOLD); - for p in window..buf.len() { - if buf[p] == b'<' && viable_prefix(&buf[p..]) { - return p; - } - } - buf.len() -} +use crate::redact::replace::Ledger; /// 一条流上的还原器。 /// @@ -70,13 +28,22 @@ fn hold_from(buf: &[u8]) -> usize { /// 还原的结果。**顺序和内容都不变,唯一的差别是有些字节晚几毫秒发出去。 pub struct Restorer { table: std::collections::HashMap, + /// 占位符开头的第一个字节。先按它筛,再比前缀 + lead: u8, + open: &'static str, + /// 最长的占位符有多长:扣住的永远不会比它更多 + longest: usize, buffer: String, } impl Restorer { pub fn new(ledger: &Ledger) -> Self { + let open = ledger.scheme().open; Self { table: ledger.table().clone(), + lead: open.as_bytes()[0], + open, + longest: ledger.table().keys().map(String::len).max().unwrap_or(0), buffer: String::new(), } } @@ -93,7 +60,7 @@ impl Restorer { return next.to_string(); } self.buffer.push_str(next); - let cut = hold_from(self.buffer.as_bytes()); + let cut = self.hold_from(); if cut == 0 { return String::new(); } @@ -104,8 +71,8 @@ impl Restorer { /// 流结束了,把扣住的那点吐出来。 /// - /// **残留的半截原样发出去。**一个到流末尾都没收尾的 `< String { if self.buffer.is_empty() { return String::new(); @@ -123,8 +90,30 @@ impl Restorer { self.restore(s) } + /// 从哪个字节开始必须扣住。返回 `buffer.len()` 表示全都能发。 + /// + /// 切点总落在占位符开头那个 ASCII 字节上,所以一定是字符边界。 + fn hold_from(&self) -> usize { + let buf = self.buffer.as_bytes(); + let window = buf.len().saturating_sub(self.longest); + for p in window..buf.len() { + if buf[p] != self.lead { + continue; + } + let tail = &buf[p..]; + if self + .table + .keys() + .any(|k| k.len() > tail.len() && k.as_bytes().starts_with(tail)) + { + return p; + } + } + buf.len() + } + fn restore(&self, s: &str) -> String { - if !s.contains(OPEN) { + if !s.contains(self.open) { return s.to_string(); } let mut out = s.to_string(); @@ -193,13 +182,18 @@ impl ByteRestorer { #[cfg(test)] mod tests { use super::*; - use crate::redact::redact; - use crate::rules::RuleSet; + use crate::redact::replace::{Scheme, redact}; + use crate::redact::rules::RuleSet; const KEY: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA"; fn ledger() -> Ledger { - redact(&format!("k={KEY}"), &RuleSet::only(&["anthropic-api-key"])).ledger + redact( + &format!("k={KEY}"), + &RuleSet::only(&["anthropic-api-key"]), + Ledger::new(Scheme::SECRET), + ) + .ledger } /// 把一段内容按给定的切法喂进去,返回客户端最终看到的东西。 @@ -231,9 +225,8 @@ mod tests { #[test] fn cpp_stream_operators_do_not_stall_the_stream() { - // **企业版的判据在这里当场坏掉。**按「最右边的 `<<` 之后没有 - // `>>` 就全扣住」,下面这段会一直卡到流结束。而这是个给写代码的 - // 人用的网关 —— 「响应里有 `<<`」不是边角情况,是常态。 + // **「最右边的 `<<` 之后没有 `>>` 就全扣住」在这里当场坏掉**:下面 + // 这段会一直卡到流结束。而「响应里有 `<<`」不是边角情况,是常态。 let l = ledger(); let mut r = Restorer::new(&l); let out = r.process("std::cout << x << std::endl;"); @@ -270,7 +263,7 @@ mod tests { // 唯一的差别只是有些字节晚几毫秒发出去。 let text = "开头 <> 中间 a << b 结尾 <>"; let l = ledger(); - let want = crate::redact::restore(text, &l); + let want = crate::redact::replace::restore(text, &l); for size in 1..=text.len().min(40) { let mut chunks = Vec::new(); let mut rest = text; @@ -296,22 +289,49 @@ mod tests { #[test] fn nothing_is_ever_held_for_long() { - // 就算判据写漏了,扣住的也永远是几十个字节 —— 而不是整条响应。 + // 扣住的永远不比最长的那个占位符长 —— 而不是整条响应。 let l = ledger(); let mut r = Restorer::new(&l); let long = format!("<= long.len() - MAX_HOLD, + out.len() >= long.len() - "<>".len(), "扣住了 {} 个字节", long.len() - out.len() ); } + #[test] + fn a_placeholder_nobody_issued_is_not_waited_for() { + // 模型自己编的 `<>` 不在账本里,没有还原的可能,也就 + // 没有等的理由 + let l = ledger(); + let mut r = Restorer::new(&l); + assert_eq!(r.process("看 <> 原样过去"), @@ -358,13 +378,18 @@ mod tests { #[cfg(test)] mod byte_tests { use super::*; - use crate::redact::redact; - use crate::rules::RuleSet; + use crate::redact::replace::{Scheme, redact}; + use crate::redact::rules::RuleSet; const KEY: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA"; fn ledger() -> Ledger { - redact(&format!("k={KEY}"), &RuleSet::only(&["anthropic-api-key"])).ledger + redact( + &format!("k={KEY}"), + &RuleSet::only(&["anthropic-api-key"]), + Ledger::new(Scheme::SECRET), + ) + .ledger } fn feed_bytes(chunks: &[&[u8]]) -> String { @@ -413,7 +438,7 @@ mod byte_tests { #[test] fn a_stream_with_nothing_to_restore_is_copied_straight_through() { - let mut r = ByteRestorer::new(&Ledger::default()); + let mut r = ByteRestorer::new(&Ledger::new(Scheme::SECRET)); assert!(r.is_noop()); let raw = &[0xff, 0xfe, 0x00][..]; assert_eq!(r.process(raw), raw.to_vec(), "二进制体也该原样过去"); diff --git a/crates/tw-guard/src/tools/mod.rs b/crates/tw-guard/src/tools/mod.rs new file mode 100644 index 00000000..10c891e6 --- /dev/null +++ b/crates/tw-guard/src/tools/mod.rs @@ -0,0 +1,4 @@ +//! 工具调用审查:上游返回的工具调用过一遍规则,高危的可以在那一帧上切断。 + +pub mod rules; +pub mod wall; diff --git a/crates/tw-scan/src/rules.rs b/crates/tw-guard/src/tools/rules.rs similarity index 71% rename from crates/tw-scan/src/rules.rs rename to crates/tw-guard/src/tools/rules.rs index 8d2ef846..5e7c3053 100644 --- a/crates/tw-scan/src/rules.rs +++ b/crates/tw-guard/src/tools/rules.rs @@ -1,13 +1,16 @@ -//! 规则集。 +//! 工具调用审查和客户端配置扫描用的规则。 //! -//! 内置那一份编译进二进制(tw-config 的 `data/rules.yaml`:`config.yaml` 按 id -//! 引用其中的规则,校验要认得出),两处在用: +//! 内置那一份编译进二进制(`data/rules.yaml`),分两组:`injection`(提示注入) +//! 和 `dangerous`(危险命令)。两处在用: //! //! - **客户端配置扫描**用全部内置规则([`scan_rules`]),不受用户改动影响。 //! 安全页上的规则只作用于经过网关的请求 —— 两件事各管各的,用户在那边 //! 停用一条误报,不该让这边悄悄少查一样东西。 -//! - **工具调用审查**只用「危险命令」那一组([`tool_rules`]),用户可以逐条 -//! 停用、再加自己的,写在 `config.yaml` 的 `security.inspect_tools` 里。 +//! - **工具调用审查**只用「危险命令」那一组([`tool_rules`]),调用方可以逐条 +//! 停用、改处置、再加自己的。 +//! +//! **这里不认识任何一边的配置格式。**桌面版的 `config.yaml`、企业版的系统设置, +//! 各自把自己那份翻译成 [`tool_rules`] 的参数。 //! //! # 为什么是加法加停用,不是整份替换 //! @@ -25,7 +28,7 @@ use regex::Regex; use serde::{Deserialize, Serialize}; /// 编译进二进制的那一份。 -pub const BUILTIN: &str = tw_config::BUILTIN_RULES; +pub const BUILTIN: &str = include_str!("../../data/rules.yaml"); #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -103,13 +106,10 @@ pub fn builtin() -> &'static RuleFile { } fn compile(spec: &RuleSpec, group: &'static str, custom: bool) -> Result { - let re = regex::RegexBuilder::new(&spec.pattern) - .size_limit(1 << 20) - .build() - .map_err(|e| RuleError::BadPattern { - name: spec.id.clone(), - detail: e.to_string(), - })?; + let re = crate::bounded(&spec.pattern).map_err(|e| RuleError::BadPattern { + name: spec.id.clone(), + detail: e.to_string(), + })?; Ok(Rule { id: spec.id.clone(), name: spec.name.clone(), @@ -135,85 +135,79 @@ pub fn scan_rules() -> Rules { Rules { rules } } -/// 工具调用审查用的:内置的危险命令规则,按用户的启停过一遍,再加上启用着 -/// 的自定义规则。 +/// 调用方自己加的一条工具调用审查规则。 +#[derive(Debug, Clone, Copy)] +pub struct Custom<'a> { + pub name: &'a str, + pub pattern: &'a str, + /// 拦截档下切断,还是只记录 + pub cut: bool, +} + +/// 工具调用审查用的:内置的危险命令规则,去掉停用的、按调用方改过的处置走, +/// 再加上调用方自己的规则。 +/// +/// `cut` 答「这条内置规则在拦截档下切不切」:`None` 是没改过,按出厂。 /// -/// 自定义规则的正则在配置校验时已经编过一次;这里再编失败只可能是有人绕过 -/// 了校验,照样当错误返回,不静默跳过。 -pub fn tool_rules(p: &tw_config::ToolPolicy) -> Result { +/// 自定义规则的正则写错了就当错误返回,不静默跳过 —— 静默跳过的表现是 +/// 「我明明加了这条规则,它怎么从来不报」。 +pub fn tool_rules<'a>( + disable: &[String], + cut: impl Fn(&str) -> Option, + custom: impl IntoIterator>, +) -> Result { let f = builtin(); let mut rules = Vec::new(); for s in &f.dangerous { - if p.disable.contains(&s.id) { + if disable.contains(&s.id) { continue; } - rules.push(with_action(compile(s, "dangerous", false)?, p)); + let mut rule = compile(s, "dangerous", false)?; + if let Some(c) = cut(&rule.id) { + rule.high = c; + } + rules.push(rule); } - for c in p.custom.iter().filter(|c| !c.disabled) { - let spec = RuleSpec { - id: c.name.clone(), - name: c.name.clone(), - pattern: c.pattern.clone(), - why: String::new(), - level: Some( - match c.action { - tw_config::ToolAction::Cut => "high", - tw_config::ToolAction::Record => "medium", - } - .to_string(), - ), - }; - rules.push(compile(&spec, "dangerous", true)?); + for c in custom { + rules.push(custom_rule(c)?); } Ok(Rules { rules }) } -/// 只有这一条正则的规则集。界面上新建规则时「测试」用它。 -pub fn single(name: &str, pattern: &str, high: bool) -> Result { - let spec = RuleSpec { - id: name.to_string(), - name: name.to_string(), - pattern: pattern.to_string(), - why: String::new(), - level: Some(if high { "high" } else { "medium" }.to_string()), - }; - if pattern.is_empty() { +fn custom_rule(c: Custom<'_>) -> Result { + if c.pattern.is_empty() { return Err(RuleError::BadPattern { - name: name.to_string(), + name: c.name.to_string(), detail: "the pattern is empty".to_string(), }); } + let spec = RuleSpec { + id: c.name.to_string(), + name: c.name.to_string(), + pattern: c.pattern.to_string(), + why: String::new(), + level: Some(if c.cut { "high" } else { "medium" }.to_string()), + }; + compile(&spec, "dangerous", true) +} + +/// 只有这一条正则的规则集。界面上新建规则时「测试」用它。 +pub fn single(name: &str, pattern: &str, cut: bool) -> Result { Ok(Rules { - rules: vec![compile(&spec, "dangerous", true)?], + rules: vec![custom_rule(Custom { name, pattern, cut })?], }) } /// 只有一条内置的危险命令规则。**不管它启用没有** —— 安全页上要能试一条 -/// 停用着的规则,再决定开不开。处置按用户设的来。不是内置规则的 id 返回 -/// `None`。 -pub fn one_builtin(id: &str, p: &tw_config::ToolPolicy) -> Option { +/// 停用着的规则,再决定开不开。`cut` 同 [`tool_rules`]。不是内置规则的 id +/// 返回 `None`。 +pub fn one_builtin(id: &str, cut: Option) -> Option { let spec = builtin().dangerous.iter().find(|s| s.id == id)?; - let rule = compile(spec, "dangerous", false).expect("the built-in patterns compile"); - Some(Rules { - rules: vec![with_action(rule, p)], - }) -} - -/// 用户改过这条内置规则在拦截档下做什么的话,按改过的来。 -fn with_action(mut rule: Rule, p: &tw_config::ToolPolicy) -> Rule { - if let Some(a) = p.actions.get(&rule.id) { - rule.high = *a == tw_config::ToolAction::Cut; - } - rule -} - -/// 一条内置规则出厂时在拦截档下做什么。 -pub fn factory_action(spec: &RuleSpec) -> tw_config::ToolAction { - if spec.high() { - tw_config::ToolAction::Cut - } else { - tw_config::ToolAction::Record + let mut rule = compile(spec, "dangerous", false).expect("the built-in patterns compile"); + if let Some(c) = cut { + rule.high = c; } + Some(Rules { rules: vec![rule] }) } #[cfg(test)] @@ -230,31 +224,11 @@ mod tests { let rs = r(); assert!(rs.rules.len() >= 12, "只有 {} 条", rs.rules.len()); assert!( - tool_rules(&Default::default()).unwrap().rules.len() >= 10, + tool_rules(&[], |_| None, []).unwrap().rules.len() >= 10, "工具调用审查的内置规则少了" ); } - #[test] - fn a_built_in_rule_does_what_the_user_set_on_enforce() { - let p = tw_config::ToolPolicy { - actions: [ - ("rm-rf-root".to_string(), tw_config::ToolAction::Cut), - ("curl-pipe-sh".to_string(), tw_config::ToolAction::Record), - ] - .into(), - ..Default::default() - }; - let rs = tool_rules(&p).unwrap(); - let high = |id: &str| rs.rules.iter().find(|r| r.id == id).unwrap().high; - assert!(high("rm-rf-root")); - assert!(!high("curl-pipe-sh")); - // 没改的照出厂 - assert!(high("base64-decode-exec")); - // 只试一条的时候也按改过的来 - assert!(one_builtin("rm-rf-root", &p).unwrap().rules[0].high); - } - #[test] fn every_rule_has_a_name_and_says_why_it_matters() { // 没有这一句,一条命中就只是个规则 id —— 用户看不出该不该管它。 @@ -407,75 +381,74 @@ mod tests { #[test] fn tool_call_inspection_uses_only_the_command_rules() { // 一个写文档的工具调用里出现「忽略以上指令」是完全正常的 - let rs = tool_rules(&Default::default()).unwrap(); + let rs = tool_rules(&[], |_| None, []).unwrap(); assert!(rs.rules.iter().all(|x| x.group == "dangerous")); assert!(!rs.rules.iter().any(|x| x.id == "ignore-previous")); } - fn policy( - disable: &[&str], - custom: &[(&str, &str, tw_config::ToolAction)], - ) -> tw_config::ToolPolicy { - tw_config::ToolPolicy { - disable: disable.iter().map(|s| s.to_string()).collect(), - custom: custom - .iter() - .map(|(n, p, a)| tw_config::CustomToolRule { - name: n.to_string(), - pattern: p.to_string(), - action: *a, - disabled: false, - }) - .collect(), - ..Default::default() - } + #[test] + fn a_built_in_rule_does_what_the_caller_set_on_enforce() { + let cut = |id: &str| match id { + "rm-rf-root" => Some(true), + "curl-pipe-sh" => Some(false), + _ => None, + }; + let rs = tool_rules(&[], cut, []).unwrap(); + let high = |id: &str| rs.rules.iter().find(|r| r.id == id).unwrap().high; + assert!(high("rm-rf-root")); + assert!(!high("curl-pipe-sh")); + // 没改的照出厂 + assert!(high("base64-decode-exec")); + // 只试一条的时候也按改过的来 + assert!(one_builtin("rm-rf-root", Some(true)).unwrap().rules[0].high); + assert!(!one_builtin("rm-rf-root", None).unwrap().rules[0].high); } #[test] - fn a_user_rule_is_added_on_top_of_the_builtin_ones() { + fn a_callers_rule_is_added_on_top_of_the_builtin_ones() { // **加法,不是替换。**替换会让用户那份永远停在复制的那一刻, // 我们后来加的每一条新攻击模式都到不了他机器上。 - let n = tool_rules(&Default::default()).unwrap().rules.len(); - let rs = tool_rules(&policy( - &[], - &[( - "删除集群资源", - r"kubectl\s+delete", - tw_config::ToolAction::Cut, - )], - )) - .unwrap(); + let n = tool_rules(&[], |_| None, []).unwrap().rules.len(); + let mine = Custom { + name: "删除集群资源", + pattern: r"kubectl\s+delete", + cut: true, + }; + let rs = tool_rules(&[], |_| None, [mine]).unwrap(); assert_eq!(rs.rules.len(), n + 1, "内置那些被顶掉了"); - let mine = rs.rules.iter().find(|x| x.id == "删除集群资源").unwrap(); - assert!(mine.custom, "界面上要分得开哪些是用户加的"); - assert!(mine.high, "写明了切断却没有切断"); - assert!(mine.re.is_match("kubectl delete ns prod")); - } + let r = rs.rules.iter().find(|x| x.id == "删除集群资源").unwrap(); + assert!(r.custom, "界面上要分得开哪些是用户加的"); + assert!(r.high, "写明了切断却没有切断"); + assert!(r.re.is_match("kubectl delete ns prod")); - #[test] - fn a_user_rule_that_does_not_say_cut_only_records() { - let rs = tool_rules(&policy( - &[], - &[("我的", "zzz", tw_config::ToolAction::Record)], - )) - .unwrap(); - assert!(!rs.rules.iter().find(|x| x.id == "我的").unwrap().high); + let record = Custom { cut: false, ..mine }; + let rs = tool_rules(&[], |_| None, [record]).unwrap(); + assert!( + !rs.rules + .iter() + .find(|x| x.id == "删除集群资源") + .unwrap() + .high + ); } #[test] fn a_builtin_rule_can_be_switched_off_by_id() { - let rs = tool_rules(&policy(&["chmod-777"], &[])).unwrap(); + let rs = tool_rules(&["chmod-777".to_string()], |_| None, []).unwrap(); assert!(!rs.rules.iter().any(|x| x.id == "chmod-777")); // 别的照常在 assert!(rs.rules.iter().any(|x| x.id == "curl-pipe-sh")); } #[test] - fn a_disabled_user_rule_stays_out() { - let mut p = policy(&[], &[("我的", "zzz", tw_config::ToolAction::Cut)]); - p.custom[0].disabled = true; - let rs = tool_rules(&p).unwrap(); - assert!(!rs.rules.iter().any(|x| x.id == "我的")); + fn a_callers_rule_with_a_broken_pattern_is_an_error_not_a_silent_skip() { + let bad = Custom { + name: "坏的", + pattern: "(", + cut: true, + }; + assert!(tool_rules(&[], |_| None, [bad]).is_err()); + assert!(single("空的", "", true).is_err()); } #[test] @@ -488,7 +461,7 @@ mod tests { #[test] fn there_is_no_second_config_file() { // `config.yaml` 是唯一的配置文件。规则不从磁盘上别的地方读。 - let src = std::fs::read_to_string("src/rules.rs").unwrap(); + let src = std::fs::read_to_string("src/tools/rules.rs").unwrap(); let code = src.split("#[cfg(test)]").next().unwrap(); assert!(!code.contains("scan-rules.yaml"), "又冒出一个配置文件"); assert!(!code.contains("read_to_string"), "规则不该再从磁盘上读"); diff --git a/crates/tw-gateway/src/toolwall.rs b/crates/tw-guard/src/tools/wall.rs similarity index 99% rename from crates/tw-gateway/src/toolwall.rs rename to crates/tw-guard/src/tools/wall.rs index b883d12c..7e441d0f 100644 --- a/crates/tw-gateway/src/toolwall.rs +++ b/crates/tw-guard/src/tools/wall.rs @@ -47,8 +47,8 @@ use std::collections::HashMap; use std::sync::Arc; +use crate::tools::rules::Rules; use serde_json::Value; -use tw_scan::rules::Rules; /// 命中了什么。 #[derive(Debug, Clone)] @@ -671,7 +671,7 @@ mod tests { use super::*; fn rules() -> Arc { - Arc::new(tw_scan::rules::tool_rules(&Default::default()).unwrap()) + Arc::new(crate::tools::rules::tool_rules(&[], |_| None, []).unwrap()) } fn start(index: u64, name: &str) -> String { diff --git a/crates/tw-redact/src/lib.rs b/crates/tw-redact/src/lib.rs deleted file mode 100644 index 0daa85fc..00000000 --- a/crates/tw-redact/src/lib.rs +++ /dev/null @@ -1,4 +0,0 @@ -pub mod redact; -pub mod rules; -pub mod sse; -pub mod stream; diff --git a/crates/tw-redact/src/sse.rs b/crates/tw-redact/src/sse.rs deleted file mode 100644 index aa4b5465..00000000 --- a/crates/tw-redact/src/sse.rs +++ /dev/null @@ -1,408 +0,0 @@ -//! 在 SSE 流里把占位符换回来。 -//! -//! # 为什么不能在原始字节上做 -//! -//! 第一版是在字节流上找占位符的,写完一测就发现它**根本不可能对**: -//! -//! ```text -//! data: {"delta":{"text":"<<"}} -//! data: {"delta":{"text":"TW_SEC"}} -//! data: {"delta":{"text":"RET_1>>"}} -//! ``` -//! -//! 占位符在**解码后的正文里**是连续的,在线路上不是 —— 中间隔着 -//! `"}}\n\ndata: {"delta":{"text":"`。模型按 token 吐字,一个 -//! `<>` 会被切成五到八段,这不是边角情况,是常态。 -//! -//! 企业版的 `PiiStreamRestorer` 之所以没这个问题,是因为它拿到的本来就是 -//! 解码后的 content —— 那个网关无论如何都要做协议转换。我们是直通的, -//! 所以这一层得自己拆帧。 -//! -//! # 做法 -//! -//! 拆出每一帧,找到装正文的那个字段,解码 → 喂给 -//! [`crate::stream::Restorer`] → 把它吐出来的那段写回去。扣住的尾巴跨帧 -//! 攒着,下一帧的正文接在它后面。 -//! -//! **不认识的帧原样转发。**心跳、`ping`、我们没见过的事件类型 —— 这条 -//! 路上任何「看不懂就重写一下」的行为都是在拿用户的流冒险。 - -use serde_json::Value; - -use crate::redact::Ledger; -use crate::stream::Restorer; - -/// 正文可能挂在哪几个字段上。**按方言列,不是猜。** -/// -/// `partial_json` 那一条尤其要紧:它是工具调用参数的分片。用户说 -/// 「把我的 key 写进 .env」时,占位符会从这里流过去 —— 不还原的话, -/// 客户端真的会把 `<>` 写进文件。 -const TEXT_PATHS: &[&[&str]] = &[ - // Anthropic - &["delta", "text"], - &["delta", "partial_json"], - &["content_block", "text"], - // OpenAI chat - &["choices", "0", "delta", "content"], - // Gemini - &["candidates", "0", "content", "parts", "0", "text"], -]; - -fn get_mut<'a>(v: &'a mut Value, path: &[&str]) -> Option<&'a mut Value> { - let mut cur = v; - for k in path { - cur = match cur { - Value::Object(m) => m.get_mut(*k)?, - Value::Array(a) => a.get_mut(k.parse::().ok()?)?, - _ => return None, - }; - } - Some(cur) -} - -/// 一条 SSE 流上的还原器。 -pub struct SseRestorer { - inner: Restorer, - /// 还没收齐的那一帧 - partial: Vec, - /// 最后见过的 `index`,补帧时要带上 - last_index: Option, - /// 补出来的那一帧是文本还是工具参数 - last_delta_type: Option, -} - -impl SseRestorer { - pub fn new(ledger: &Ledger) -> Self { - Self { - inner: Restorer::new(ledger), - partial: Vec::new(), - last_index: None, - last_delta_type: None, - } - } - pub fn is_noop(&self) -> bool { - self.inner.is_noop() - } - - pub fn process(&mut self, chunk: &[u8]) -> Vec { - if self.is_noop() { - return chunk.to_vec(); - } - self.partial.extend_from_slice(chunk); - let mut out = Vec::new(); - // 帧之间用空行分隔。**收不齐就等下一块** —— 半帧转发出去, - // 客户端那边会当成一帧解析失败 - while let Some(end) = find_frame_end(&self.partial) { - let frame: Vec = self.partial.drain(..end).collect(); - out.extend_from_slice(&self.rewrite(&frame)); - } - out - } - - /// 流结束了。 - /// - /// **扣住的尾巴要补一帧发出去。**丢掉它就是丢掉模型说过的字,而 - /// 那比多一帧难看得多。 - pub fn flush(&mut self) -> Vec { - let mut out = Vec::new(); - if !self.partial.is_empty() { - let frame: Vec = std::mem::take(&mut self.partial); - out.extend_from_slice(&self.rewrite(&frame)); - } - let tail = self.inner.flush(); - if !tail.is_empty() { - out.extend_from_slice(self.synth(&tail).as_bytes()); - } - out - } - - /// 补一帧,把扣住的尾巴装进去。 - fn synth(&self, text: &str) -> String { - let index = self.last_index.unwrap_or(0); - let dt = self.last_delta_type.as_deref().unwrap_or("text_delta"); - let field = if dt == "input_json_delta" { - "partial_json" - } else { - "text" - }; - format!( - "event: content_block_delta\ndata: {{\"type\":\"content_block_delta\",\"index\":{index},\"delta\":{{\"type\":\"{dt}\",\"{field}\":{}}}}}\n\n", - serde_json::to_string(text).unwrap_or_else(|_| "\"\"".into()) - ) - } - - /// 改写一帧。**看不懂就原样转发。** - fn rewrite(&mut self, frame: &[u8]) -> Vec { - let Ok(text) = std::str::from_utf8(frame) else { - return frame.to_vec(); - }; - let mut out = String::with_capacity(text.len()); - let mut touched = false; - for line in text.split_inclusive('\n') { - let Some(payload) = line.strip_prefix("data: ") else { - out.push_str(line); - continue; - }; - let trimmed = payload.trim_end_matches(['\n', '\r']); - let Ok(mut v) = serde_json::from_str::(trimmed) else { - out.push_str(line); - continue; - }; - // 记住 index 和 delta 类型,补帧时要用 - if let Some(i) = v.get("index").and_then(|x| x.as_u64()) { - self.last_index = Some(i); - } - if let Some(t) = v - .get("delta") - .and_then(|d| d.get("type")) - .and_then(|x| x.as_str()) - { - self.last_delta_type = Some(t.to_string()); - } - let mut hit = false; - for path in TEXT_PATHS { - let Some(slot) = get_mut(&mut v, path) else { - continue; - }; - let Some(s) = slot.as_str() else { continue }; - *slot = Value::String(self.inner.process(s)); - hit = true; - break; - } - if !hit { - out.push_str(line); - continue; - } - touched = true; - out.push_str("data: "); - out.push_str(&serde_json::to_string(&v).unwrap_or_else(|_| trimmed.to_string())); - // 把 trim 掉的换行原样接回去 - out.push_str(&payload[trimmed.len()..]); - } - if touched { - out.into_bytes() - } else { - frame.to_vec() - } - } -} - -/// 一帧到哪儿结束(含分隔的空行)。 -fn find_frame_end(buf: &[u8]) -> Option { - // `\n\n` 或者 `\r\n\r\n` - buf.windows(2) - .position(|w| w == b"\n\n") - .map(|i| i + 2) - .or_else(|| buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4)) -} - -/// 一条响应流上的还原器,按内容类型分派。 -/// -/// **SSE 和非流式是两件不同的事**:前者的占位符散落在几十帧里,后者 -/// 整个躺在一份 JSON 里。合成一个「通用」的实现只会让两边都做不对 —— -/// 第一版就是那么写的,SSE 那半从来没还原成功过。 -pub enum Body { - Sse(SseRestorer), - Whole(crate::stream::ByteRestorer), -} - -impl Body { - pub fn new(ledger: &Ledger, is_sse: bool) -> Self { - if is_sse { - Body::Sse(SseRestorer::new(ledger)) - } else { - Body::Whole(crate::stream::ByteRestorer::new(ledger)) - } - } - pub fn is_noop(&self) -> bool { - match self { - Body::Sse(r) => r.is_noop(), - Body::Whole(r) => r.is_noop(), - } - } - pub fn process(&mut self, chunk: &[u8]) -> Vec { - match self { - Body::Sse(r) => r.process(chunk), - Body::Whole(r) => r.process(chunk), - } - } - pub fn flush(&mut self) -> Vec { - match self { - Body::Sse(r) => r.flush(), - Body::Whole(r) => r.flush(), - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::redact::redact; - use crate::rules::RuleSet; - - const KEY: &str = "sk-ant-api03-AAAAAAAAAAAAAAAAAAAAAAAAAA"; - - fn ledger() -> Ledger { - redact(&format!("k={KEY}"), &RuleSet::only(&["anthropic-api-key"])).ledger - } - - fn delta(text: &str) -> String { - format!( - "event: content_block_delta\ndata: {{\"type\":\"content_block_delta\",\"index\":0,\"delta\":{{\"type\":\"text_delta\",\"text\":{}}}}}\n\n", - serde_json::to_string(text).unwrap() - ) - } - - /// 把帧喂进去,返回客户端最终看到的正文(把所有 text 拼起来)。 - fn text_out(frames: &[String]) -> String { - let l = ledger(); - let mut r = SseRestorer::new(&l); - let mut raw = Vec::new(); - for f in frames { - raw.extend_from_slice(&r.process(f.as_bytes())); - } - raw.extend_from_slice(&r.flush()); - let s = String::from_utf8(raw).unwrap(); - s.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() - .or_else(|| v["delta"]["partial_json"].as_str()) - .map(|s| s.to_string()) - }) - .collect() - } - - #[test] - fn a_placeholder_spread_over_one_character_per_frame_comes_back_whole() { - // **这是第一版当场失败的那个用例。**模型按 token 吐字,一个 - // `<>` 会被切成五到八段 —— 不是边角情况,是常态。 - let frames: Vec = "你的 key 是 <> 对吗" - .chars() - .map(|c| delta(&c.to_string())) - .collect(); - assert_eq!(text_out(&frames), format!("你的 key 是 {KEY} 对吗")); - } - - #[test] - fn a_realistic_token_split_comes_back_whole() { - let frames: Vec = [ - "你的 key 是 <<", - "TW_", - "SECRET", - "_1", - ">>", - ",看起来没问题", - ] - .iter() - .map(|s| delta(s)) - .collect(); - assert_eq!( - text_out(&frames), - format!("你的 key 是 {KEY},看起来没问题") - ); - } - - #[test] - fn a_tool_call_argument_is_restored_too() { - // **用户说「把我的 key 写进 .env」的时候,占位符从这里流过去。** - // 不还原的话,客户端真的会把 `<>` 写进文件。 - let f = |s: &str| { - format!( - "event: content_block_delta\ndata: {{\"type\":\"content_block_delta\",\"index\":1,\"delta\":{{\"type\":\"input_json_delta\",\"partial_json\":{}}}}}\n\n", - serde_json::to_string(s).unwrap() - ) - }; - let frames: Vec = [r#"{"content":"KEY=<>"}"#] - .iter() - .map(|s| f(s)) - .collect(); - assert_eq!(text_out(&frames), format!(r#"{{"content":"KEY={KEY}"}}"#)); - } - - #[test] - fn frames_that_arrive_in_pieces_are_not_forwarded_half_written() { - // 半帧转发出去,客户端那边会当成一帧解析失败。 - let l = ledger(); - let mut r = SseRestorer::new(&l); - let whole = delta("<>"); - let bytes = whole.as_bytes(); - let mid = bytes.len() / 2; - let first = r.process(&bytes[..mid]); - assert!( - first.is_empty(), - "半帧就发出去了:{:?}", - String::from_utf8_lossy(&first) - ); - let rest = r.process(&bytes[mid..]); - assert!(String::from_utf8_lossy(&rest).contains(KEY)); - } - - #[test] - fn frames_we_do_not_understand_pass_through_byte_for_byte() { - // 心跳、ping、没见过的事件类型 —— 「看不懂就重写一下」是在拿 - // 用户的流冒险。 - let l = ledger(); - let mut r = SseRestorer::new(&l); - for raw in [ - ": 心跳\n\n", - "event: ping\ndata: {\"type\":\"ping\"}\n\n", - "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"m\"}}\n\n", - "data: [DONE]\n\n", - ] { - assert_eq!( - String::from_utf8(r.process(raw.as_bytes())).unwrap(), - raw, - "改写了不该改的帧" - ); - } - } - - #[test] - fn a_stream_that_ends_mid_placeholder_still_delivers_the_text() { - // 丢掉它就是丢掉模型说过的字。补一帧比丢字难看得多,但正确。 - let frames = vec![delta("结果是 <>"); - assert_eq!(String::from_utf8(r.process(raw.as_bytes())).unwrap(), raw); - } - - #[test] - fn the_openai_shape_works_too() { - let f = |s: &str| { - format!( - "data: {{\"choices\":[{{\"delta\":{{\"content\":{}}}}}]}}\n\n", - serde_json::to_string(s).unwrap() - ) - }; - let l = ledger(); - let mut r = SseRestorer::new(&l); - let mut out = Vec::new(); - for s in ["key 是 <>"] { - out.extend_from_slice(&r.process(f(s).as_bytes())); - } - out.extend_from_slice(&r.flush()); - assert!(String::from_utf8(out).unwrap().contains(KEY)); - } -} diff --git a/crates/tw-resil/Cargo.toml b/crates/tw-resil/Cargo.toml deleted file mode 100644 index 8b9a8fdd..00000000 --- a/crates/tw-resil/Cargo.toml +++ /dev/null @@ -1,16 +0,0 @@ -[package] -name = "tw-resil" -version.workspace = true -edition.workspace = true -rust-version.workspace = true -license.workspace = true -repository.workspace = true -description = "Retries, circuit breaking, and failover" - -[dependencies] -tw-types = { workspace = true } -futures = { workspace = true } -tokio = { workspace = true } -tracing = { workspace = true } -metrics = { workspace = true } -rand = { workspace = true } diff --git a/crates/tw-resil/src/cb_registry.rs b/crates/tw-resil/src/cb_registry.rs deleted file mode 100644 index 2d2e7101..00000000 --- a/crates/tw-resil/src/cb_registry.rs +++ /dev/null @@ -1,194 +0,0 @@ -//! Process-wide circuit-breaker state registry. -//! -//! Both the AI gateway (`think-watch-gateway`) and the MCP gateway -//! (`think-watch-mcp-gateway`) write into this shared map every time a -//! circuit transitions. The dashboard handler in `think-watch-server` reads -//! a snapshot to render real-time CB state in the upstream-health panel. -//! -//! Living in `think-watch-common` keeps the two gateways decoupled while -//! still letting them share a single global view. - -use std::collections::HashMap; -use std::sync::OnceLock; -use std::sync::RwLock; - -/// Public, stable representation of a circuit-breaker state. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum CbState { - Closed, - HalfOpen, - Open, -} - -impl CbState { - pub fn as_str(&self) -> &'static str { - match self { - CbState::Closed => "Closed", - CbState::HalfOpen => "HalfOpen", - CbState::Open => "Open", - } - } -} - -static CB_REGISTRY: OnceLock>> = OnceLock::new(); - -/// Signature of the Open-transition listener. Named so the static's -/// type declaration stays short and clippy::type_complexity happy. -pub type OpenListener = Box; - -/// Optional listener invoked whenever a key transitions *into* `Open`. -/// The server installs this at startup to emit a `provider.circuit_open` -/// audit event; the gateways themselves don't need to know about audit. -/// `kind` is "ai" for provider breakers and "mcp" for MCP server -/// breakers so downstream subscribers can distinguish them. -static OPEN_LISTENER: OnceLock = OnceLock::new(); - -fn cb_registry() -> &'static RwLock> { - CB_REGISTRY.get_or_init(|| RwLock::new(HashMap::new())) -} - -/// Install a listener for Open transitions. Called once at startup; a -/// second call is a no-op (OnceLock) so tests and double-init are safe. -pub fn set_open_listener(f: F) -where - F: Fn(&str, &str) + Send + Sync + 'static, -{ - let _ = OPEN_LISTENER.set(Box::new(f)); -} - -/// Record a circuit-breaker state transition for `key` (typically the -/// upstream provider/server name). Cheap; safe to call from any thread. -/// -/// `kind` is a free-form discriminator the caller picks — in practice -/// either "ai" or "mcp" — used by the Open listener to tag emitted -/// audit events. When the transition is Closed→Open or HalfOpen→Open -/// the listener (if installed) fires once. -pub fn record_cb_with_kind(key: &str, state: CbState, kind: &str) { - let prev = if let Ok(mut m) = cb_registry().write() { - m.insert(key.to_string(), state) - } else { - None - }; - if state == CbState::Open - && prev != Some(CbState::Open) - && let Some(listener) = OPEN_LISTENER.get() - { - listener(key, kind); - } -} - -/// Snapshot the current state of every key the registry has seen. -pub fn snapshot_cb_states() -> HashMap { - cb_registry().read().map(|m| m.clone()).unwrap_or_default() -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Mutex; - use std::sync::OnceLock; - - /// Tests share the global `OPEN_LISTENER` and `CB_REGISTRY` — - /// running them in parallel would crosstalk. A serial mutex - /// keeps them ordered without forcing the whole crate single- - /// threaded. - fn serial_lock() -> &'static Mutex<()> { - static M: OnceLock> = OnceLock::new(); - M.get_or_init(|| Mutex::new(())) - } - - /// Captures listener invocations into a static so a second test - /// run within the same process still sees calls made *after* - /// the first set_open_listener wins. (OnceLock semantics: only - /// the first set takes effect, so we install once at first use.) - fn captured() -> &'static Mutex> { - static C: OnceLock>> = OnceLock::new(); - let cell = C.get_or_init(|| Mutex::new(Vec::new())); - // Idempotent install — only the first call actually wires the - // listener, subsequent ones no-op (OnceLock::set returns Err). - let cap = cell; - set_open_listener(move |key, kind| { - if let Ok(mut g) = cap.lock() { - g.push((key.to_string(), kind.to_string())); - } - }); - cell - } - - fn drain_captured() -> Vec<(String, String)> { - let cap = captured(); - cap.lock() - .map(|mut g| std::mem::take(&mut *g)) - .unwrap_or_default() - } - - #[test] - fn open_listener_fires_once_per_transition_to_open() { - let _g = serial_lock().lock().unwrap(); - let _ = drain_captured(); // discard residue from earlier tests - - record_cb_with_kind("test-fires-once", CbState::Closed, "ai"); - record_cb_with_kind("test-fires-once", CbState::Open, "ai"); - record_cb_with_kind("test-fires-once", CbState::Open, "ai"); - record_cb_with_kind("test-fires-once", CbState::Open, "ai"); - - let calls = drain_captured(); - let calls_for_key: Vec<_> = calls - .iter() - .filter(|(k, _)| k == "test-fires-once") - .collect(); - assert_eq!( - calls_for_key.len(), - 1, - "expected exactly one Open transition, got {calls_for_key:?}" - ); - assert_eq!(calls_for_key[0].1, "ai"); - } - - #[test] - fn open_listener_re_fires_after_close_then_open() { - let _g = serial_lock().lock().unwrap(); - let _ = drain_captured(); - - record_cb_with_kind("test-re-fires", CbState::Open, "mcp"); - record_cb_with_kind("test-re-fires", CbState::Closed, "mcp"); - record_cb_with_kind("test-re-fires", CbState::Open, "mcp"); - - let calls = drain_captured(); - let calls_for_key: Vec<_> = calls.iter().filter(|(k, _)| k == "test-re-fires").collect(); - assert_eq!( - calls_for_key.len(), - 2, - "Closed→Open should re-fire, got {calls_for_key:?}" - ); - assert!(calls_for_key.iter().all(|(_, kind)| kind == "mcp")); - } - - #[test] - fn open_listener_does_not_fire_on_half_open() { - let _g = serial_lock().lock().unwrap(); - let _ = drain_captured(); - - record_cb_with_kind("test-no-half-open", CbState::Closed, "ai"); - record_cb_with_kind("test-no-half-open", CbState::HalfOpen, "ai"); - - let calls = drain_captured(); - assert!( - !calls.iter().any(|(k, _)| k == "test-no-half-open"), - "HalfOpen transition must not fire the Open listener" - ); - } - - #[test] - fn snapshot_reflects_latest_state_for_each_key() { - let _g = serial_lock().lock().unwrap(); - - record_cb_with_kind("snapshot-test-1", CbState::Closed, "ai"); - record_cb_with_kind("snapshot-test-2", CbState::Open, "mcp"); - record_cb_with_kind("snapshot-test-1", CbState::HalfOpen, "ai"); - - let snap = snapshot_cb_states(); - assert_eq!(snap.get("snapshot-test-1"), Some(&CbState::HalfOpen)); - assert_eq!(snap.get("snapshot-test-2"), Some(&CbState::Open)); - } -} diff --git a/crates/tw-resil/src/lib.rs b/crates/tw-resil/src/lib.rs deleted file mode 100644 index 89cdf9b7..00000000 --- a/crates/tw-resil/src/lib.rs +++ /dev/null @@ -1,11 +0,0 @@ -//! 重试与熔断。 -//! -//! 桌面版的熔断参数比企业版克制得多(只留连续失败 -//! 阈值和冷却时长两个旋钮),但状态机本身是同一套。 - -pub mod cb_registry; -pub mod metrics_labels; -pub mod retry; - -pub use cb_registry::{CbState, record_cb_with_kind}; -pub use retry::*; diff --git a/crates/tw-resil/src/metrics_labels.rs b/crates/tw-resil/src/metrics_labels.rs deleted file mode 100644 index 3da6fb47..00000000 --- a/crates/tw-resil/src/metrics_labels.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! Cardinality guards for Prometheus labels. -//! -//! A naive `metrics::counter!("foo", "provider" => name.into())` emits -//! one time series per distinct value of `name`. If an operator stands -//! up 1000 custom providers (or a bug makes them look custom by string- -//! differing), the Prometheus scrape queue starves and the dashboard -//! goes dark. Labels that come from user-controlled config always need -//! a cap. -//! -//! `normalize_provider_label` is the gate for the `provider` dimension: -//! recognised providers pass through verbatim, everything else collapses -//! to `"other"`. Extending the allow-list is a deliberate code change, -//! not a config flip — which keeps the worst-case cardinality pinned. - -/// Well-known provider names kept as individual series. Order doesn't -/// matter; keep the list short and memorable. Adding a value here is -/// a deliberate decision about dashboard cardinality. -const KNOWN_PROVIDERS: &[&str] = &[ - "openai", - "anthropic", - "gemini", - "azure", - "bedrock", - "mistral", - "together", - "groq", - "openrouter", - "deepseek", -]; - -/// Collapse any provider name not in [`KNOWN_PROVIDERS`] to `"other"` -/// so the Prometheus cardinality for the `provider` label stays bounded -/// regardless of how many custom provider rows sit in the database. -pub fn normalize_provider_label(name: &str) -> &'static str { - let lower = name.to_ascii_lowercase(); - for known in KNOWN_PROVIDERS { - if lower == *known { - return known; - } - } - "other" -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn known_providers_preserved() { - assert_eq!(normalize_provider_label("openai"), "openai"); - assert_eq!(normalize_provider_label("Anthropic"), "anthropic"); - assert_eq!(normalize_provider_label("BEDROCK"), "bedrock"); - } - - #[test] - fn unknown_collapses_to_other() { - assert_eq!(normalize_provider_label("my-custom-proxy"), "other"); - assert_eq!(normalize_provider_label(""), "other"); - assert_eq!(normalize_provider_label("openaix"), "other"); - } -} diff --git a/crates/tw-resil/src/retry.rs b/crates/tw-resil/src/retry.rs deleted file mode 100644 index df962df3..00000000 --- a/crates/tw-resil/src/retry.rs +++ /dev/null @@ -1,198 +0,0 @@ -use std::time::Duration; - -/// Retry policy with exponential backoff and optional jitter. -#[derive(Debug, Clone)] -pub struct RetryPolicy { - pub max_retries: u32, - pub initial_delay_ms: u64, - pub max_delay_ms: u64, - pub jitter: bool, -} - -impl Default for RetryPolicy { - fn default() -> Self { - Self { - max_retries: 2, - initial_delay_ms: 500, - max_delay_ms: 5000, - jitter: true, - } - } -} - -impl RetryPolicy { - /// Compute the delay for a given attempt (0-based). - pub fn delay_for_attempt(&self, attempt: u32) -> Duration { - let base = self.initial_delay_ms * 2u64.pow(attempt); - let capped = base.min(self.max_delay_ms); - - let delay = if self.jitter { - // Add random jitter up to 25% of the delay - let jitter_range = capped / 4; - let jitter = rand::random_range(0..=jitter_range); - capped + jitter - } else { - capped - }; - - Duration::from_millis(delay) - } - - /// Execute an async operation with retry. - /// - /// Only retries on errors where `should_retry` returns true. - pub async fn execute( - &self, - mut operation: F, - should_retry: fn(&E) -> bool, - ) -> Result - where - F: FnMut() -> Fut, - Fut: std::future::Future>, - E: std::fmt::Display, - { - let mut last_error; - - match operation().await { - Ok(v) => return Ok(v), - Err(e) => { - if !should_retry(&e) || self.max_retries == 0 { - return Err(e); - } - tracing::warn!("Retryable error (attempt 1/{}): {e}", self.max_retries + 1); - last_error = e; - } - } - - for attempt in 1..=self.max_retries { - let delay = self.delay_for_attempt(attempt - 1); - tokio::time::sleep(delay).await; - - match operation().await { - Ok(v) => { - tracing::info!("Succeeded on retry attempt {attempt}"); - return Ok(v); - } - Err(e) => { - if !should_retry(&e) { - return Err(e); - } - tracing::warn!( - "Retryable error (attempt {}/{}):{e}", - attempt + 1, - self.max_retries + 1 - ); - last_error = e; - } - } - } - - Err(last_error) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::sync::atomic::{AtomicU32, Ordering}; - - #[tokio::test] - async fn succeeds_on_first_try() { - let policy = RetryPolicy { - max_retries: 2, - initial_delay_ms: 10, - max_delay_ms: 100, - jitter: false, - }; - - let result = policy - .execute(|| async { Ok::<_, String>(42) }, |_| true) - .await; - - assert_eq!(result.unwrap(), 42); - } - - #[tokio::test] - async fn retries_on_failure() { - let counter = AtomicU32::new(0); - let policy = RetryPolicy { - max_retries: 2, - initial_delay_ms: 10, - max_delay_ms: 100, - jitter: false, - }; - - let result = policy - .execute( - || { - let attempt = counter.fetch_add(1, Ordering::SeqCst); - async move { - if attempt < 2 { - Err(format!("fail {attempt}")) - } else { - Ok(42) - } - } - }, - |_| true, - ) - .await; - - assert_eq!(result.unwrap(), 42); - assert_eq!(counter.load(Ordering::SeqCst), 3); - } - - #[tokio::test] - async fn does_not_retry_non_retryable() { - let counter = AtomicU32::new(0); - let policy = RetryPolicy { - max_retries: 3, - initial_delay_ms: 10, - max_delay_ms: 100, - jitter: false, - }; - - let result: Result = policy - .execute( - || { - counter.fetch_add(1, Ordering::SeqCst); - async { Err("auth error".to_string()) } - }, - |e| !e.contains("auth"), - ) - .await; - - assert!(result.is_err()); - assert_eq!(counter.load(Ordering::SeqCst), 1); // Only tried once - } - - #[test] - fn delay_increases_exponentially() { - let policy = RetryPolicy { - max_retries: 5, - initial_delay_ms: 100, - max_delay_ms: 5000, - jitter: false, - }; - - assert_eq!(policy.delay_for_attempt(0), Duration::from_millis(100)); - assert_eq!(policy.delay_for_attempt(1), Duration::from_millis(200)); - assert_eq!(policy.delay_for_attempt(2), Duration::from_millis(400)); - assert_eq!(policy.delay_for_attempt(3), Duration::from_millis(800)); - } - - #[test] - fn delay_capped_at_max() { - let policy = RetryPolicy { - max_retries: 5, - initial_delay_ms: 1000, - max_delay_ms: 3000, - jitter: false, - }; - - assert_eq!(policy.delay_for_attempt(0), Duration::from_millis(1000)); - assert_eq!(policy.delay_for_attempt(1), Duration::from_millis(2000)); - assert_eq!(policy.delay_for_attempt(2), Duration::from_millis(3000)); // capped - assert_eq!(policy.delay_for_attempt(3), Duration::from_millis(3000)); // capped - } -} diff --git a/crates/tw-scan/Cargo.toml b/crates/tw-scan/Cargo.toml index 6858f0e6..091b875c 100644 --- a/crates/tw-scan/Cargo.toml +++ b/crates/tw-scan/Cargo.toml @@ -15,6 +15,7 @@ serde_yaml_ng = { workspace = true } tw-adopt = { workspace = true } tw-config = { workspace = true } tw-types = { workspace = true } +tw-guard = { workspace = true } notify = { workspace = true } tokio = { workspace = true } thiserror = { workspace = true } diff --git a/crates/tw-scan/src/lib.rs b/crates/tw-scan/src/lib.rs index 4813dd16..94f3cc48 100644 --- a/crates/tw-scan/src/lib.rs +++ b/crates/tw-scan/src/lib.rs @@ -1,5 +1,4 @@ pub mod hidden; pub mod report; -pub mod rules; pub mod sources; pub mod watch; diff --git a/crates/tw-scan/src/report.rs b/crates/tw-scan/src/report.rs index f1a47cf7..26d9ccc3 100644 --- a/crates/tw-scan/src/report.rs +++ b/crates/tw-scan/src/report.rs @@ -21,8 +21,8 @@ use tw_adopt::json::Val; use tw_types::{Msg, msg}; use crate::hidden; -use crate::rules::Rules; use crate::sources::{self, Source}; +use tw_guard::tools::rules::Rules; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub enum Level { diff --git a/crates/tw-scan/tests/scan.rs b/crates/tw-scan/tests/scan.rs index 49918be5..72b276e9 100644 --- a/crates/tw-scan/tests/scan.rs +++ b/crates/tw-scan/tests/scan.rs @@ -6,8 +6,9 @@ use std::path::{Path, PathBuf}; +use tw_guard::tools::rules; use tw_scan::report::{Level, scan}; -use tw_scan::{rules, sources}; +use tw_scan::sources; fn write(p: &Path, s: &str) { std::fs::create_dir_all(p.parent().unwrap()).unwrap(); @@ -254,7 +255,8 @@ fn the_source_code_itself_contains_no_way_to_delete_anything() { "src/report.rs", "src/hidden.rs", "src/sources.rs", - "src/rules.rs", + // 规则引擎住在 tw-guard,扫描器用的也是它 + "../tw-guard/src/tools/rules.rs", ] { let src = std::fs::read_to_string(f).unwrap(); // 测试里当然要造文件。看的是产品代码那一半 diff --git a/crates/tw-types/src/lib.rs b/crates/tw-types/src/lib.rs index f11cda9d..e65900ec 100644 --- a/crates/tw-types/src/lib.rs +++ b/crates/tw-types/src/lib.rs @@ -261,6 +261,12 @@ pub enum GatewayError { /// "monthly budget"). Maps to 429 in `IntoResponse`. #[error("Rate limited: {0}")] LocalRateLimited(String), + /// Refused by the gateway's own policy — a tool call the upstream + /// returned matched a rule set to cut it. Neither the caller's fault + /// (not 400) nor the upstream failing (not 502): the answer exists + /// and the gateway will not hand it over. Maps to 403. + #[error("Blocked by policy: {0}")] + PolicyBlocked(String), } impl GatewayError { @@ -281,6 +287,7 @@ impl GatewayError { GatewayError::NetworkError(_) => 502, GatewayError::UpstreamRateLimited { .. } | GatewayError::LocalRateLimited(_) => 429, GatewayError::UpstreamAuthError => 401, + GatewayError::PolicyBlocked(_) => 403, } } @@ -298,6 +305,7 @@ impl GatewayError { GatewayError::UpstreamRateLimited { .. } => "UpstreamRateLimited", GatewayError::LocalRateLimited(_) => "LocalRateLimited", GatewayError::UpstreamAuthError => "UpstreamAuthError", + GatewayError::PolicyBlocked(_) => "PolicyBlocked", } } @@ -431,6 +439,14 @@ mod call_ctx_tests { .collect() } + #[test] + fn a_policy_refusal_is_forbidden_not_a_bad_request_or_an_upstream_failure() { + let e = GatewayError::PolicyBlocked("the tool call matched a rule".into()); + assert_eq!(e.status_code(), 403); + assert_eq!(e.error_tag(), "PolicyBlocked"); + assert_eq!(e.retry_after_secs(), None); + } + #[test] fn substitutes_known_keys() { let a = attrs(&[("user_id", "u1"), ("user_email", "a@b.c")]);