aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
aien-sovereign-core / crates / aien-cli / src / safety.rs
| 1 | use serde_json::Value; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | #[derive(Debug, Clone, PartialEq)] |
| 6 | pub enum SafetyDecision { |
| 7 | Allow, |
| 8 | AskUser(String), |
| 9 | Deny(String), |
| 10 | } |
| 11 | |
| 12 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 13 | pub enum PolicyPriority { |
| 14 | SpecificDeny = 1, |
| 15 | SpecificAsk = 2, |
| 16 | SpecificAllow = 3, |
| 17 | PrefixWildcardDeny = 4, |
| 18 | PrefixWildcardAsk = 5, |
| 19 | PrefixWildcardAllow = 6, |
| 20 | GlobalWildcardDeny = 7, |
| 21 | GlobalWildcardAsk = 8, |
| 22 | GlobalWildcardAllow = 9, |
| 23 | } |
| 24 | |
| 25 | pub type PredicateFn = Arc<dyn Fn(&Value) -> Result<bool, String> + Send + Sync>; |
| 26 | |
| 27 | #[derive(Clone)] |
| 28 | pub struct PolicyRule { |
| 29 | pub name: String, |
| 30 | pub tool_pattern: String, |
| 31 | pub priority: PolicyPriority, |
| 32 | pub predicate: Option<PredicateFn>, |
| 33 | pub action: SafetyDecision, |
| 34 | } |
| 35 | |
| 36 | pub struct SafetyEngine { |
| 37 | rules: Vec<PolicyRule>, |
| 38 | workspaces: Vec<PathBuf>, |
| 39 | } |
| 40 | |
| 41 | impl SafetyEngine { |
| 42 | pub fn new() -> Self { |
| 43 | Self { |
| 44 | rules: Vec::new(), |
| 45 | workspaces: vec![ |
| 46 | PathBuf::from("/home/drakestapleton/workspace"), |
| 47 | PathBuf::from("/home/drakestapleton/atlas-prime-workspace"), |
| 48 | PathBuf::from("/home/drakestapleton/basecamp"), |
| 49 | PathBuf::from("/home/drakestapleton/spark-neural-os"), |
| 50 | PathBuf::from("/home/drakestapleton/skills"), |
| 51 | PathBuf::from("/home/drakestapleton/aien-cli"), |
| 52 | PathBuf::from("/home/drakestapleton/spark-cockpit"), |
| 53 | PathBuf::from("/home/drakestapleton/spark-cockpit-rs"), |
| 54 | PathBuf::from("/tmp"), |
| 55 | ], |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | pub fn add_rule(&mut self, rule: PolicyRule) { |
| 60 | self.rules.push(rule); |
| 61 | self.rules.sort_by_key(|r| r.priority); |
| 62 | } |
| 63 | |
| 64 | pub fn set_workspaces(&mut self, workspaces: Vec<PathBuf>) { |
| 65 | self.workspaces = workspaces; |
| 66 | } |
| 67 | |
| 68 | pub fn evaluate(&self, tool: &str, args: &Value) -> SafetyDecision { |
| 69 | for rule in &self.rules { |
| 70 | if !self.matches_tool_pattern(&rule.tool_pattern, tool) { |
| 71 | continue; |
| 72 | } |
| 73 | |
| 74 | if let Some(pred) = &rule.predicate { |
| 75 | match pred(args) { |
| 76 | Ok(true) => return rule.action.clone(), |
| 77 | Ok(false) => continue, |
| 78 | Err(err) => { |
| 79 | // Fail-closed guarantee from Antigravity SDK: |
| 80 | // Predicate evaluation failure treats the rule as matched for Deny/Ask |
| 81 | return match &rule.action { |
| 82 | SafetyDecision::Deny(msg) => SafetyDecision::Deny(format!("{}: [Predicate Evaluation Error: {}]", msg, err)), |
| 83 | SafetyDecision::AskUser(msg) => SafetyDecision::AskUser(format!("{}: [Predicate Evaluation Error: {}]", msg, err)), |
| 84 | SafetyDecision::Allow => SafetyDecision::Deny(format!("Predicate failed closed on allow rule: {}", err)), |
| 85 | }; |
| 86 | } |
| 87 | } |
| 88 | } else { |
| 89 | return rule.action.clone(); |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | // Default conservative fallback |
| 94 | SafetyDecision::AskUser(format!("No matching safety rule for tool '{}'", tool)) |
| 95 | } |
| 96 | |
| 97 | fn matches_tool_pattern(&self, pattern: &str, tool: &str) -> bool { |
| 98 | if pattern == "*" { |
| 99 | return true; |
| 100 | } |
| 101 | if pattern.ends_with("/*") { |
| 102 | let prefix = &pattern[..pattern.len() - 2]; |
| 103 | return tool.starts_with(prefix); |
| 104 | } |
| 105 | pattern == tool |
| 106 | } |
| 107 | |
| 108 | pub fn default_sovereign_engine() -> Self { |
| 109 | let mut engine = Self::new(); |
| 110 | |
| 111 | // 1. SPECIFIC DENY: Block writing plaintext secrets to .env or credential files |
| 112 | engine.add_rule(PolicyRule { |
| 113 | name: "deny_env_secrets".to_string(), |
| 114 | tool_pattern: "write_to_file".to_string(), |
| 115 | priority: PolicyPriority::SpecificDeny, |
| 116 | predicate: Some(Arc::new(|args| { |
| 117 | let path = args.get("path").and_then(Value::as_str).unwrap_or(""); |
| 118 | Ok(is_secret_leak_path(path)) |
| 119 | })), |
| 120 | action: SafetyDecision::Deny("REJECTED BY SOVEREIGN VAULT POLICY: Writing plaintext secrets into .env or credential files is forbidden. Use 'atlas-vault add <KEY>'.".to_string()), |
| 121 | }); |
| 122 | |
| 123 | engine.add_rule(PolicyRule { |
| 124 | name: "deny_env_secrets_replace".to_string(), |
| 125 | tool_pattern: "replace_file_content".to_string(), |
| 126 | priority: PolicyPriority::SpecificDeny, |
| 127 | predicate: Some(Arc::new(|args| { |
| 128 | let path = args.get("path").and_then(Value::as_str).unwrap_or(""); |
| 129 | Ok(is_secret_leak_path(path)) |
| 130 | })), |
| 131 | action: SafetyDecision::Deny("REJECTED BY SOVEREIGN VAULT POLICY: Writing plaintext secrets into .env or credential files is forbidden. Use 'atlas-vault add <KEY>'.".to_string()), |
| 132 | }); |
| 133 | |
| 134 | // 2. SPECIFIC DENY: Block writing unmasked API keys or private keys into any file |
| 135 | engine.add_rule(PolicyRule { |
| 136 | name: "deny_unmasked_secret_content".to_string(), |
| 137 | tool_pattern: "write_to_file".to_string(), |
| 138 | priority: PolicyPriority::SpecificDeny, |
| 139 | predicate: Some(Arc::new(|args| { |
| 140 | let content = args.get("content").and_then(Value::as_str).unwrap_or(""); |
| 141 | Ok(contains_unmasked_secret(content).is_some()) |
| 142 | })), |
| 143 | action: SafetyDecision::Deny("REJECTED BY SOVEREIGN VAULT POLICY: Plaintext API key or credential pattern detected. Use atlas-vault.".to_string()), |
| 144 | }); |
| 145 | |
| 146 | // 3. SPECIFIC ASK: Destructive commands require operator confirmation |
| 147 | engine.add_rule(PolicyRule { |
| 148 | name: "ask_destructive_commands".to_string(), |
| 149 | tool_pattern: "run_command".to_string(), |
| 150 | priority: PolicyPriority::SpecificAsk, |
| 151 | predicate: Some(Arc::new(|args| { |
| 152 | let cmd = args.get("command").and_then(Value::as_str).unwrap_or(""); |
| 153 | Ok(is_high_risk_command(cmd)) |
| 154 | })), |
| 155 | action: SafetyDecision::AskUser("Potentially destructive command detected.".to_string()), |
| 156 | }); |
| 157 | |
| 158 | // 4. SPECIFIC ASK: Writing to OS system paths (/etc, /boot, /root, /usr) |
| 159 | engine.add_rule(PolicyRule { |
| 160 | name: "ask_system_path_writes".to_string(), |
| 161 | tool_pattern: "write_to_file".to_string(), |
| 162 | priority: PolicyPriority::SpecificAsk, |
| 163 | predicate: Some(Arc::new(|args| { |
| 164 | let path = args.get("path").and_then(Value::as_str).unwrap_or(""); |
| 165 | Ok(is_high_risk_path(path)) |
| 166 | })), |
| 167 | action: SafetyDecision::AskUser("Writing to system operating system path requires operator confirmation.".to_string()), |
| 168 | }); |
| 169 | |
| 170 | // 5. SPECIFIC ALLOW: Safe standard tool execution |
| 171 | let safe_tools = [ |
| 172 | "view_file", "list_dir", "grep_search", "crumb", |
| 173 | "vault", "goal", "skill", "cortex", "walkthrough", "hive", |
| 174 | "sandbox", "browser", "invoke_subagent", "subagent", "subagents", |
| 175 | "adapter", "model_adapter", "model_adapters", "socratic", "socratic_inquiry" |
| 176 | ]; |
| 177 | for st in safe_tools { |
| 178 | engine.add_rule(PolicyRule { |
| 179 | name: format!("allow_{}", st), |
| 180 | tool_pattern: st.to_string(), |
| 181 | priority: PolicyPriority::SpecificAllow, |
| 182 | predicate: None, |
| 183 | action: SafetyDecision::Allow, |
| 184 | }); |
| 185 | } |
| 186 | |
| 187 | // 6. GLOBAL WILDCARD ALLOW: Permissive default for verified standard commands |
| 188 | engine.add_rule(PolicyRule { |
| 189 | name: "allow_standard_commands".to_string(), |
| 190 | tool_pattern: "run_command".to_string(), |
| 191 | priority: PolicyPriority::GlobalWildcardAllow, |
| 192 | predicate: None, |
| 193 | action: SafetyDecision::Allow, |
| 194 | }); |
| 195 | |
| 196 | engine.add_rule(PolicyRule { |
| 197 | name: "allow_standard_writes".to_string(), |
| 198 | tool_pattern: "write_to_file".to_string(), |
| 199 | priority: PolicyPriority::GlobalWildcardAllow, |
| 200 | predicate: None, |
| 201 | action: SafetyDecision::Allow, |
| 202 | }); |
| 203 | |
| 204 | engine.add_rule(PolicyRule { |
| 205 | name: "allow_standard_replaces".to_string(), |
| 206 | tool_pattern: "replace_file_content".to_string(), |
| 207 | priority: PolicyPriority::GlobalWildcardAllow, |
| 208 | predicate: None, |
| 209 | action: SafetyDecision::Allow, |
| 210 | }); |
| 211 | |
| 212 | engine.add_rule(PolicyRule { |
| 213 | name: "allow_standard_create_dir".to_string(), |
| 214 | tool_pattern: "create_dir".to_string(), |
| 215 | priority: PolicyPriority::GlobalWildcardAllow, |
| 216 | predicate: None, |
| 217 | action: SafetyDecision::Allow, |
| 218 | }); |
| 219 | |
| 220 | engine |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | pub fn is_high_risk_command(cmd: &str) -> bool { |
| 225 | let lower = cmd.to_lowercase(); |
| 226 | let dangerous_patterns = [ |
| 227 | "rm -rf /", |
| 228 | "rm -rf ~", |
| 229 | "rm -rf /home", |
| 230 | "mkfs", |
| 231 | "dd if=", |
| 232 | "fdisk", |
| 233 | "> /dev/sd", |
| 234 | "> /dev/nvme", |
| 235 | "shutdown", |
| 236 | "reboot", |
| 237 | "drop database", |
| 238 | "drop table", |
| 239 | "truncate table", |
| 240 | "kill -9 1", |
| 241 | ]; |
| 242 | |
| 243 | for pattern in dangerous_patterns { |
| 244 | if lower.contains(pattern) { |
| 245 | return true; |
| 246 | } |
| 247 | } |
| 248 | false |
| 249 | } |
| 250 | |
| 251 | pub fn is_high_risk_path(path: &str) -> bool { |
| 252 | let lower = path.to_lowercase(); |
| 253 | lower.starts_with("/etc") |
| 254 | || lower.starts_with("/boot") |
| 255 | || lower.starts_with("/root") |
| 256 | || lower.starts_with("/usr") |
| 257 | } |
| 258 | |
| 259 | pub fn is_secret_leak_path(path: &str) -> bool { |
| 260 | let p = Path::new(path); |
| 261 | let file_name = p.file_name().and_then(|f| f.to_str()).unwrap_or("").to_lowercase(); |
| 262 | |
| 263 | if file_name == ".env" || file_name.starts_with(".env.") || file_name.ends_with(".env") { |
| 264 | return true; |
| 265 | } |
| 266 | if file_name == "secrets.json" || file_name == "credentials.json" || file_name == "id_rsa" { |
| 267 | return true; |
| 268 | } |
| 269 | false |
| 270 | } |
| 271 | |
| 272 | pub fn contains_unmasked_secret(content: &str) -> Option<&'static str> { |
| 273 | let lower = content.to_lowercase(); |
| 274 | if lower.contains("api_key=") || lower.contains("secret_key=") || lower.contains("auth_token=") { |
| 275 | return Some("Plaintext key assignment pattern detected (e.g. API_KEY=...)"); |
| 276 | } |
| 277 | if content.contains("sk-proj-") || content.contains("ghp_") || content.contains("AIzaSy") { |
| 278 | return Some("Live API key signature detected (sk-, ghp-, AIzaSy)"); |
| 279 | } |
| 280 | None |
| 281 | } |
| 282 | |
| 283 | #[cfg(test)] |
| 284 | mod tests { |
| 285 | use super::*; |
| 286 | use serde_json::json; |
| 287 | |
| 288 | #[test] |
| 289 | fn test_secret_leak_paths() { |
| 290 | assert!(is_secret_leak_path(".env")); |
| 291 | assert!(is_secret_leak_path("/path/to/.env")); |
| 292 | assert!(is_secret_leak_path(".env.local")); |
| 293 | assert!(is_secret_leak_path("production.env")); |
| 294 | assert!(is_secret_leak_path("secrets.json")); |
| 295 | assert!(!is_secret_leak_path("environment.rs")); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn test_unmasked_secret_patterns() { |
| 300 | assert!(contains_unmasked_secret("API_KEY=\"abcdefghijklmnop\"").is_some()); |
| 301 | assert!(contains_unmasked_secret("export sk-proj-1234567890abcdef").is_some()); |
| 302 | assert!(contains_unmasked_secret("ghp_1234567890abcdef").is_some()); |
| 303 | assert!(contains_unmasked_secret("let normal_code = true;").is_none()); |
| 304 | } |
| 305 | |
| 306 | #[test] |
| 307 | fn test_policy_precedence_and_fail_closed() { |
| 308 | let engine = SafetyEngine::default_sovereign_engine(); |
| 309 | |
| 310 | // 1. Specific Deny beats everything: writing to .env |
| 311 | let env_args = json!({"path": "/home/drakestapleton/workspace/.env", "content": "KEY=123"}); |
| 312 | assert!(matches!(engine.evaluate("write_to_file", &env_args), SafetyDecision::Deny(_))); |
| 313 | |
| 314 | // 2. Specific Ask: high-risk command |
| 315 | let rm_args = json!({"command": "rm -rf /", "cwd": "."}); |
| 316 | assert!(matches!(engine.evaluate("run_command", &rm_args), SafetyDecision::AskUser(_))); |
| 317 | |
| 318 | // 3. Specific Allow: standard read |
| 319 | let view_args = json!({"path": "src/main.rs"}); |
| 320 | assert_eq!(engine.evaluate("view_file", &view_args), SafetyDecision::Allow); |
| 321 | |
| 322 | // 4. Global Allow: standard harmless command |
| 323 | let ls_args = json!({"command": "cargo check", "cwd": "."}); |
| 324 | assert_eq!(engine.evaluate("run_command", &ls_args), SafetyDecision::Allow); |
| 325 | } |
| 326 | } |