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/aegis-runtime-mv/blob/main/src/vault.rs # aegis-runtime-mv Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha. 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 `aegis-runtime-mv / src / vault.rs` 211 lines ยท 7238 bytes Raw Blame History 1 use std::collections::HashMap; 2 use std::process::Command; 3 use std::sync::{Arc, Mutex}; 4 5 pub const REDACTED_MARKER: &str = "[REDACTED_BY_ATLAS_VAULT]"; 6 7 /// Development-only permission to read a credential from the process environment 8 /// after atlas-vault does not answer. Unset means production: fail closed. 9 pub fn dev_secret_fallback_enabled() -> bool { 10 matches!( 11 std::env::var("AIEN_DEV_SECRET_FALLBACK").ok().as_deref(), 12 Some("1") | Some("true") | Some("on") 13 ) 14 } 15 16 #[derive(Clone)] 17 pub struct VaultResolver { 18 cache: Arc>>, 19 } 20 21 impl Default for VaultResolver { 22 fn default() -> Self { 23 Self::new() 24 } 25 } 26 27 impl VaultResolver { 28 pub fn new() -> Self { 29 Self { 30 cache: Arc::new(Mutex::new(HashMap::new())), 31 } 32 } 33 34 pub fn resolve_secret(&self, key: &str) -> Result { 35 if key.trim().is_empty() { 36 return Err("Secret key cannot be empty".to_string()); 37 } 38 39 let mut cache = self.cache.lock().map_err(|e| e.to_string())?; 40 if let Some(val) = cache.get(key) { 41 return Ok(val.clone()); 42 } 43 44 // Try atlas-vault CLI binary first 45 if let Ok(output) = Command::new("atlas-vault").arg("get").arg(key).output() { 46 if output.status.success() { 47 let val = String::from_utf8_lossy(&output.stdout).trim().to_string(); 48 if !val.is_empty() { 49 cache.insert(key.to_string(), val.clone()); 50 return Ok(val); 51 } 52 } 53 } 54 55 // Environment values are a development fallback only, and only when 56 // the operator turns that fallback on. Production stops here. 57 if dev_secret_fallback_enabled() { 58 if let Ok(val) = std::env::var(key) { 59 cache.insert(key.to_string(), val.clone()); 60 return Ok(val); 61 } 62 } 63 64 Err(format!( 65 "Secret '{}' was not returned by atlas-vault. VaultResolver is a client of atlas-vault, not a TPM. Process-environment fallback is off unless AIEN_DEV_SECRET_FALLBACK=1.", 66 key 67 )) 68 } 69 70 pub fn insert_cached(&self, key: &str, secret: &str) { 71 if let Ok(mut cache) = self.cache.lock() { 72 cache.insert(key.to_string(), secret.to_string()); 73 } 74 } 75 76 pub fn has_cached(&self, key: &str) -> bool { 77 if let Ok(cache) = self.cache.lock() { 78 cache.contains_key(key) 79 } else { 80 false 81 } 82 } 83 84 pub fn redact_sensitive_text(&self, text: &str) -> String { 85 let cache = match self.cache.lock() { 86 Ok(c) => c, 87 Err(_) => return text.to_string(), 88 }; 89 90 let mut sanitized = text.to_string(); 91 for val in cache.values() { 92 if val.len() >= 4 { 93 sanitized = sanitized.replace(val, REDACTED_MARKER); 94 } 95 } 96 sanitized 97 } 98 } 99 100 #[cfg(test)] 101 mod tests { 102 use super::*; 103 104 fn env_lock() -> std::sync::MutexGuard<'static, ()> { 105 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); 106 LOCK.lock().unwrap() 107 } 108 109 #[test] 110 fn test_vault_resolution_and_redaction() { 111 let _guard = env_lock(); 112 let vault = VaultResolver::new(); 113 std::env::set_var("AIEN_DEV_SECRET_FALLBACK", "1"); 114 std::env::set_var("TEST_TOKEN_SECRET", "super_secret_12345"); 115 116 let secret = vault.resolve_secret("TEST_TOKEN_SECRET").unwrap(); 117 assert_eq!(secret, "super_secret_12345"); 118 119 let output = "Connecting with bearer super_secret_12345 to endpoint".to_string(); 120 let redacted = vault.redact_sensitive_text(&output); 121 assert_eq!( 122 redacted, 123 format!("Connecting with bearer {} to endpoint", REDACTED_MARKER) 124 ); 125 } 126 127 #[test] 128 fn test_vault_empty_key_resolution() { 129 let vault = VaultResolver::new(); 130 assert!(vault.resolve_secret("").is_err()); 131 assert!(vault.resolve_secret(" ").is_err()); 132 let err = vault.resolve_secret("").unwrap_err(); 133 assert_eq!(err, "Secret key cannot be empty"); 134 } 135 136 #[test] 137 fn production_does_not_read_the_environment() { 138 let _guard = env_lock(); 139 std::env::set_var("AIEN_DEV_SECRET_FALLBACK", "0"); 140 std::env::set_var("PROD_BLOCKED_SECRET", "should-not-resolve"); 141 let vault = VaultResolver::new(); 142 let err = vault.resolve_secret("PROD_BLOCKED_SECRET").unwrap_err(); 143 assert!(err.contains("was not returned by atlas-vault")); 144 std::env::remove_var("PROD_BLOCKED_SECRET"); 145 } 146 147 #[test] 148 fn test_vault_missing_key_fallback() { 149 let _guard = env_lock(); 150 let vault = VaultResolver::new(); 151 let err = vault 152 .resolve_secret("NONEXISTENT_KEY_12345_XYZ") 153 .unwrap_err(); 154 assert!(err.contains("was not returned by atlas-vault")); 155 } 156 157 #[test] 158 fn test_vault_multiline_redaction() { 159 let vault = VaultResolver::new(); 160 vault.insert_cached("KEY_A", "secret_alpha_99"); 161 vault.insert_cached("KEY_B", "secret_beta_88"); 162 163 let multiline = 164 "Line 1: secret_alpha_99\nLine 2: benign text\nLine 3: bearer secret_beta_88 token"; 165 let redacted = vault.redact_sensitive_text(multiline); 166 assert!(!redacted.contains("secret_alpha_99")); 167 assert!(!redacted.contains("secret_beta_88")); 168 assert!(redacted.contains(REDACTED_MARKER)); 169 assert!(redacted.contains("Line 2: benign text")); 170 } 171 172 #[test] 173 fn test_vault_streaming_chunk_redaction() { 174 let vault = VaultResolver::new(); 175 vault.insert_cached("API_KEY", "aegis_sk_live_998877"); 176 177 let chunks = vec![ 178 "data: {\"choices\": [{\"delta\": {\"content\": \"key is \"}}]}\\n\\n", 179 "data: {\"choices\": [{\"delta\": {\"content\": \"aegis_sk_live_998877\"}}]}\\n\\n", 180 "data: [DONE]\\n\\n", 181 ]; 182 183 let mut sanitized_stream = Vec::new(); 184 for chunk in chunks { 185 sanitized_stream.push(vault.redact_sensitive_text(chunk)); 186 } 187 188 assert_eq!(sanitized_stream.len(), 3); 189 assert!(!sanitized_stream[1].contains("aegis_sk_live_998877")); 190 assert!(sanitized_stream[1].contains(REDACTED_MARKER)); 191 assert_eq!(sanitized_stream[2], "data: [DONE]\\n\\n"); 192 } 193 194 #[test] 195 fn test_vault_prevention_of_disk_secret_writes() { 196 let temp_dir = tempfile::tempdir().unwrap(); 197 let vault = VaultResolver::new(); 198 vault.insert_cached("CRITICAL_VAULT_KEY", "sovereign_in_memory_only_key_value"); 199 200 let resolved = vault.resolve_secret("CRITICAL_VAULT_KEY").unwrap(); 201 assert_eq!(resolved, "sovereign_in_memory_only_key_value"); 202 203 // Verify that no .env or plaintext secret files were written anywhere in temp_dir 204 let entries = std::fs::read_dir(temp_dir.path()).unwrap(); 205 assert_eq!(entries.count(), 0); 206 207 // Verify current directory has no new .env files created 208 assert!(!std::path::Path::new(".env").exists()); 209 assert!(!std::path::Path::new(".env.local").exists()); 210 } 211 }