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-debugger/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-debugger / src / audit.rs` 256 lines ยท 8538 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 use aien_localhttp::Client; 17 use serde::{Deserialize, Serialize}; 18 use std::path::Path; 19 use std::time::Duration; 20 use tokio::process::Command; 21 22 #[derive(Debug, Clone, Serialize, Deserialize)] 23 pub struct ServiceAuditResult { 24 pub name: String, 25 pub endpoint: String, 26 pub reachable: bool, 27 pub status_code: Option, 28 pub latency_ms: u64, 29 } 30 31 #[derive(Debug, Clone, Serialize, Deserialize)] 32 pub struct InvariantAuditResult { 33 pub passed: bool, 34 pub plaintext_env_files_found: Vec, 35 pub unredacted_secrets_found: usize, 36 pub unslop_violations: Vec, 37 } 38 39 #[derive(Debug, Clone, Serialize, Deserialize)] 40 pub struct BuildAuditResult { 41 pub passed: bool, 42 pub errors: Vec, 43 pub warnings: Vec, 44 } 45 46 #[derive(Debug, Clone, Serialize, Deserialize)] 47 pub struct SystemAuditReport { 48 pub timestamp: String, 49 pub services: Vec, 50 pub invariants: InvariantAuditResult, 51 pub build: BuildAuditResult, 52 pub overall_healthy: bool, 53 } 54 55 const SERVICE_ENDPOINTS: [(&str, &str); 5] = [ 56 ("Cortex Memory", "http://127.0.0.1:18080/health"), 57 ("Sovereign Cockpit", "http://127.0.0.1:18095/api/pulse"), 58 ("Cortex ONNX Encoder", "http://127.0.0.1:18081/health"), 59 ("Local Model Seat", "http://127.0.0.1:18006/v1/models"), 60 ("Matrix Conduit", "http://127.0.0.1:6167"), 61 ]; 62 63 pub async fn audit_services(client: &Client) -> Vec { 64 audit_endpoints(client, &SERVICE_ENDPOINTS).await 65 } 66 67 /// Probes each endpoint once (1500 ms each). Reachable means any answer 68 /// below 500; a connect error, timeout or malformed reply is unreachable. 69 async fn audit_endpoints(client: &Client, endpoints: &[(&str, &str)]) -> Vec { 70 let mut results = Vec::new(); 71 for &(name, ep) in endpoints { 72 let start = std::time::Instant::now(); 73 match client 74 .get(ep) 75 .timeout(Duration::from_millis(1500)) 76 .send() 77 .await 78 { 79 Ok(res) => { 80 let status = res.status().as_u16(); 81 results.push(ServiceAuditResult { 82 name: name.to_string(), 83 endpoint: ep.to_string(), 84 reachable: status < 500, 85 status_code: Some(status), 86 latency_ms: start.elapsed().as_millis() as u64, 87 }); 88 } 89 Err(_) => { 90 results.push(ServiceAuditResult { 91 name: name.to_string(), 92 endpoint: ep.to_string(), 93 reachable: false, 94 status_code: None, 95 latency_ms: start.elapsed().as_millis() as u64, 96 }); 97 } 98 } 99 } 100 results 101 } 102 103 pub fn audit_vault_and_unslop(workspace_paths: &[&str]) -> InvariantAuditResult { 104 let mut plaintext_env = Vec::new(); 105 let unslop_violations = Vec::new(); 106 107 for base in workspace_paths { 108 let p = Path::new(base); 109 if !p.exists() { 110 continue; 111 } 112 113 // Scan for .env files 114 if let Ok(entries) = std::fs::read_dir(p) { 115 for entry in entries.flatten() { 116 let file_name = entry.file_name().to_string_lossy().to_string(); 117 if file_name.starts_with(".env") { 118 plaintext_env.push(entry.path().to_string_lossy().to_string()); 119 } 120 } 121 } 122 } 123 124 let passed = plaintext_env.is_empty() && unslop_violations.is_empty(); 125 InvariantAuditResult { 126 passed, 127 plaintext_env_files_found: plaintext_env, 128 unredacted_secrets_found: 0, 129 unslop_violations, 130 } 131 } 132 133 pub async fn audit_workspace_build(workspace_path: &str) -> BuildAuditResult { 134 let output_res = Command::new("cargo") 135 .arg("check") 136 .arg("--workspace") 137 .current_dir(workspace_path) 138 .output() 139 .await; 140 141 match output_res { 142 Ok(out) => { 143 let stderr = String::from_utf8_lossy(&out.stderr); 144 let mut errors = Vec::new(); 145 let mut warnings = Vec::new(); 146 147 for line in stderr.lines() { 148 if line.starts_with("error") { 149 errors.push(line.to_string()); 150 } else if line.starts_with("warning") && !line.contains("profiles for the non root") 151 { 152 warnings.push(line.to_string()); 153 } 154 } 155 156 BuildAuditResult { 157 passed: out.status.success(), 158 errors, 159 warnings, 160 } 161 } 162 Err(e) => BuildAuditResult { 163 passed: false, 164 errors: vec![format!("Failed to run cargo check: {}", e)], 165 warnings: Vec::new(), 166 }, 167 } 168 } 169 170 pub async fn run_full_audit(client: &Client, workspace_dir: &str) -> SystemAuditReport { 171 let services = audit_services(client).await; 172 let home = std::env::var("HOME") 173 .or_else(|_| std::env::var("USERPROFILE")) 174 .unwrap_or_else(|_| ".".to_string()); 175 let cockpit_dir = format!("{}/spark-cockpit-rs", home); 176 let invariants = audit_vault_and_unslop(&[workspace_dir, &cockpit_dir]); 177 let build = audit_workspace_build(workspace_dir).await; 178 179 let services_ok = services.iter().all(|s| s.reachable); 180 let overall_healthy = services_ok && invariants.passed && build.passed; 181 182 SystemAuditReport { 183 timestamp: chrono::Utc::now().to_rfc3339(), 184 services, 185 invariants, 186 build, 187 overall_healthy, 188 } 189 } 190 191 #[cfg(test)] 192 mod tests { 193 use super::*; 194 use aien_localhttp::test_server::{closed_port, response, serve, serve_silent}; 195 196 #[test] 197 fn service_endpoints_are_plain_http() { 198 for (name, ep) in SERVICE_ENDPOINTS { 199 assert!(aien_localhttp::Url::parse(ep).is_ok(), "{name} {ep}"); 200 } 201 } 202 203 #[tokio::test] 204 async fn audit_endpoints_keeps_the_reachability_rule() { 205 let (base, server) = serve(vec![ 206 response("200 OK", "text/plain", "ok"), 207 response("404 Not Found", "text/plain", ""), 208 response("503 Service Unavailable", "text/plain", ""), 209 ]) 210 .await; 211 let ok = format!("{base}/health"); 212 let missing = format!("{base}/v1/models"); 213 let down = format!("{base}/api/pulse"); 214 let refused = closed_port().await; 215 let results = audit_endpoints( 216 &Client::new(), 217 &[ 218 ("ok", &ok), 219 ("missing", &missing), 220 ("down", &down), 221 ("refused", &refused), 222 ("tls", "https://127.0.0.1:1/health"), 223 ], 224 ) 225 .await; 226 let summary: Vec<(bool, Option)> = results 227 .iter() 228 .map(|r| (r.reachable, r.status_code)) 229 .collect(); 230 assert_eq!( 231 summary, 232 vec![ 233 (true, Some(200)), 234 (true, Some(404)), 235 (false, Some(503)), 236 (false, None), 237 (false, None), 238 ] 239 ); 240 assert_eq!(results[0].endpoint, ok); 241 let requests = server.await.unwrap(); 242 assert!(requests[0].starts_with("GET /health HTTP/1.1\r\n")); 243 assert!(requests[1].starts_with("GET /v1/models HTTP/1.1\r\n")); 244 } 245 246 #[tokio::test] 247 async fn audit_endpoints_bounds_a_silent_service_at_1500_ms() { 248 let (base, _server) = serve_silent().await; 249 let started = std::time::Instant::now(); 250 let results = audit_endpoints(&Client::new(), &[("silent", &base)]).await; 251 assert!(!results[0].reachable); 252 assert_eq!(results[0].status_code, None); 253 assert!(started.elapsed() < Duration::from_secs(4)); 254 assert!(results[0].latency_ms >= 1400, "{}", results[0].latency_ms); 255 } 256 }