AnyBot/src/gate.rs

323 lines
20 KiB
Rust
Raw Normal View History

//! 核准關卡的規則: the part of a step's approval that is rules alone, out of the turn loop
//! (agent::spawn) so it can be read in one place and tested as a table. What safety.md's
//! 「每一步的關卡順序」 says, steps 6 and 8:
//!
//! - `by_kind` (step 6): what kind of step it is decides — the Mac's own apps (reading once per
//! app, writing once per app, sending every time), the screen (its own desktop free; looking
//! once; operating once per app; never AnyBot's own window), another computer's screen (seeing
//! and operating once each), the browser (reading a logged-in tab once), everything else by
//! tools::decide_on (commands and files).
//! - `always_ask` (step 8): what is asked every time whatever came before — a click on a target
//! that says paying, sending or deleting; mail and messages; AppleScript outside the sandbox.
//!
//! What stays in the loop: asking the person to turn computer tools or this computer on (steps
//! 3–5, they wait for an answer), and the 自動審核 model call (step 7). Engineering plan E9.
use crate::tools::{self, Decision};
/// 「一律允許」 for this computer's whole screen: what is offered when the desktop can't say
/// which app a step lands in (GNOME / KDE on Wayland never can; wlroots can't for a point).
pub const SCREEN_CONTROL_GRANT: &str = "computer:control";
const LOOKS: [&str; 3] = ["computer_use_screenshot", "computer_use_zoom", "computer_use_show"];
/// What a screen step on this computer asks: (the grant 「一律允許」 keeps, the question). Per app
/// when the desktop names it; for the screen as a whole when it can't — the question then says
/// so. (An empty grant there used to make every click, key and scroll ask with no 「一律允許」.)
pub fn screen_control_ask(app: Option<&str>, via: &str, what: &str) -> (String, String) {
match app.map(str::trim).filter(|a| !a.is_empty()) {
Some(a) => (format!("app:{a}"), format!("讓 {via} 看到「{a}」,並在其中點擊和輸入:{what}")),
None => (SCREEN_CONTROL_GRANT.to_string(), format!("讓 {via} 在這台電腦的螢幕上點擊和輸入:{what}\n(這個桌面看不出是哪個 App;一律允許後,這台電腦的螢幕操作不再逐步詢問,付款、刪除、送出這類動作仍會問。)")),
}
}
/// Where a step runs, as the rules need it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Place<'a> {
/// The bot's own desktop (the box).
OwnBox,
/// Another computer of the person's account (by its name).
Device(&'a str),
/// Anywhere else (this computer, an SSH computer…).
Elsewhere,
}
/// Step 6: the decision by what kind of step it is. `what` is the step in words (for the card),
/// `via` the bot's name, `app` finds the app a screen step aims at (computer::target_app: only
/// asked for an operating step on this computer's screen).
#[allow(clippy::too_many_arguments)]
pub fn by_kind(name: &str, args: &str, what: &str, via: &str, target: &tools::Target, place: Place, app: impl FnOnce() -> Option<String>, grants: &[String]) -> Decision {
let has = |g: &str| grants.iter().any(|x| x == g);
if crate::macapps::is_mac_tool(name) {
let app = crate::macapps::app_of(name);
return if crate::macapps::is_send(name) && name == crate::macapps::SEND_MESSAGE && has("messages:no-ask") {
Decision::Allow
} else if crate::macapps::is_send(name) {
Decision::Ask { reason: format!("用你的「{app}」{what}"), grant: String::new() }
} else if crate::macapps::is_write(name) {
let grant = format!("macapp-write:{app}");
if has(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("讓 {via} 修改你的「{app}」:{what}"), grant } }
} else {
let grant = format!("macapp:{app}");
if has(&grant) || has(&format!("macapp-write:{app}")) { Decision::Allow } else { Decision::Ask { reason: format!("讓 {via} 讀取你的「{app}」:{what}"), grant } }
};
}
if crate::computer::is_computer_tool(name) {
if place == Place::OwnBox || name == "computer_use_check_permissions" {
return Decision::Allow;
}
let looks = LOOKS.contains(&name);
if let Place::Device(device) = place {
let grant = if looks { format!("device-see:{device}") } else { format!("device-control:{device}") };
return if has(&grant) { Decision::Allow } else { Decision::Ask { reason: format!("{}「{device}」的螢幕:{what}", if looks { "看" } else { "操作" }), grant } };
}
if looks {
return if has("computer:see") { Decision::Allow } else { Decision::Ask { reason: format!("看你的螢幕畫面:{what}"), grant: "computer:see".into() } };
}
let app = app();
if app.as_deref().is_some_and(|a| crate::computer::is_self_app(a, None)) {
return Decision::Deny("Bot 不能點擊或操作 AnyBot 自己的視窗或核准按鈕。".into());
}
let (grant, reason) = screen_control_ask(app.as_deref(), via, what);
return if has(SCREEN_CONTROL_GRANT) || has(&grant) { Decision::Allow } else { Decision::Ask { reason, grant } };
}
if crate::web::is_web_tool(name) {
return if name == "browser_read" && crate::web::read_needs_permission(args) && !has("browser:read") {
Decision::Ask { reason: "讀取你瀏覽器目前分頁的內容(包含已登入的頁面):目前的分頁".into(), grant: "browser:read".into() }
} else {
Decision::Allow
};
}
tools::decide_on(name, args, target, grants)
}
/// What step 8 found (the decision, and whether it may not be granted away or reviewed).
#[derive(Debug, PartialEq)]
pub struct Always {
pub decision: Decision,
/// Asked by step 8 itself: the review's note doesn't stand.
pub overridden: bool,
/// No 「一律允許」, no review, no direct mode past it.
pub must_ask: bool,
}
/// Step 8: what is asked every time, over whatever steps 6 and 7 said (a refusal stays one).
/// `sensitive_click`: the click's target reads like paying, sending or deleting;
/// `on_persons`: the step runs on this computer or another of the person's.
#[allow(clippy::too_many_arguments)]
pub fn always_ask(name: &str, args: &serde_json::Value, what: &str, via: &str, decision: Decision, sensitive_click: bool, on_persons: bool, grants: &[String]) -> Always {
let has = |g: &str| grants.iter().any(|x| x == g);
if matches!(decision, Decision::Deny(_)) {
return Always { decision, overridden: false, must_ask: false };
}
if sensitive_click {
return Always { decision: Decision::Ask { reason: format!("畫面上的目標說的是敏感操作:{what}(付款、傳送、刪除這類事,每一次都會先問你)"), grant: String::new() }, overridden: true, must_ask: false };
}
let skip_msg_ask = name == crate::macapps::SEND_MESSAGE && has("messages:no-ask");
if crate::macapps::is_mac_tool(name) && crate::macapps::is_send(name) && !skip_msg_ask {
return Always { decision: Decision::Ask { reason: format!("用你的「{}」{what}(每一封都會先問你)", crate::macapps::app_of(name)), grant: String::new() }, overridden: true, must_ask: false };
}
let script = args["command"].as_str().unwrap_or("");
if name == "shell" && on_persons && tools::osascript_outside(script).is_ok() && !has(tools::OSASCRIPT_GRANT) {
let short: String = script.chars().take(200).collect();
return Always { decision: Decision::Ask { reason: format!("讓 {via} 在沙盒外執行 AppleScript(可以指揮你電腦上的 App):{short}"), grant: tools::OSASCRIPT_GRANT.into() }, overridden: true, must_ask: true };
}
Always { decision, overridden: false, must_ask: false }
}
#[cfg(test)]
mod tests {
use super::*;
fn here() -> tools::Target {
tools::Target { name: "這台".into(), place: tools::Place::Local { workdir: std::env::temp_dir() } }
}
fn ask_grant(d: &Decision) -> Option<&str> {
match d {
Decision::Ask { grant, .. } => Some(grant.as_str()),
_ => None,
}
}
/// Step 6 as a table: (tool, place, app, grants) → allowed, asked (with what grant), refused.
#[test]
fn step_six_by_kind() {
let g = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let t = here();
let d = |name: &str, args: &str, place: Place, app: Option<&str>, grants: &[String]| by_kind(name, args, "做事", "Bot", &t, place, || app.map(String::from), grants);
// The Mac's apps.
let send = crate::macapps::SEND_MESSAGE;
assert_eq!(ask_grant(&d(send, "{}", Place::Elsewhere, None, &[])), Some(""), "sending: every time, nothing to keep");
assert_eq!(d(send, "{}", Place::Elsewhere, None, &g(&["messages:no-ask"])), Decision::Allow);
// The screen.
assert_eq!(d("computer_use_click", "{}", Place::OwnBox, None, &[]), Decision::Allow, "its own desktop");
assert_eq!(ask_grant(&d("computer_use_screenshot", "{}", Place::Elsewhere, None, &[])), Some("computer:see"));
assert_eq!(d("computer_use_screenshot", "{}", Place::Elsewhere, None, &g(&["computer:see"])), Decision::Allow);
assert_eq!(ask_grant(&d("computer_use_click", "{}", Place::Elsewhere, Some("Safari"), &[])), Some("app:Safari"));
assert_eq!(d("computer_use_click", "{}", Place::Elsewhere, Some("Safari"), &g(&[SCREEN_CONTROL_GRANT])), Decision::Allow);
assert_eq!(ask_grant(&d("computer_use_click", "{}", Place::Elsewhere, None, &[])), Some(SCREEN_CONTROL_GRANT));
assert!(matches!(d("computer_use_click", "{}", Place::Elsewhere, Some("AnyBot"), &g(&[SCREEN_CONTROL_GRANT])), Decision::Deny(_)), "never AnyBot's own window");
// Another computer's screen.
assert_eq!(ask_grant(&d("computer_use_screenshot", "{}", Place::Device("筆電"), None, &[])), Some("device-see:筆電"));
assert_eq!(ask_grant(&d("computer_use_click", "{}", Place::Device("筆電"), None, &g(&["device-see:筆電"]))), Some("device-control:筆電"));
// The browser: opening is free.
assert_eq!(d("browser_open", r#"{"url":"https://example.com"}"#, Place::Elsewhere, None, &[]), Decision::Allow);
// Commands go by the command rules.
assert!(matches!(d("shell", r#"{"command":"sudo rm -rf /"}"#, Place::Elsewhere, None, &[]), Decision::Deny(_)));
assert_eq!(d("shell", r#"{"command":"ls"}"#, Place::Elsewhere, None, &[]), Decision::Allow);
}
/// Step 8 as a table: what is asked every time, over an allow; a refusal stays one.
#[test]
fn step_eight_always_asks() {
let a = |name: &str, args: serde_json::Value, d: Decision, sensitive: bool, persons: bool, grants: &[String]| always_ask(name, &args, "做事", "Bot", d, sensitive, persons, grants);
let none = serde_json::json!({});
let r = a("computer_use_click", none.clone(), Decision::Allow, true, true, &[]);
assert!(r.overridden && !r.must_ask && ask_grant(&r.decision) == Some(""), "a pay/send/delete click");
let r = a(crate::macapps::SEND_MESSAGE, none.clone(), Decision::Allow, false, true, &[]);
assert!(r.overridden && ask_grant(&r.decision) == Some(""), "a message, each one");
let r = a(crate::macapps::SEND_MESSAGE, none.clone(), Decision::Allow, false, true, &["messages:no-ask".into()]);
assert_eq!(r.decision, Decision::Allow, "unless the person said messages may go without asking");
let osa = serde_json::json!({"command": "osascript -e 'tell application \"Music\" to pause'"});
let r = a("shell", osa.clone(), Decision::Allow, false, true, &[]);
assert!(r.must_ask && ask_grant(&r.decision) == Some(tools::OSASCRIPT_GRANT), "AppleScript outside the sandbox: {r:?}");
assert_eq!(a("shell", osa.clone(), Decision::Allow, false, true, &[tools::OSASCRIPT_GRANT.into()]).decision, Decision::Allow);
assert_eq!(a("shell", osa, Decision::Allow, false, false, &[]).decision, Decision::Allow, "not on the person's computer");
let deny = Decision::Deny("不行".into());
assert_eq!(a("computer_use_click", none, deny.clone(), true, true, &[]).decision, deny, "a refusal stays a refusal");
}
}
feat: 自動審核可以寫固定樣式的規則,在模型之前判斷、每次一樣 計畫 R2(grok-build 的 Bash(git *)、deny > ask > allow 在模型之前)。用一般的話寫的規則交給模型判斷,每次可能不一樣,網頁上的字也可能把模型說成「允許」。 - gate.rs:is_pattern、glob(* 任何字、? 一個字;檔案的 * 只在一層、** 跨資料夾)、patterns:shell(…)(允許要每一段都符合,詢問只要一段;藏起來的指令 $()/反引號樣式不允許)、file(…)(讀檔、改檔、列資料夾、搜尋的路徑,~ 換成家目錄)、connector(…)(mcp__server__tool,use_connector_tool 也算)、web(domain:…)(web_fetch、browser_open 的網址,子網域算、example.com.evil.net 不算)、tool(…)。詢問的樣式贏過允許的樣式。 - agent::review_action:先看樣式。符合詢問 → 問(不能一律允許);符合允許 → 允許,但有用話寫的「一律詢問」時先讓模型看那幾條;都不符合 → 只把用話寫的規則交給模型(review_by_model)。直接操作模式下詢問的樣式一樣擋。 - 設定 › 權限 › 自動審核的說明寫樣式怎麼寫;功能地圖 safety.md、FEATURES.md。 已驗證:cargo test 580 全過、clippy -D warnings 過。新測試:glob;樣式的表格(13 種:git status 允許、git status && rm -rf x 不允許、git push 被詢問蓋過、$() 不允許、路徑、連接器、子網域和假網域、工具名);一輪:直接操作 + 一律詢問的 shell(echo *),那一步停下來問、卡上寫是哪一條規則,模型只被問了兩次(沒有額外的審核呼叫),檔案沒建。 未驗證:無。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 04:01:34 +00:00
// ---------- 固定樣式的規則 (R2) ----------
// 「無需詢問直接允許」 and 「一律詢問」 rules may be written as a pattern instead of a sentence:
// shell(git *) a command (every part of `a && b | c` for an allow; any part for an ask)
// file(~/Projects/**) a file or folder a step reads or changes (** any depth, * one name)
// connector(gitlab__*) a connector's tool (server__tool)
// web(domain:example.com) a page opened or fetched on that site (or below it)
// tool(browser_click) a step by its tool's name
// They are decided here, the same every time, before the model reads the sentence rules: an ask
// pattern can't be talked out of by anything the model read (grok-build's deny > ask > allow
// rules, checked before its model).
/// What the pattern rules say about a step.
#[derive(Clone, Debug, PartialEq)]
pub enum PatternVerdict {
Ask(String),
Allow(String),
NoMatch,
}
/// A rule written as a pattern (else it is a sentence for the model).
pub fn is_pattern(rule: &str) -> bool {
let r = rule.trim();
["shell(", "file(", "connector(", "web(", "tool("].iter().any(|p| r.starts_with(p)) && r.ends_with(')')
}
/// `*` any run of characters, `?` one; with `slash_stops`, `*` stays within one path name and
/// `**` crosses folders.
pub fn glob(pat: &str, text: &str, slash_stops: bool) -> bool {
fn go(p: &[char], t: &[char], slash_stops: bool) -> bool {
match p.first() {
None => t.is_empty(),
Some('*') if p.get(1) == Some(&'*') => (0..=t.len()).any(|i| go(&p[2..], &t[i..], slash_stops)),
Some('*') => (0..=t.len()).take_while(|&i| i == 0 || !(slash_stops && t[i - 1] == '/')).any(|i| go(&p[1..], &t[i..], slash_stops)),
Some('?') => !t.is_empty() && go(&p[1..], &t[1..], slash_stops),
Some(c) => t.first() == Some(c) && go(&p[1..], &t[1..], slash_stops),
}
}
let (p, t): (Vec<char>, Vec<char>) = (pat.chars().collect(), text.chars().collect());
go(&p, &t, slash_stops)
}
fn host_of(url: &str) -> String {
url.split("://").nth(1).unwrap_or(url).split(['/', ':', '?', '#']).next().unwrap_or("").to_ascii_lowercase()
}
/// Whether `rule` (a pattern) is about this step; `all` for an allow (every part of a command
/// must match), any part for an ask.
fn pattern_matches(rule: &str, name: &str, args: &serde_json::Value, all: bool) -> bool {
let r = rule.trim();
let Some((kind, inner)) = r.split_once('(').map(|(k, rest)| (k, rest.strip_suffix(')').unwrap_or(rest).trim())) else { return false };
let s = |k: &str| args[k].as_str().unwrap_or("").trim().to_string();
match kind {
"shell" if name == "shell" => {
let cmd = s("command");
match tools::split_commands(&cmd) {
Some(parts) if !parts.is_empty() => {
let hit = |p: &String| glob(inner, p.trim(), false);
if all { parts.iter().all(hit) } else { parts.iter().any(hit) }
}
// Hidden commands ($(), backticks): an allow can't vouch for what it can't see; an
// ask still looks at the whole line.
_ => !all && glob(inner, &cmd, false),
}
}
"file" if matches!(name, "read_file" | "edit_file" | "list_dir" | "search" | "write_file") => {
let path = s("path");
let home = |p: &str| tools::expand_home(p).display().to_string();
!path.is_empty() && (glob(inner, &path, true) || glob(&home(inner), &home(&path), true))
}
"connector" => {
let tool = if name == crate::mcp::USE_TOOL { s("tool") } else { name.to_string() };
tool.strip_prefix("mcp__").is_some_and(|t| glob(inner, t, false))
}
"web" if matches!(name, "web_fetch" | "browser_open") => {
let host = host_of(&s("url"));
let want = inner.strip_prefix("domain:").unwrap_or(inner).trim().to_ascii_lowercase();
!host.is_empty() && (host == want || host.ends_with(&format!(".{want}")))
}
"tool" => glob(inner, name, false),
_ => false,
}
}
/// The pattern rules' word on a step: any ask pattern about it asks (over any allow); else an
/// allow pattern that covers it allows; else they say nothing (the sentences go to the model).
pub fn patterns(name: &str, args: &str, allow: &[String], ask: &[String]) -> PatternVerdict {
let v = tools::args_of(args);
if let Some(r) = ask.iter().filter(|r| is_pattern(r)).find(|r| pattern_matches(r, name, &v, false)) {
return PatternVerdict::Ask(r.trim().to_string());
}
if let Some(r) = allow.iter().filter(|r| is_pattern(r)).find(|r| pattern_matches(r, name, &v, true)) {
return PatternVerdict::Allow(r.trim().to_string());
}
PatternVerdict::NoMatch
}
#[cfg(test)]
mod pattern_tests {
use super::*;
#[test]
fn globs() {
assert!(glob("git *", "git status", false) && !glob("git *", "gitk", false));
assert!(glob("npm ?un *", "npm run build", false));
assert!(glob("/a/**", "/a/b/c.txt", true) && glob("/a/*", "/a/b", true) && !glob("/a/*", "/a/b/c", true));
}
/// R2 as a table: the same answer every time, an ask over an allow, a chained command allowed
/// only when every part is.
#[test]
fn pattern_rules_decide_before_the_model() {
let rules = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
let allow = rules(&["shell(git *)", "file(~/Projects/**)", "connector(gitlab__get_*)", "web(domain:example.com)", "只是一句話的規則"]);
let ask = rules(&["shell(git push*)", "tool(browser_click)"]);
let p = |name: &str, args: serde_json::Value| patterns(name, &args.to_string(), &allow, &ask);
let sh = |c: &str| serde_json::json!({"command": c});
assert_eq!(p("shell", sh("git status")), PatternVerdict::Allow("shell(git *)".into()));
assert_eq!(p("shell", sh("git status && git log")), PatternVerdict::Allow("shell(git *)".into()));
assert_eq!(p("shell", sh("git status && rm -rf x")), PatternVerdict::NoMatch, "every part, or no allow");
assert_eq!(p("shell", sh("git add . && git push origin main")), PatternVerdict::Ask("shell(git push*)".into()), "an ask over an allow");
assert_eq!(p("shell", sh("echo $(git status)")), PatternVerdict::NoMatch, "a hidden command is never allowed by a pattern");
assert_eq!(p("read_file", serde_json::json!({"path": "~/Projects/a/b.rs"})), PatternVerdict::Allow("file(~/Projects/**)".into()));
assert_eq!(p("read_file", serde_json::json!({"path": "~/Documents/x"})), PatternVerdict::NoMatch);
assert_eq!(p("mcp__gitlab__get_issue", serde_json::json!({})), PatternVerdict::Allow("connector(gitlab__get_*)".into()));
assert_eq!(p(crate::mcp::USE_TOOL, serde_json::json!({"tool": "mcp__gitlab__delete_project"})), PatternVerdict::NoMatch);
assert_eq!(p("web_fetch", serde_json::json!({"url": "https://docs.example.com/a"})), PatternVerdict::Allow("web(domain:example.com)".into()));
assert_eq!(p("web_fetch", serde_json::json!({"url": "https://example.com.evil.net/"})), PatternVerdict::NoMatch);
assert_eq!(p("browser_click", serde_json::json!({})), PatternVerdict::Ask("tool(browser_click)".into()));
assert!(is_pattern("shell(ls)") && !is_pattern("刪除檔案前先問我") && !is_pattern("shell ls"));
}
}