AnyBot/src/gate.rs

191 lines
12 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");
}
}