AnyBot/src/policy.rs

96 lines
3.7 KiB
Rust
Raw Normal View History

// Admin locks for the permission switches, following how managed policies are delivered:
// - macOS: user defaults (`systemPreferences.getUserDefault(key, "string")`), which MDM profiles
// can force; Linux: a JSON file in the home folder; Windows: the native managed-policy lookup.
// - A missing or blank value = "unmanaged"; a valid value = "pinned"; anything else = "invalid",
// which managed-policy readers refuse to use. Here an invalid value locks the switch off.
use std::process::{Command, Stdio};
/// The macOS defaults domain AnyBot reads (`defaults write com.anybot.AnyBot AllowDirectMode false`).
pub const DOMAIN: &str = "com.anybot.AnyBot";
pub const KEY_DIRECT: &str = "AllowDirectMode";
pub const KEY_LOCAL: &str = "AllowLocalExecution";
/// 「網路流量改走你的電腦」 (the original lets admins turn it off).
pub const KEY_EGRESS: &str = "AllowBoxTrafficViaThisMac";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Policy {
Unmanaged,
Pinned(bool),
Invalid,
}
impl Policy {
/// May the person turn this on?
pub fn allows(self) -> bool {
match self {
Policy::Unmanaged => true,
Policy::Pinned(b) => b,
Policy::Invalid => false,
}
}
}
/// Blank or missing → unmanaged (the original's `mZ`); true/false words → pinned; else invalid.
pub fn parse(v: Option<&str>) -> Policy {
match v.map(|s| s.trim().to_ascii_lowercase()) {
None => Policy::Unmanaged,
Some(s) if s.is_empty() => Policy::Unmanaged,
Some(s) if ["true", "1", "yes"].contains(&s.as_str()) => Policy::Pinned(true),
Some(s) if ["false", "0", "no"].contains(&s.as_str()) => Policy::Pinned(false),
Some(_) => Policy::Invalid,
}
}
fn read_raw(key: &str) -> Option<String> {
if cfg!(target_os = "macos") {
let out = Command::new("defaults").args(["read", DOMAIN, key]).stderr(Stdio::null()).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
} else {
安全、修正: harden sandboxes, approval gates, vault, relay roles, and fix protocol/UI bugs - macOS 沙盒與工具 (tools.rs, policy.rs, docindex.rs): block AppleScript raw events and concatenation outside the sandbox; stop exposing ~/.ssh or localhost sockets in Sealed mode; deny writes to shell profiles, LaunchAgents and .git/hooks; expand secret-file ignores and enforce symlink/policy checks across SSH, device and document search. - 電腦操作與遮罩 (computer.rs, agent.rs, marks.rs, desktop.rs, cloudbox.rs, portal.rs): forbid clicking or typing into AnyBot's own windows; extend the sensitive-action hard gate to raw coordinates, Return/Delete submits and remote devices; stop batch steps if the front app changes; black out secrets on zoom, show, >600-node trees, adjacent OTP labels, box screenshots and control text lists; preserve non-text Wayland clipboards. - 保險庫與瀏覽器 (vault.rs, vault_store.rs, browser.rs, botbrowser.rs, web.rs, box/browser): verify tab host and HTTPS atomically at fill time; taint filled tabs against browser_eval and PDF export while masking card/CVC values and screenshots; remember sites only on always-allow; drop --remote-allow-origins=*; gate private URLs and block metadata/Docker ports, OrbStack 198.18/15 and IPv6 transition ranges. - 帳號伺服器、同步與傳送 (relay/, remote.rs, mirror_ui.rs, share.rs, drops.rs): isolate paired hands hosts from brain sync, tickets, pairing and backup overwrites; redact routine trigger secrets and clear REDACTED when endpoints change; isolate channel and team-member turns from owner memories, appctl and grants; scrub shared bot exports and reset grants/routines on import; validate drop IDs and serialize chunk writes. - 網路與協定穩定性 (httpd.rs, tunnel.rs, vnc.rs, Caddyfile*): fix chunked integer overflow and CRLF header injection; enforce Origin checks, connection/job caps, 200 MB backup reads, unique atomic temp files and ASCII hex guards; bound deflate unzip and VNC sniff buffers; move VNC stdin/text off the tunnel loop. - 介面、排程、語言與其他修正 (app.rs, i18n.rs, providers.rs, skills.rs, routines.rs, setup.rs, store.rs, preview.rs, attach.rs, speech.rs, teams.rs, mcp.rs, voice.rs): wire up the delete-routine confirmation dialog and mirror run-now; preserve unsaved mirror edits across brief disconnects; give Chinese skills distinct folders and approval gates; convert parsed tool JSON fields without corrupting code fences, URLs or paths; fix Hourly DST offsets and time out unattended routine approvals; lock --install-skill, cap docx/xlsx unzip sizes, isolate test env keys, and tighten local file permissions. Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-12 06:34:10 +00:00
// Check root-managed `/etc/anybot/policy.json` first so the user or a process under `$HOME` cannot override an admin policy.
let sys = std::path::Path::new("/etc/anybot/policy.json");
let path = if sys.exists() { sys.to_path_buf() } else { dirs::home_dir()?.join(".anybot").join("policy.json") };
let text = std::fs::read_to_string(path).ok()?;
let v: serde_json::Value = serde_json::from_str(&text).ok()?;
v.get(key).map(|x| x.as_str().map(str::to_string).unwrap_or_else(|| x.to_string()))
}
}
#[derive(Clone, Copy, Debug)]
pub struct Managed {
pub direct: Policy,
pub local: Policy,
pub egress: Policy,
}
impl Default for Managed {
fn default() -> Self {
Managed { direct: Policy::Unmanaged, local: Policy::Unmanaged, egress: Policy::Unmanaged }
}
}
/// Just the traffic switch (checked when a command starts).
pub fn read_egress() -> Policy {
parse(read_raw(KEY_EGRESS).as_deref())
}
pub fn read() -> Managed {
Managed { direct: parse(read_raw(KEY_DIRECT).as_deref()), local: parse(read_raw(KEY_LOCAL).as_deref()), egress: parse(read_raw(KEY_EGRESS).as_deref()) }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn values_follow_the_original_kinds() {
assert_eq!(parse(None), Policy::Unmanaged);
assert_eq!(parse(Some(" ")), Policy::Unmanaged);
assert_eq!(parse(Some("0")), Policy::Pinned(false));
assert_eq!(parse(Some("TRUE")), Policy::Pinned(true));
assert_eq!(parse(Some("maybe")), Policy::Invalid);
assert!(Policy::Unmanaged.allows() && Policy::Pinned(true).allows());
assert!(!Policy::Pinned(false).allows() && !Policy::Invalid.allows());
}
}