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 / spark-adapters / src / vault.rs

555 lines · 20157 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 regex::Regex;
17use std::collections::HashMap;
18use std::process::Command;
19use std::sync::{OnceLock, RwLock};
20use std::time::{Duration, Instant};
21
22static VAULT_CACHE: OnceLock<RwLock<(Instant, Vec<String>)>> = OnceLock::new();
23static RESOLVED_SECRETS_CACHE: OnceLock<RwLock<HashMap<String, (Instant, String)>>> =
24 OnceLock::new();
25static SCRUB_TARGETS_CACHE: OnceLock<RwLock<(Instant, Vec<String>)>> = OnceLock::new();
26static TEST_SECRETS: OnceLock<RwLock<HashMap<String, String>>> = OnceLock::new();
27
28/// How long vault key lists, resolved secrets and scrub targets are cached before the TPM vault
29/// is asked again.
30const CACHE_TTL: Duration = Duration::from_secs(60);
31
32/// List all secret keys currently registered in the hardware TPM vault.
33/// Results are cached for `CACHE_TTL` (60 seconds) to avoid repeated TPM queries.
34pub fn list_vault_keys() -> Vec<String> {
35 let cache_lock =
36 VAULT_CACHE.get_or_init(|| RwLock::new((Instant::now() - CACHE_TTL, Vec::new())));
37
38 if let Ok(read_guard) = cache_lock.read() {
39 if read_guard.0.elapsed() < CACHE_TTL {
40 return read_guard.1.clone();
41 }
42 }
43
44 if let Ok(mut write_guard) = cache_lock.write() {
45 if write_guard.0.elapsed() < CACHE_TTL {
46 return write_guard.1.clone();
47 }
48 let keys = fetch_vault_keys_raw();
49 *write_guard = (Instant::now(), keys.clone());
50 return keys;
51 }
52
53 fetch_vault_keys_raw()
54}
55
56fn fetch_vault_keys_raw() -> Vec<String> {
57 if let Ok(out) = Command::new("atlas-vault").arg("list").output() {
58 if out.status.success() {
59 return String::from_utf8_lossy(&out.stdout)
60 .lines()
61 .map(|s| s.trim().to_string())
62 .filter(|s| !s.is_empty())
63 .collect();
64 }
65 }
66 Vec::new()
67}
68
69fn fetch_secret_raw(key_name: &str) -> Option<String> {
70 if let Ok(out) = Command::new("atlas-vault").args(["get", key_name]).output() {
71 if out.status.success() {
72 let val = String::from_utf8_lossy(&out.stdout).trim().to_string();
73 if !val.is_empty() {
74 return Some(val);
75 }
76 }
77 }
78 None
79}
80
81/// Dynamically resolve a secret token.
82/// Checks process environment first, then in-memory test secrets, then cache (`CACHE_TTL`, 60 seconds), then hardware TPM vault.
83pub fn resolve_secret(key_name: &str) -> Option<String> {
84 if key_name.trim().is_empty() {
85 return None;
86 }
87
88 // 1. Check process environment first
89 if let Ok(env_val) = std::env::var(key_name) {
90 let trimmed = env_val.trim().to_string();
91 if !trimmed.is_empty() {
92 return Some(trimmed);
93 }
94 }
95
96 // 2. Check in-memory test secrets store
97 if let Some(test_lock) = TEST_SECRETS.get() {
98 if let Ok(guard) = test_lock.read() {
99 if let Some(val) = guard.get(key_name) {
100 let trimmed = val.trim();
101 if !trimmed.is_empty() {
102 return Some(trimmed.to_string());
103 } else {
104 return None;
105 }
106 }
107 }
108 }
109
110 // 3. Cache lookup (`CACHE_TTL`)
111 let cache_lock = RESOLVED_SECRETS_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
112 if let Ok(guard) = cache_lock.read() {
113 if let Some((fetched_at, val)) = guard.get(key_name) {
114 if fetched_at.elapsed() < CACHE_TTL {
115 return Some(val.clone());
116 }
117 }
118 }
119
120 // 4. Query hardware TPM-bound vault if key is registered
121 let keys = list_vault_keys();
122 if keys.iter().any(|k| k == key_name) {
123 if let Some(val) = fetch_secret_raw(key_name) {
124 if let Ok(mut write_guard) = cache_lock.write() {
125 write_guard.insert(key_name.to_string(), (Instant::now(), val.clone()));
126 }
127 return Some(val);
128 }
129 }
130
131 None
132}
133
134/// Check if a secret key is registered without exposing its value.
135pub fn is_secret_present(key_name: &str) -> bool {
136 if key_name.trim().is_empty() {
137 return false;
138 }
139
140 if let Ok(env_val) = std::env::var(key_name) {
141 if !env_val.trim().is_empty() {
142 return true;
143 }
144 }
145
146 if let Some(test_lock) = TEST_SECRETS.get() {
147 if let Ok(guard) = test_lock.read() {
148 if let Some(val) = guard.get(key_name) {
149 return !val.trim().is_empty();
150 }
151 }
152 }
153
154 let keys = list_vault_keys();
155 keys.iter().any(|k| k == key_name)
156}
157
158/// Register a test secret in memory for test verification without physical TPM interaction.
159pub fn register_test_secret(key_name: &str, value: &str) {
160 let test_lock = TEST_SECRETS.get_or_init(|| RwLock::new(HashMap::new()));
161 if let Ok(mut guard) = test_lock.write() {
162 guard.insert(key_name.to_string(), value.to_string());
163 }
164
165 // Update resolved secrets cache
166 let cache_lock = RESOLVED_SECRETS_CACHE.get_or_init(|| RwLock::new(HashMap::new()));
167 if let Ok(mut guard) = cache_lock.write() {
168 if value.trim().is_empty() {
169 guard.remove(key_name);
170 } else {
171 guard.insert(key_name.to_string(), (Instant::now(), value.to_string()));
172 }
173 }
174
175 // Incremental update to scrub targets cache so valid cached TPM keys are preserved
176 if let Some(scrub_lock) = SCRUB_TARGETS_CACHE.get() {
177 if let Ok(mut guard) = scrub_lock.write() {
178 if guard.0.elapsed() < CACHE_TTL {
179 let trimmed = value.trim();
180 if trimmed.len() >= 6 {
181 if !guard.1.contains(&trimmed.to_string()) {
182 guard.1.push(trimmed.to_string());
183 guard.1.sort();
184 guard.1.dedup();
185 guard.1.sort_by_key(|a| std::cmp::Reverse(a.len()));
186 }
187 } else {
188 guard.1.retain(|s| s != trimmed);
189 }
190 guard.0 = Instant::now();
191 } else {
192 guard.0 = Instant::now() - CACHE_TTL;
193 guard.1.clear();
194 }
195 }
196 }
197}
198
199/// Remove a test secret from memory and purge from caches.
200pub fn remove_test_secret(key_name: &str) {
201 if let Some(test_lock) = TEST_SECRETS.get() {
202 if let Ok(mut guard) = test_lock.write() {
203 guard.remove(key_name);
204 }
205 }
206 if let Some(cache_lock) = RESOLVED_SECRETS_CACHE.get() {
207 if let Ok(mut guard) = cache_lock.write() {
208 guard.remove(key_name);
209 }
210 }
211}
212
213/// Retrieve all active secret values of length >= 6 for outbound scrubbing.
214/// Cached in memory for `CACHE_TTL` (60 seconds).
215pub fn get_scrub_targets() -> Vec<String> {
216 let cache_lock =
217 SCRUB_TARGETS_CACHE.get_or_init(|| RwLock::new((Instant::now() - CACHE_TTL, Vec::new())));
218
219 if let Ok(read_guard) = cache_lock.read() {
220 if read_guard.0.elapsed() < CACHE_TTL {
221 return read_guard.1.clone();
222 }
223 }
224
225 if let Ok(mut write_guard) = cache_lock.write() {
226 if write_guard.0.elapsed() < CACHE_TTL {
227 return write_guard.1.clone();
228 }
229
230 let mut targets = Vec::new();
231
232 // 1. Environment secrets for known model providers and services
233 let known_env_keys = [
234 "OPENAI_API_KEY",
235 "ANTHROPIC_API_KEY",
236 "OPENROUTER_API_KEY",
237 "GEMINI_API_KEY",
238 "GROQ_API_KEY",
239 "DEEPSEEK_API_KEY",
240 "CHATGPT_SESSION_TOKEN",
241 "CLAUDE_SESSION_KEY",
242 "CORTEX_TOKEN",
243 ];
244 for k in known_env_keys {
245 if let Ok(val) = std::env::var(k) {
246 let trimmed = val.trim().to_string();
247 if trimmed.len() >= 6 {
248 targets.push(trimmed);
249 }
250 }
251 }
252
253 // 2. Hardware TPM-bound vault keys
254 let vault_keys = list_vault_keys();
255 for k in vault_keys {
256 if let Some(val) = resolve_secret(&k) {
257 if val.len() >= 6 {
258 targets.push(val);
259 }
260 }
261 }
262
263 // 3. Test secrets
264 if let Some(test_lock) = TEST_SECRETS.get() {
265 if let Ok(guard) = test_lock.read() {
266 for val in guard.values() {
267 if val.len() >= 6 {
268 targets.push(val.clone());
269 }
270 }
271 }
272 }
273
274 // Deduplicate and sort descending by length to prevent partial replacement bugs
275 targets.sort();
276 targets.dedup();
277 targets.sort_by_key(|a| std::cmp::Reverse(a.len()));
278
279 *write_guard = (Instant::now(), targets.clone());
280 return targets;
281 }
282
283 Vec::new()
284}
285
286/// Scrub sensitive host paths, local subnets, vault secrets, and operator identity from outbound prompts.
287pub fn sanitize_outbound_prompt(prompt: &str) -> String {
288 static PATH_RE: OnceLock<Regex> = OnceLock::new();
289 static IP_RE: OnceLock<Regex> = OnceLock::new();
290 static HOST_RE: OnceLock<Regex> = OnceLock::new();
291 static SECRET_RE: OnceLock<Regex> = OnceLock::new();
292 static OPERATOR_RE: OnceLock<Regex> = OnceLock::new();
293
294 let path_re = PATH_RE.get_or_init(|| {
295 Regex::new(r"/(?:home|Users)/[a-zA-Z0-9_.-]+(?:/[a-zA-Z0-9_.-]+)*").unwrap()
296 });
297 let ip_re = IP_RE.get_or_init(|| {
298 Regex::new(r"\b(?:127\.\d{1,3}\.\d{1,3}\.\d{1,3}|100\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}|0\.0\.0\.0)\b").unwrap()
299 });
300 let host_re = HOST_RE.get_or_init(|| {
301 Regex::new(
302 r"(?i)\b(?:spark-[0-9a-f]{4}(?:\.local)?|spark\.local|localhost)\b|(?i)\bspark([^\w-]|\z)",
303 )
304 .unwrap()
305 });
306 let secret_re = SECRET_RE.get_or_init(|| {
307 Regex::new(r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----|\b(?:sk-ant-[a-zA-Z0-9_-]{20,}|sk-[a-zA-Z0-9_-]{20,}|AIzaSy[a-zA-Z0-9_-]{30,}|hf_[a-zA-Z0-9_]{30,}|ghp_[a-zA-Z0-9]{20,}|gho_[a-zA-Z0-9]{20,}|ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,})\b").unwrap()
308 });
309 let operator_re = OPERATOR_RE.get_or_init(|| {
310 Regex::new(r"(?i)\b(?:[a-zA-Z0-9._%+-]*(?:drake\.stapleton|drake\.aien|drakestapleton|ballentine|aien)[a-zA-Z0-9._%+-]*@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}|michael\s+drake\s+ballentine|drake\s+ballentine|michael\s+ballentine|drake\s+stapleton|ballentine|drakestapleton|drake\.stapleton)\b").unwrap()
311 });
312
313 // 1. Filesystem paths
314 let s1 = path_re.replace_all(prompt, "<WORKSPACE_PATH>");
315
316 // 2. Private IP addresses
317 let s2 = ip_re.replace_all(&s1, "<LOCAL_HOST>");
318
319 // 3. Local hostnames (preserves compound names like spark-adapters, spark-distill)
320 let s3 = host_re.replace_all(&s2, "<LOCAL_HOST>$1");
321
322 // 4. Dynamic registered vault secrets (exact literal replacement)
323 let mut s4 = s3.into_owned();
324 for secret in get_scrub_targets() {
325 if s4.contains(&secret) {
326 s4 = s4.replace(&secret, "[REDACTED_BY_ATLAS_VAULT]");
327 }
328 }
329
330 // 5. Well-known API key signature patterns & PEM keys
331 let s5 = secret_re.replace_all(&s4, "[REDACTED_BY_ATLAS_VAULT]");
332
333 // 6. Operator personal identifiers & emails
334 let s6 = operator_re.replace_all(&s5, "<OPERATOR>");
335
336 s6.into_owned()
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342
343 #[test]
344 fn test_sanitize_paths_and_ips() {
345 let raw = "Read /home/alice/workspace/secret.rs from 100.100.1.2 and send to 127.0.0.1";
346 let clean = sanitize_outbound_prompt(raw);
347 assert!(!clean.contains("/home/alice"));
348 assert!(!clean.contains("100.100.1.2"));
349 assert!(!clean.contains("127.0.0.1"));
350 assert!(clean.contains("<WORKSPACE_PATH>"));
351 assert!(clean.contains("<LOCAL_HOST>"));
352 }
353
354 #[test]
355 fn test_sanitize_operator_variants() {
356 assert_eq!(
357 sanitize_outbound_prompt("Author: Drake Stapleton"),
358 "Author: <OPERATOR>"
359 );
360 assert_eq!(
361 sanitize_outbound_prompt("Author: drake stapleton"),
362 "Author: <OPERATOR>"
363 );
364 assert_eq!(
365 sanitize_outbound_prompt("Former: Michael Drake Ballentine"),
366 "Former: <OPERATOR>"
367 );
368 assert_eq!(
369 sanitize_outbound_prompt("Former: Drake Ballentine"),
370 "Former: <OPERATOR>"
371 );
372 assert_eq!(
373 sanitize_outbound_prompt("Surname: Ballentine"),
374 "Surname: <OPERATOR>"
375 );
376 assert_eq!(
377 sanitize_outbound_prompt("User: drakestapleton"),
378 "User: <OPERATOR>"
379 );
380 assert_eq!(
381 sanitize_outbound_prompt("Handle: drake.stapleton"),
382 "Handle: <OPERATOR>"
383 );
384 assert_eq!(
385 sanitize_outbound_prompt("Email: aien@aienos.com"),
386 "Email: <OPERATOR>"
387 );
388 assert_eq!(
389 sanitize_outbound_prompt("Email: drake.stapleton@example.com"),
390 "Email: <OPERATOR>"
391 );
392 assert_eq!(
393 sanitize_outbound_prompt("Bracket: <drake.stapleton@example.com>"),
394 "Bracket: <<OPERATOR>>"
395 );
396 }
397
398 #[test]
399 fn test_sanitize_operator_negative_cases() {
400 assert_eq!(
401 sanitize_outbound_prompt(
402 "The Drake equation calculates extraterrestrial probabilities"
403 ),
404 "The Drake equation calculates extraterrestrial probabilities"
405 );
406 assert_eq!(
407 sanitize_outbound_prompt("Use a staple to bind documents"),
408 "Use a staple to bind documents"
409 );
410 }
411
412 #[test]
413 fn test_sanitize_hostnames() {
414 assert_eq!(
415 sanitize_outbound_prompt("Connecting to spark-1a2b on port 18080"),
416 "Connecting to <LOCAL_HOST> on port 18080"
417 );
418 assert_eq!(
419 sanitize_outbound_prompt("Connecting to spark-1a2b.local"),
420 "Connecting to <LOCAL_HOST>"
421 );
422 assert_eq!(
423 sanitize_outbound_prompt("Connecting to spark.local"),
424 "Connecting to <LOCAL_HOST>"
425 );
426 assert_eq!(
427 sanitize_outbound_prompt("Connecting to localhost:8080"),
428 "Connecting to <LOCAL_HOST>:8080"
429 );
430 assert_eq!(
431 sanitize_outbound_prompt("ssh drakestapleton@spark"),
432 "ssh <OPERATOR>@<LOCAL_HOST>"
433 );
434 assert_eq!(
435 sanitize_outbound_prompt("http://spark:18080/api"),
436 "http://<LOCAL_HOST>:18080/api"
437 );
438 assert_eq!(
439 sanitize_outbound_prompt("Run target on spark"),
440 "Run target on <LOCAL_HOST>"
441 );
442 }
443
444 #[test]
445 fn test_preserve_crate_and_binary_names() {
446 assert_eq!(
447 sanitize_outbound_prompt("Update crates/spark-adapters/src/vault.rs"),
448 "Update crates/spark-adapters/src/vault.rs"
449 );
450 assert_eq!(
451 sanitize_outbound_prompt("Run spark-distill crawl --track systems"),
452 "Run spark-distill crawl --track systems"
453 );
454 assert_eq!(
455 sanitize_outbound_prompt(
456 "Crates: spark-mask, spark-supervisor, spark-hive, spark-dream"
457 ),
458 "Crates: spark-mask, spark-supervisor, spark-hive, spark-dream"
459 );
460 assert_eq!(
461 sanitize_outbound_prompt("Check spark_adapters module and sparkling water"),
462 "Check spark_adapters module and sparkling water"
463 );
464 }
465
466 #[test]
467 fn test_sanitize_secrets() {
468 assert_eq!(
469 sanitize_outbound_prompt(
470 "Anthropic: sk-ant-api03-123456789012345678901234567890123456"
471 ),
472 "Anthropic: [REDACTED_BY_ATLAS_VAULT]"
473 );
474 assert_eq!(
475 sanitize_outbound_prompt("OpenAI: sk-proj-123456789012345678901234567890"),
476 "OpenAI: [REDACTED_BY_ATLAS_VAULT]"
477 );
478 assert_eq!(
479 sanitize_outbound_prompt("Gemini: AIzaSyD-1234567890123456789012345678901"),
480 "Gemini: [REDACTED_BY_ATLAS_VAULT]"
481 );
482 assert_eq!(
483 sanitize_outbound_prompt("HuggingFace: hf_abcdefghijklmnopqrstuvwxyz12345678"),
484 "HuggingFace: [REDACTED_BY_ATLAS_VAULT]"
485 );
486 assert_eq!(
487 sanitize_outbound_prompt("GitHub PAT: ghp_123456789012345678901234567890"),
488 "GitHub PAT: [REDACTED_BY_ATLAS_VAULT]"
489 );
490 assert_eq!(
491 sanitize_outbound_prompt("GitHub OAuth: gho_123456789012345678901234567890"),
492 "GitHub OAuth: [REDACTED_BY_ATLAS_VAULT]"
493 );
494 assert_eq!(
495 sanitize_outbound_prompt("JWT: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"),
496 "JWT: [REDACTED_BY_ATLAS_VAULT]"
497 );
498 assert_eq!(
499 sanitize_outbound_prompt(
500 "Key: -----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEA0\n-----END RSA PRIVATE KEY-----"
501 ),
502 "Key: [REDACTED_BY_ATLAS_VAULT]"
503 );
504 assert_eq!(
505 sanitize_outbound_prompt(
506 "Key: -----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjE\n-----END OPENSSH PRIVATE KEY-----"
507 ),
508 "Key: [REDACTED_BY_ATLAS_VAULT]"
509 );
510 assert_eq!(
511 sanitize_outbound_prompt(
512 "Key: -----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASC\n-----END PRIVATE KEY-----"
513 ),
514 "Key: [REDACTED_BY_ATLAS_VAULT]"
515 );
516 }
517
518 #[test]
519 fn test_complex_multimodal_sanitization() {
520 let raw = "Operator Drake Stapleton running on spark-1a2b with key sk-ant-api03-abcdefghijklmnopqrstuvwxyz12345 accessing /home/alice/secret.txt at 192.168.0.50 and spark:18080";
521 let clean = sanitize_outbound_prompt(raw);
522 assert_eq!(
523 clean,
524 "Operator <OPERATOR> running on <LOCAL_HOST> with key [REDACTED_BY_ATLAS_VAULT] accessing <WORKSPACE_PATH> at <LOCAL_HOST> and <LOCAL_HOST>:18080"
525 );
526 }
527
528 #[test]
529 fn test_dynamic_vault_secret_scrubbing() {
530 register_test_secret("SUPER_SECRET_KEY", "quantum_secure_vault_passphrase_99182");
531 let raw = "Deploy using passphrase quantum_secure_vault_passphrase_99182 immediately.";
532 let clean = sanitize_outbound_prompt(raw);
533 assert!(!clean.contains("quantum_secure_vault_passphrase_99182"));
534 assert!(clean.contains("[REDACTED_BY_ATLAS_VAULT]"));
535 }
536
537 #[test]
538 fn test_short_secrets_not_scrubbed() {
539 register_test_secret("SHORT_SECRET", "abcde");
540 let raw = "The word abcde is normal text.";
541 let clean = sanitize_outbound_prompt(raw);
542 assert!(clean.contains("abcde"));
543 assert!(!clean.contains("[REDACTED_BY_ATLAS_VAULT]"));
544 }
545
546 #[test]
547 fn test_sanitize_operator_and_secrets() {
548 let raw = "Operator drakestapleton deployed key sk-proj-123456789012345678901234 for aien@aienos.com";
549 let clean = sanitize_outbound_prompt(raw);
550 assert!(!clean.contains("drakestapleton"));
551 assert!(!clean.contains("aien@aienos.com"));
552 assert!(clean.contains("<OPERATOR>"));
553 assert!(clean.contains("[REDACTED_BY_ATLAS_VAULT]"));
554 }
555}