Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/spark-aegis/src/audit.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / spark-aegis / src / audit.rs` 219 lines ยท 7121 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 16 // spark-aegis Live System and Workspace Confinement Audit Engine 17 // Inspects active listening sockets, workspace secrets, and host invariants 18 19 use anyhow::Result; 20 use chrono::{DateTime, Utc}; 21 use serde::{Deserialize, Serialize}; 22 use std::fs; 23 use std::path::{Path, PathBuf}; 24 use std::process::Command; 25 26 #[derive(Debug, Clone, Serialize, Deserialize)] 27 pub struct SocketAudit { 28 pub protocol: String, 29 pub local_address: String, 30 pub is_loopback: bool, 31 pub process_name: Option, 32 } 33 34 #[derive(Debug, Clone, Serialize, Deserialize)] 35 pub struct WorkspaceAudit { 36 pub path: PathBuf, 37 pub dot_env_found: Vec, 38 pub exposed_keys_found: Vec, 39 pub secure_tpm_only: bool, 40 } 41 42 #[derive(Debug, Clone, Serialize, Deserialize)] 43 pub struct LiveAuditReport { 44 pub timestamp: DateTime, 45 pub sockets: Vec, 46 pub non_loopback_sockets_count: usize, 47 pub workspace: WorkspaceAudit, 48 pub cortex_online: bool, 49 pub cortex_version: Option, 50 pub blake3_digest: String, 51 pub overall_safe: bool, 52 } 53 54 pub async fn audit_system() -> Result { 55 let ts = Utc::now(); 56 57 // 1. Audit listening sockets 58 let sockets = audit_listening_sockets(); 59 let non_loopback_count = sockets.iter().filter(|s| !s.is_loopback).count(); 60 61 // 2. Audit workspace confinement 62 let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); 63 let workspace_dir = PathBuf::from(home).join("workspace"); 64 let workspace = audit_workspace_dir(&workspace_dir); 65 66 // 3. Audit Cortex memory engine 67 let (cortex_online, cortex_version) = check_cortex_health().await; 68 69 // Overall safety: no plaintext secrets in workspace 70 let overall_safe = workspace.secure_tpm_only; 71 72 // Cryptographic hash of audit report 73 let digest_seed = format!( 74 "{}:{}:{}:{}", 75 ts, non_loopback_count, workspace.secure_tpm_only, cortex_online 76 ); 77 let blake3_digest = blake3::hash(digest_seed.as_bytes()).to_hex().to_string(); 78 79 Ok(LiveAuditReport { 80 timestamp: ts, 81 sockets, 82 non_loopback_sockets_count: non_loopback_count, 83 workspace, 84 cortex_online, 85 cortex_version, 86 blake3_digest, 87 overall_safe, 88 }) 89 } 90 91 fn audit_listening_sockets() -> Vec { 92 let mut results = Vec::new(); 93 94 // Try `ss -tulpn` 95 if let Ok(output) = Command::new("ss").args(["-tulpn"]).output() { 96 let text = String::from_utf8_lossy(&output.stdout); 97 for line in text.lines().skip(1) { 98 let parts: Vec<&str> = line.split_whitespace().collect(); 99 if parts.len() >= 5 { 100 let proto = parts[0].to_string(); 101 let addr_str = parts[4]; 102 let is_loop = addr_str.starts_with("127.") || addr_str.starts_with("[::1]"); 103 let proc_name = if parts.len() >= 7 { 104 Some(parts[6].to_string()) 105 } else { 106 None 107 }; 108 109 results.push(SocketAudit { 110 protocol: proto, 111 local_address: addr_str.to_string(), 112 is_loopback: is_loop, 113 process_name: proc_name, 114 }); 115 } 116 } 117 } 118 119 results 120 } 121 122 fn audit_workspace_dir(dir: &Path) -> WorkspaceAudit { 123 let mut dot_envs = Vec::new(); 124 let mut exposed_keys = Vec::new(); 125 126 if dir.exists() && dir.is_dir() { 127 let mut stack = vec![dir.to_path_buf()]; 128 let mut files_checked = 0; 129 130 while let Some(current) = stack.pop() { 131 if files_checked > 2000 { 132 break; // Boundary limit 133 } 134 if let Ok(entries) = fs::read_dir(¤t) { 135 for entry in entries.flatten() { 136 let p = entry.path(); 137 let name = match p.file_name().and_then(|s| s.to_str()) { 138 Some(n) => n, 139 None => continue, 140 }; 141 142 if name == ".git" || name == "target" || name == "node_modules" { 143 continue; 144 } 145 146 if p.is_dir() { 147 stack.push(p); 148 } else if p.is_file() { 149 files_checked += 1; 150 if name == ".env" || name.starts_with(".env.") { 151 dot_envs.push(p.clone()); 152 } 153 if name.ends_with(".key") || name.ends_with(".pem") || name == "id_rsa" { 154 exposed_keys.push(p.clone()); 155 } 156 } 157 } 158 } 159 } 160 } 161 162 let secure_tpm_only = dot_envs.is_empty() && exposed_keys.is_empty(); 163 164 WorkspaceAudit { 165 path: dir.to_path_buf(), 166 dot_env_found: dot_envs, 167 exposed_keys_found: exposed_keys, 168 secure_tpm_only, 169 } 170 } 171 172 async fn check_cortex_health() -> (bool, Option) { 173 let client = reqwest::Client::builder() 174 .timeout(std::time::Duration::from_millis(1500)) 175 .build(); 176 177 if let Ok(c) = client { 178 let cortex_url = std::env::var("CORTEX_HEALTH_URL") 179 .unwrap_or_else(|_| "http://127.0.0.1:18080/health".to_string()); 180 if let Ok(resp) = c.get(&cortex_url).send().await { 181 if resp.status().is_success() { 182 if let Ok(json) = resp.json::().await { 183 let ver = json 184 .get("version") 185 .and_then(|v| v.as_str()) 186 .map(|s| s.to_string()); 187 return (true, ver); 188 } 189 return (true, None); 190 } 191 } 192 } 193 194 (false, None) 195 } 196 197 #[cfg(test)] 198 mod tests { 199 use super::*; 200 201 #[test] 202 fn test_workspace_audit_empty_tmp() { 203 let tmp = tempfile::tempdir().unwrap(); 204 let audit = audit_workspace_dir(tmp.path()); 205 assert!(audit.secure_tpm_only); 206 assert!(audit.dot_env_found.is_empty()); 207 } 208 209 #[test] 210 fn test_workspace_audit_flags_dotenv() { 211 let tmp = tempfile::tempdir().unwrap(); 212 let env_file = tmp.path().join(".env"); 213 fs::write(&env_file, b"SECRET=true").unwrap(); 214 215 let audit = audit_workspace_dir(tmp.path()); 216 assert!(!audit.secure_tpm_only); 217 assert_eq!(audit.dot_env_found.len(), 1); 218 } 219 }