interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-cli / src / safety.rs

581 lines · 20991 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use serde_json::Value;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19
20use crate::platform::PlatformContext;
21
22#[derive(Debug, Clone, PartialEq)]
23pub enum SafetyDecision {
24 Allow,
25 AskUser(String),
26 Deny(String),
27}
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
30#[allow(dead_code)]
31pub enum PolicyPriority {
32 SpecificDeny = 1,
33 SpecificAsk = 2,
34 SpecificAllow = 3,
35 PrefixWildcardDeny = 4,
36 PrefixWildcardAsk = 5,
37 PrefixWildcardAllow = 6,
38 GlobalWildcardDeny = 7,
39 GlobalWildcardAsk = 8,
40 GlobalWildcardAllow = 9,
41}
42
43pub type PredicateFn = Arc<dyn Fn(&Value) -> Result<bool, String> + Send + Sync>;
44
45#[derive(Clone)]
46#[allow(dead_code)]
47pub struct PolicyRule {
48 pub name: String,
49 pub tool_pattern: String,
50 pub priority: PolicyPriority,
51 pub predicate: Option<PredicateFn>,
52 pub action: SafetyDecision,
53}
54
55pub struct SafetyEngine {
56 rules: Vec<PolicyRule>,
57 workspaces: Vec<PathBuf>,
58}
59
60impl SafetyEngine {
61 pub fn new() -> Self {
62 let platform = PlatformContext::detect();
63 let mut workspaces = platform.default_workspaces;
64 workspaces.push(PathBuf::from("/tmp"));
65
66 Self {
67 rules: Vec::new(),
68 workspaces,
69 }
70 }
71
72 #[allow(dead_code)]
73 pub fn workspaces(&self) -> &[PathBuf] {
74 &self.workspaces
75 }
76
77 pub fn add_rule(&mut self, rule: PolicyRule) {
78 self.rules.push(rule);
79 self.rules.sort_by_key(|r| r.priority);
80 }
81
82 #[allow(dead_code)]
83 pub fn set_workspaces(&mut self, workspaces: Vec<PathBuf>) {
84 self.workspaces = workspaces;
85 }
86
87 pub fn validate_path(&self, path: &str) -> Result<PathBuf, String> {
88 validate_workspace_path(path, &self.workspaces)
89 }
90
91 pub fn evaluate(&self, tool: &str, args: &Value) -> SafetyDecision {
92 // Foundational Primitive: Path Confinement for all filesystem tools
93 match tool {
94 "view_file" | "write_to_file" | "replace_file_content" | "list_dir" | "create_dir" => {
95 if let Some(path_str) = args.get("path").and_then(Value::as_str) {
96 if let Err(err) = self.validate_path(path_str) {
97 return SafetyDecision::Deny(format!("CONFINEMENT DENIAL: {}", err));
98 }
99 }
100 }
101 "run_command" => {
102 if let Some(cwd_str) = args.get("cwd").and_then(Value::as_str) {
103 if let Err(err) = self.validate_path(cwd_str) {
104 return SafetyDecision::Deny(format!(
105 "CONFINEMENT DENIAL: Invalid command working directory: {}",
106 err
107 ));
108 }
109 }
110 }
111 _ => {}
112 }
113
114 for rule in &self.rules {
115 if !self.matches_tool_pattern(&rule.tool_pattern, tool) {
116 continue;
117 }
118
119 if let Some(pred) = &rule.predicate {
120 match pred(args) {
121 Ok(true) => return rule.action.clone(),
122 Ok(false) => continue,
123 Err(err) => {
124 // Fail-closed guarantee from Antigravity SDK:
125 // Predicate evaluation failure treats the rule as matched for Deny/Ask
126 return match &rule.action {
127 SafetyDecision::Deny(msg) => SafetyDecision::Deny(format!(
128 "{}: [Predicate Evaluation Error: {}]",
129 msg, err
130 )),
131 SafetyDecision::AskUser(msg) => SafetyDecision::AskUser(format!(
132 "{}: [Predicate Evaluation Error: {}]",
133 msg, err
134 )),
135 SafetyDecision::Allow => SafetyDecision::Deny(format!(
136 "Predicate failed closed on allow rule: {}",
137 err
138 )),
139 };
140 }
141 }
142 } else {
143 return rule.action.clone();
144 }
145 }
146
147 // Default conservative fallback
148 SafetyDecision::AskUser(format!("No matching safety rule for tool '{}'", tool))
149 }
150
151 fn matches_tool_pattern(&self, pattern: &str, tool: &str) -> bool {
152 if pattern == "*" {
153 return true;
154 }
155 if let Some(prefix) = pattern.strip_suffix("/*") {
156 return tool.starts_with(prefix);
157 }
158 pattern == tool
159 }
160
161 pub fn default_sovereign_engine() -> Self {
162 let mut engine = Self::new();
163
164 // 1. SPECIFIC DENY: Block writing plaintext secrets to disk (.env / keys)
165 engine.add_rule(PolicyRule {
166 name: "deny_env_secret_writes".to_string(),
167 tool_pattern: "write_to_file".to_string(),
168 priority: PolicyPriority::SpecificDeny,
169 predicate: Some(Arc::new(|args| {
170 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
171 Ok(is_secret_leak_path(path))
172 })),
173 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()),
174 });
175
176 engine.add_rule(PolicyRule {
177 name: "deny_env_secret_replaces".to_string(),
178 tool_pattern: "replace_file_content".to_string(),
179 priority: PolicyPriority::SpecificDeny,
180 predicate: Some(Arc::new(|args| {
181 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
182 Ok(is_secret_leak_path(path))
183 })),
184 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()),
185 });
186
187 // 2. SPECIFIC DENY: Block writing unmasked API keys or private keys into any file
188 engine.add_rule(PolicyRule {
189 name: "deny_unmasked_secret_content".to_string(),
190 tool_pattern: "write_to_file".to_string(),
191 priority: PolicyPriority::SpecificDeny,
192 predicate: Some(Arc::new(|args| {
193 let content = args.get("content").and_then(Value::as_str).unwrap_or("");
194 Ok(contains_unmasked_secret(content).is_some())
195 })),
196 action: SafetyDecision::Deny("REJECTED BY SOVEREIGN VAULT POLICY: Plaintext API key or credential pattern detected. Use atlas-vault.".to_string()),
197 });
198
199 // 3. SPECIFIC ASK: Destructive commands require operator confirmation
200 engine.add_rule(PolicyRule {
201 name: "ask_destructive_commands".to_string(),
202 tool_pattern: "run_command".to_string(),
203 priority: PolicyPriority::SpecificAsk,
204 predicate: Some(Arc::new(|args| {
205 let cmd = args.get("command").and_then(Value::as_str).unwrap_or("");
206 Ok(is_high_risk_command(cmd))
207 })),
208 action: SafetyDecision::AskUser(
209 "Potentially destructive command detected.".to_string(),
210 ),
211 });
212
213 // 4. SPECIFIC ASK: Writing to OS system paths (/etc, /boot, /root, /usr)
214 engine.add_rule(PolicyRule {
215 name: "ask_system_path_writes".to_string(),
216 tool_pattern: "write_to_file".to_string(),
217 priority: PolicyPriority::SpecificAsk,
218 predicate: Some(Arc::new(|args| {
219 let path = args.get("path").and_then(Value::as_str).unwrap_or("");
220 Ok(is_high_risk_path(path))
221 })),
222 action: SafetyDecision::AskUser(
223 "Writing to system operating system path requires operator confirmation."
224 .to_string(),
225 ),
226 });
227
228 // 5. SPECIFIC ALLOW: Safe standard tool execution
229 let safe_tools = [
230 "view_file",
231 "list_dir",
232 "grep_search",
233 "crumb",
234 "vault",
235 "goal",
236 "skill",
237 "cortex",
238 "walkthrough",
239 "hive",
240 "sandbox",
241 "browser",
242 "invoke_subagent",
243 "subagent",
244 "subagents",
245 "adapter",
246 "model_adapter",
247 "model_adapters",
248 "socratic",
249 "socratic_inquiry",
250 ];
251 for st in safe_tools {
252 engine.add_rule(PolicyRule {
253 name: format!("allow_{}", st),
254 tool_pattern: st.to_string(),
255 priority: PolicyPriority::SpecificAllow,
256 predicate: None,
257 action: SafetyDecision::Allow,
258 });
259 }
260
261 // `run_command` has no wildcard allow. Manual mode asks the person.
262 engine.add_rule(PolicyRule {
263 name: "allow_standard_writes".to_string(),
264 tool_pattern: "write_to_file".to_string(),
265 priority: PolicyPriority::GlobalWildcardAllow,
266 predicate: None,
267 action: SafetyDecision::Allow,
268 });
269
270 engine.add_rule(PolicyRule {
271 name: "allow_standard_replaces".to_string(),
272 tool_pattern: "replace_file_content".to_string(),
273 priority: PolicyPriority::GlobalWildcardAllow,
274 predicate: None,
275 action: SafetyDecision::Allow,
276 });
277
278 engine.add_rule(PolicyRule {
279 name: "allow_standard_create_dir".to_string(),
280 tool_pattern: "create_dir".to_string(),
281 priority: PolicyPriority::GlobalWildcardAllow,
282 predicate: None,
283 action: SafetyDecision::Allow,
284 });
285
286 engine
287 }
288}
289
290pub fn validate_workspace_path<P: AsRef<Path>>(
291 path: P,
292 workspaces: &[PathBuf],
293) -> Result<PathBuf, String> {
294 let raw = path.as_ref();
295 let absolute = if raw.is_relative() {
296 match std::env::current_dir() {
297 Ok(cwd) => cwd.join(raw),
298 Err(e) => {
299 return Err(format!(
300 "Failed to determine current working directory: {}",
301 e
302 ))
303 }
304 }
305 } else {
306 raw.to_path_buf()
307 };
308
309 // Keep the original component order. Collapsing `..` before resolving
310 // symlinks can validate a different target from the path the OS opens.
311 // This is the workspace allow-list check only. It does not pin a
312 // descriptor: callers that then open by name can still observe a
313 // different object. CLI tool bodies bind the authorized path with
314 // `fs_bind` (openat2 beneath a held workspace directory).
315 let mut existing_ancestor = absolute.as_path();
316 let mut subparts = Vec::new();
317 loop {
318 match std::fs::symlink_metadata(existing_ancestor) {
319 Ok(_) => break,
320 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
321 // Only plain missing names can safely be reconstructed. A
322 // parent traversal through a missing component has no resolved
323 // filesystem meaning; ask the caller to name the target directly.
324 match existing_ancestor.components().next_back() {
325 Some(std::path::Component::Normal(name)) => subparts.push(name),
326 _ => {
327 return Err(format!(
328 "Cannot resolve path '{}': use a direct path below an existing workspace directory",
329 raw.display()
330 ));
331 }
332 }
333 existing_ancestor = existing_ancestor
334 .parent()
335 .ok_or_else(|| format!("Cannot resolve parent of '{}'", raw.display()))?;
336 }
337 Err(e) => {
338 return Err(format!(
339 "Failed to inspect path '{}': {}",
340 existing_ancestor.display(),
341 e
342 ));
343 }
344 }
345 }
346
347 // symlink_metadata notices a dangling link rather than treating it as
348 // an absent name. canonicalize then refuses its unresolved target.
349 let canon_ancestor = existing_ancestor.canonicalize().map_err(|e| {
350 format!(
351 "Failed to canonicalize ancestor '{}': {}",
352 existing_ancestor.display(),
353 e
354 )
355 })?;
356
357 let mut canonical = canon_ancestor;
358 for part in subparts.into_iter().rev() {
359 canonical.push(part);
360 }
361
362 // Verify that the canonical path is enclosed within at least one permitted workspace root
363 let permitted = workspaces.iter().any(|ws| {
364 let ws_canon = ws.canonicalize().unwrap_or_else(|_| ws.clone());
365 canonical.starts_with(&ws_canon)
366 });
367
368 if !permitted {
369 return Err(format!(
370 "Path '{}' resolves to '{}' which is outside permitted workspace roots",
371 raw.display(),
372 canonical.display()
373 ));
374 }
375
376 Ok(canonical)
377}
378
379pub fn is_high_risk_command(cmd: &str) -> bool {
380 let lower = cmd.to_lowercase();
381 let dangerous_patterns = [
382 "rm -rf /",
383 "rm -rf ~",
384 "rm -rf /home",
385 "mkfs",
386 "dd if=",
387 "fdisk",
388 "> /dev/sd",
389 "> /dev/nvme",
390 "shutdown",
391 "reboot",
392 "drop database",
393 "drop table",
394 "truncate table",
395 "kill -9 1",
396 ];
397
398 for pattern in dangerous_patterns {
399 if lower.contains(pattern) {
400 return true;
401 }
402 }
403 false
404}
405
406pub fn is_high_risk_path(path: &str) -> bool {
407 let lower = path.to_lowercase();
408 lower.starts_with("/etc")
409 || lower.starts_with("/boot")
410 || lower.starts_with("/root")
411 || lower.starts_with("/usr")
412}
413
414pub fn is_secret_leak_path(path: &str) -> bool {
415 let p = Path::new(path);
416 let file_name = p
417 .file_name()
418 .and_then(|f| f.to_str())
419 .unwrap_or("")
420 .to_lowercase();
421
422 if file_name == ".env" || file_name.starts_with(".env.") || file_name.ends_with(".env") {
423 return true;
424 }
425 if file_name == "secrets.json" || file_name == "credentials.json" || file_name == "id_rsa" {
426 return true;
427 }
428 false
429}
430
431pub fn contains_unmasked_secret(content: &str) -> Option<&'static str> {
432 let lower = content.to_lowercase();
433 if lower.contains("api_key=") || lower.contains("secret_key=") || lower.contains("auth_token=")
434 {
435 return Some("Plaintext key assignment pattern detected (e.g. API_KEY=...)");
436 }
437 if content.contains("sk-proj-") || content.contains("ghp_") || content.contains("AIzaSy") {
438 return Some("Live API key signature detected (sk-, ghp-, AIzaSy)");
439 }
440 None
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446 use serde_json::json;
447
448 #[test]
449 fn test_secret_leak_paths() {
450 assert!(is_secret_leak_path(".env"));
451 assert!(is_secret_leak_path("/path/to/.env"));
452 assert!(is_secret_leak_path(".env.local"));
453 assert!(is_secret_leak_path("production.env"));
454 assert!(is_secret_leak_path("secrets.json"));
455 assert!(!is_secret_leak_path("environment.rs"));
456 }
457
458 #[test]
459 fn test_unmasked_secret_patterns() {
460 assert!(contains_unmasked_secret("API_KEY=\"abcdefghijklmnop\"").is_some());
461 assert!(contains_unmasked_secret("export sk-proj-1234567890abcdef").is_some());
462 assert!(contains_unmasked_secret("ghp_1234567890abcdef").is_some());
463 assert!(contains_unmasked_secret("let normal_code = true;").is_none());
464 }
465
466 #[test]
467 fn test_path_confinement_validation() {
468 let tmp = std::env::temp_dir();
469 let allowed = vec![tmp.clone()];
470
471 // Allowed path inside temp_dir
472 let ok_file = tmp.join("test_file.txt");
473 assert!(validate_workspace_path(&ok_file, &allowed).is_ok());
474
475 // Escape attempt via parent traversal on existing path
476 let escape_path = tmp.join("../etc/shadow");
477 assert!(validate_workspace_path(&escape_path, &allowed).is_err());
478
479 // Escape attempt via parent traversal on non-existent path
480 let nonexistent_escape = tmp.join("does_not_exist/../../etc/passwd");
481 assert!(validate_workspace_path(&nonexistent_escape, &allowed).is_err());
482 }
483
484 #[cfg(unix)]
485 #[test]
486 fn path_confinement_respects_parent_after_symlink() {
487 use std::os::unix::fs::symlink;
488 let root = tempfile::tempdir().unwrap();
489 let workspace = root.path().join("workspace");
490 let outside = root.path().join("outside");
491 std::fs::create_dir(&workspace).unwrap();
492 std::fs::create_dir_all(outside.join("child")).unwrap();
493 std::fs::write(outside.join("sentinel"), "synthetic").unwrap();
494 symlink(outside.join("child"), workspace.join("link")).unwrap();
495 let allowed = vec![workspace.clone()];
496 assert!(validate_workspace_path(workspace.join("link/../sentinel"), &allowed).is_err());
497 assert!(validate_workspace_path(workspace.join("link/../newdir"), &allowed).is_err());
498 }
499
500 #[cfg(unix)]
501 #[test]
502 fn path_confinement_refuses_dangling_symlink_creation() {
503 use std::os::unix::fs::symlink;
504 let root = tempfile::tempdir().unwrap();
505 let workspace = root.path().join("workspace");
506 let outside = root.path().join("outside");
507 std::fs::create_dir(&workspace).unwrap();
508 std::fs::create_dir(&outside).unwrap();
509 symlink(outside.join("newfile"), workspace.join("newfile")).unwrap();
510 assert!(validate_workspace_path(workspace.join("newfile"), &[workspace]).is_err());
511 assert!(!outside.join("newfile").exists());
512 }
513
514 #[test]
515 fn path_confinement_allows_normal_missing_suffix() {
516 let workspace = tempfile::tempdir().unwrap();
517 let path = workspace.path().join("newdir/newfile");
518 let expected = workspace
519 .path()
520 .canonicalize()
521 .unwrap()
522 .join("newdir/newfile");
523 assert_eq!(
524 validate_workspace_path(&path, &[workspace.path().to_path_buf()]).unwrap(),
525 expected
526 );
527 }
528
529 #[cfg(unix)]
530 #[test]
531 fn path_confinement_preserves_safe_symlinks_and_existing_parent_traversal() {
532 use std::os::unix::fs::symlink;
533 let workspace = tempfile::tempdir().unwrap();
534 let root = workspace.path();
535 std::fs::create_dir(root.join("child")).unwrap();
536 std::fs::write(root.join("sentinel"), "synthetic").unwrap();
537 symlink(root.join("child"), root.join("link")).unwrap();
538 let expected = root.canonicalize().unwrap().join("sentinel");
539 assert_eq!(
540 validate_workspace_path(root.join("link/../sentinel"), &[root.to_path_buf()]).unwrap(),
541 expected
542 );
543 assert!(validate_workspace_path(root.join("link/newfile"), &[root.to_path_buf()]).is_ok());
544 }
545
546 #[test]
547 fn path_confinement_refuses_unresolved_parent_components() {
548 let workspace = tempfile::tempdir().unwrap();
549 assert!(validate_workspace_path(
550 workspace.path().join("absent/../newfile"),
551 &[workspace.path().to_path_buf()]
552 )
553 .is_err());
554 }
555
556 #[test]
557 fn test_policy_precedence_and_fail_closed() {
558 let engine = SafetyEngine::default_sovereign_engine();
559
560 // 1. Specific Deny beats everything: writing to .env
561 let env_args = json!({"path": "/tmp/.env", "content": "KEY=123"});
562 assert!(matches!(
563 engine.evaluate("write_to_file", &env_args),
564 SafetyDecision::Deny(_)
565 ));
566
567 // 2. Specific Ask: high-risk command
568 let rm_args = json!({"command": "rm -rf /", "cwd": "/tmp"});
569 assert!(matches!(
570 engine.evaluate("run_command", &rm_args),
571 SafetyDecision::AskUser(_)
572 ));
573
574 // 3. Specific Allow: standard read within allowed path
575 let view_args = json!({"path": "/tmp/test.rs"});
576 assert_eq!(
577 engine.evaluate("view_file", &view_args),
578 SafetyDecision::Allow
579 );
580 }
581}