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/cortex-rs/src/security.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 / cortex-rs / src / security.rs` 521 lines ยท 18908 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 regex::Regex; 17 use serde::{Deserialize, Serialize}; 18 use sha2::{Digest, Sha256}; 19 use std::sync::OnceLock; 20 21 use crate::models::CortexSessionEvent; 22 23 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] 24 #[serde(rename_all = "snake_case")] 25 pub enum SensitivityClass { 26 DoNotRemember, 27 Credential, 28 Authentication, 29 Financial, 30 Health, 31 ThirdPartyPersonalData, 32 } 33 34 impl SensitivityClass { 35 pub fn as_str(&self) -> &'static str { 36 match self { 37 Self::DoNotRemember => "do_not_remember", 38 Self::Credential => "credential", 39 Self::Authentication => "authentication", 40 Self::Financial => "financial", 41 Self::Health => "health", 42 Self::ThirdPartyPersonalData => "third_party_personal_data", 43 } 44 } 45 46 pub fn from_str_opt(s: &str) -> Option { 47 match s { 48 "do_not_remember" => Some(Self::DoNotRemember), 49 "credential" => Some(Self::Credential), 50 "authentication" => Some(Self::Authentication), 51 "financial" => Some(Self::Financial), 52 "health" => Some(Self::Health), 53 "third_party_personal_data" => Some(Self::ThirdPartyPersonalData), 54 _ => None, 55 } 56 } 57 } 58 59 static DO_NOT_REMEMBER_RE: OnceLock = OnceLock::new(); 60 static CREDENTIAL_RE: OnceLock = OnceLock::new(); 61 static AUTH_RE: OnceLock = OnceLock::new(); 62 static FINANCIAL_RE: OnceLock = OnceLock::new(); 63 static HEALTH_RE: OnceLock = OnceLock::new(); 64 static PII_RE: OnceLock = OnceLock::new(); 65 66 fn get_do_not_remember_re() -> &'static Regex { 67 DO_NOT_REMEMBER_RE.get_or_init(|| { 68 Regex::new(r"(?i)\b(?:do not|don't|dont|never)\s+(?:remember|store|save|memorize)\b") 69 .unwrap() 70 }) 71 } 72 73 fn get_credential_re() -> &'static Regex { 74 CREDENTIAL_RE.get_or_init(|| { 75 Regex::new(r#"(?i)\b(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|password|passwd|private[_ -]?key|client[_ -]?secret)\b\s*(?::|=|is|was)\s*([^\s,;"']+)"#) 76 .unwrap() 77 }) 78 } 79 80 fn get_auth_re() -> &'static Regex { 81 AUTH_RE.get_or_init(|| { 82 Regex::new(r"(?i)\b(?:authorization:\s*bearer\s+[^\s]+|session[_ -]?cookie|one[- ]time password|\botp\b|mfa code)\b") 83 .unwrap() 84 }) 85 } 86 87 fn get_financial_re() -> &'static Regex { 88 FINANCIAL_RE.get_or_init(|| { 89 Regex::new( 90 r"(?i)\b(?:credit|debit) card\b|\b(?:routing|account) number\b|\b(?:cvv|iban|swift)\b", 91 ) 92 .unwrap() 93 }) 94 } 95 96 fn get_health_re() -> &'static Regex { 97 HEALTH_RE.get_or_init(|| { 98 Regex::new(r"(?i)\b(?:diagnosis|medical record|prescription|patient|therapy notes?|health insurance)\b") 99 .unwrap() 100 }) 101 } 102 103 fn get_pii_re() -> &'static Regex { 104 PII_RE.get_or_init(|| { 105 Regex::new(r"(?i)\b(?:social security|ssn|passport number|driver'?s license|home address)\b|\b(?:his|her|their|client|customer|employee|friend|coworker)'?s?\s+(?:email|phone|address|birthday)\b") 106 .unwrap() 107 }) 108 } 109 110 pub struct SanitizationResult { 111 pub sanitized_content: Option, 112 pub sanitized_payload: serde_json::Value, 113 pub sensitivity: Option, 114 pub secret_fingerprint: Option, 115 pub redacted: bool, 116 } 117 118 pub struct SecurityMembrane; 119 120 impl SecurityMembrane { 121 /// HMAC-SHA256 (RFC 2104) over the secret. The key never enters the stored fingerprint. 122 pub fn hmac_sha256(key: &[u8], message: &[u8]) -> [u8; 32] { 123 const BLOCK: usize = 64; 124 let mut key_block = [0u8; BLOCK]; 125 if key.len() > BLOCK { 126 let digest = Sha256::digest(key); 127 key_block[..32].copy_from_slice(&digest); 128 } else { 129 key_block[..key.len()].copy_from_slice(key); 130 } 131 let mut ipad = [0x36u8; BLOCK]; 132 let mut opad = [0x5cu8; BLOCK]; 133 for i in 0..BLOCK { 134 ipad[i] ^= key_block[i]; 135 opad[i] ^= key_block[i]; 136 } 137 let mut inner = Sha256::new(); 138 inner.update(ipad); 139 inner.update(message); 140 let inner_hash = inner.finalize(); 141 let mut outer = Sha256::new(); 142 outer.update(opad); 143 outer.update(inner_hash); 144 let digest = outer.finalize(); 145 let mut out = [0u8; 32]; 146 out.copy_from_slice(&digest); 147 out 148 } 149 150 pub fn compute_secret_fingerprint(secret: &str, hmac_key: &[u8]) -> String { 151 format!( 152 "HMAC-SHA256:{}", 153 crate::evidence::hex_encode(&Self::hmac_sha256(hmac_key, secret.trim().as_bytes(),)) 154 ) 155 } 156 157 fn mask_text(text: &str, hmac_key: &[u8]) -> (String, Option, Option, bool) { 158 if get_do_not_remember_re().is_match(text) { 159 return ( 160 "".to_string(), 161 Some("do_not_remember".to_string()), 162 None, 163 true, 164 ); 165 } 166 167 let mut out = text.to_string(); 168 let mut sensitivity: Option = None; 169 let mut fingerprint = None; 170 let mut redacted = false; 171 172 if let Some(caps) = get_credential_re().captures(&out) { 173 let secret = caps.get(1).map(|m| m.as_str()).unwrap_or("").to_string(); 174 if !secret.is_empty() { 175 fingerprint = Some(Self::compute_secret_fingerprint(&secret, hmac_key)); 176 out = out.replace(&secret, ""); 177 redacted = true; 178 } 179 sensitivity = Some("credential".to_string()); 180 } 181 if get_auth_re().is_match(&out) { 182 if fingerprint.is_none() { 183 if let Some(m) = get_auth_re().find(&out) { 184 fingerprint = Some(Self::compute_secret_fingerprint(m.as_str(), hmac_key)); 185 } 186 } 187 out = get_auth_re() 188 .replace_all(&out, "") 189 .to_string(); 190 if sensitivity.is_none() { 191 sensitivity = Some("authentication".to_string()); 192 } 193 redacted = true; 194 } 195 if get_financial_re().is_match(&out) { 196 out = get_financial_re() 197 .replace_all(&out, "") 198 .to_string(); 199 if sensitivity.is_none() { 200 sensitivity = Some("financial".to_string()); 201 } 202 redacted = true; 203 } 204 if get_health_re().is_match(&out) { 205 let diagnosis_only = get_health_re().find_iter(&out).all(|m| { 206 m.as_str().eq_ignore_ascii_case("diagnosis") && out.contains("diagnosis-protocol") 207 }); 208 if !diagnosis_only { 209 out = get_health_re() 210 .replace_all(&out, "") 211 .to_string(); 212 if sensitivity.is_none() { 213 sensitivity = Some("health".to_string()); 214 } 215 redacted = true; 216 } 217 } 218 if get_pii_re().is_match(&out) { 219 out = get_pii_re().replace_all(&out, "").to_string(); 220 if sensitivity.is_none() { 221 sensitivity = Some("third_party_personal_data".to_string()); 222 } 223 redacted = true; 224 } 225 (out, sensitivity, fingerprint, redacted) 226 } 227 228 fn sanitize_payload( 229 value: &serde_json::Value, 230 hmac_key: &[u8], 231 ) -> (serde_json::Value, Option, Option, bool) { 232 match value { 233 serde_json::Value::String(text) => { 234 let (masked, sensitivity, fingerprint, redacted) = Self::mask_text(text, hmac_key); 235 ( 236 serde_json::Value::String(masked), 237 sensitivity, 238 fingerprint, 239 redacted, 240 ) 241 } 242 serde_json::Value::Array(items) => { 243 let mut out = Vec::with_capacity(items.len()); 244 let mut sensitivity = None; 245 let mut fingerprint = None; 246 let mut redacted = false; 247 for item in items { 248 let (child, child_sensitivity, child_fp, child_redacted) = 249 Self::sanitize_payload(item, hmac_key); 250 out.push(child); 251 if sensitivity.is_none() { 252 sensitivity = child_sensitivity; 253 } 254 if fingerprint.is_none() { 255 fingerprint = child_fp; 256 } 257 redacted |= child_redacted; 258 } 259 ( 260 serde_json::Value::Array(out), 261 sensitivity, 262 fingerprint, 263 redacted, 264 ) 265 } 266 serde_json::Value::Object(map) => { 267 let mut out = serde_json::Map::new(); 268 let mut sensitivity = None; 269 let mut fingerprint = None; 270 let mut redacted = false; 271 for (k, v) in map { 272 let (child, child_sensitivity, child_fp, child_redacted) = 273 Self::sanitize_payload(v, hmac_key); 274 out.insert(k.clone(), child); 275 if sensitivity.is_none() { 276 sensitivity = child_sensitivity; 277 } 278 if fingerprint.is_none() { 279 fingerprint = child_fp; 280 } 281 redacted |= child_redacted; 282 } 283 ( 284 serde_json::Value::Object(out), 285 sensitivity, 286 fingerprint, 287 redacted, 288 ) 289 } 290 other => (other.clone(), None, None, false), 291 } 292 } 293 294 /// Inspect incoming text and payload, mask secrets, and enforce memory directives. 295 pub fn inspect_and_sanitize( 296 content: Option<&str>, 297 payload: &serde_json::Value, 298 explicit_sensitivity: Option<&str>, 299 hmac_key: &[u8], 300 ) -> SanitizationResult { 301 if explicit_sensitivity == Some("do_not_remember") 302 || content.is_some_and(|t| get_do_not_remember_re().is_match(t)) 303 { 304 return SanitizationResult { 305 sanitized_content: content.map(|_| "".to_string()), 306 sanitized_payload: serde_json::json!({ "redacted": true }), 307 sensitivity: Some("do_not_remember".to_string()), 308 secret_fingerprint: None, 309 redacted: true, 310 }; 311 } 312 313 let (sanitized_payload, payload_sensitivity, payload_fp, payload_redacted) = 314 Self::sanitize_payload(payload, hmac_key); 315 316 let (sanitized_content, content_sensitivity, content_fp, content_redacted) = match content { 317 Some(text) => { 318 let (masked, sensitivity, fingerprint, redacted) = Self::mask_text(text, hmac_key); 319 (Some(masked), sensitivity, fingerprint, redacted) 320 } 321 None => (None, None, None, false), 322 }; 323 324 let mut sensitivity = content_sensitivity.or(payload_sensitivity); 325 if sensitivity.is_none() { 326 sensitivity = explicit_sensitivity.map(|s| s.to_string()); 327 } 328 if explicit_sensitivity == Some("health") && sensitivity.as_deref() != Some("health") { 329 sensitivity = Some("health".to_string()); 330 } 331 if explicit_sensitivity == Some("financial") && sensitivity.is_none() { 332 sensitivity = Some("financial".to_string()); 333 } 334 if explicit_sensitivity == Some("third_party_personal_data") && sensitivity.is_none() { 335 sensitivity = Some("third_party_personal_data".to_string()); 336 } 337 if explicit_sensitivity == Some("authentication") && sensitivity.is_none() { 338 sensitivity = Some("authentication".to_string()); 339 } 340 341 let redacted = content_redacted 342 || payload_redacted 343 || matches!( 344 sensitivity.as_deref(), 345 Some( 346 "do_not_remember" 347 | "credential" 348 | "authentication" 349 | "financial" 350 | "health" 351 | "third_party_personal_data" 352 ) 353 ); 354 355 SanitizationResult { 356 sanitized_content, 357 sanitized_payload, 358 sensitivity, 359 secret_fingerprint: content_fp.or(payload_fp), 360 redacted, 361 } 362 } 363 364 /// Project a raw database event into a SafeEventView. 365 /// Processors must only access events through this view. 366 pub fn to_safe_view(event: &CortexSessionEvent, hmac_key: &[u8]) -> SafeEventView { 367 let inspected = Self::inspect_and_sanitize( 368 event.content.as_deref(), 369 &event.payload, 370 event.sensitivity.as_deref(), 371 hmac_key, 372 ); 373 let is_do_not_remember = inspected.sensitivity.as_deref() == Some("do_not_remember"); 374 let is_credential = matches!( 375 inspected.sensitivity.as_deref(), 376 Some("credential" | "authentication") 377 ); 378 let extraction_allowed = !inspected.redacted && !is_do_not_remember && !is_credential; 379 let safe_content = if inspected.redacted || is_do_not_remember { 380 None 381 } else { 382 inspected.sanitized_content 383 }; 384 let payload = if inspected.redacted { 385 serde_json::json!({ "redacted": true }) 386 } else { 387 inspected.sanitized_payload 388 }; 389 390 SafeEventView { 391 event_id: event.id.clone(), 392 session_id: event.session_id.clone(), 393 sequence: event.sequence, 394 branch_id: event.branch_id.clone(), 395 event_type: event.event_type.clone(), 396 role: event.role.clone(), 397 safe_content, 398 payload, 399 sensitivity: inspected.sensitivity.or_else(|| event.sensitivity.clone()), 400 extraction_allowed, 401 } 402 } 403 } 404 405 /// The sanitized, policy-filtered view of an event provided to background workers. 406 #[derive(Debug, Clone, Serialize, Deserialize)] 407 #[serde(rename_all = "camelCase")] 408 pub struct SafeEventView { 409 pub event_id: String, 410 pub session_id: String, 411 pub sequence: i64, 412 pub branch_id: String, 413 pub event_type: String, 414 pub role: Option, 415 pub safe_content: Option, 416 pub payload: serde_json::Value, 417 pub sensitivity: Option, 418 pub extraction_allowed: bool, 419 } 420 421 #[cfg(test)] 422 mod tests { 423 use super::*; 424 425 #[test] 426 fn test_do_not_remember_directive() { 427 let res = SecurityMembrane::inspect_and_sanitize( 428 Some("Please do not remember this confidential exchange"), 429 &serde_json::json!({}), 430 None, 431 b"test-hmac-key", 432 ); 433 assert_eq!(res.sensitivity, Some("do_not_remember".to_string())); 434 assert_eq!( 435 res.sanitized_content, 436 Some("".to_string()) 437 ); 438 } 439 440 #[test] 441 fn test_credential_masking_and_fingerprint() { 442 let key = b"test-hmac-key"; 443 let res = SecurityMembrane::inspect_and_sanitize( 444 Some("Connecting with api_key: sk_live_`99418294719247192` to server"), 445 &serde_json::json!({"token": "api_key: sk_live_`99418294719247192`"}), 446 None, 447 key, 448 ); 449 assert_eq!(res.sensitivity, Some("credential".to_string())); 450 assert!(res.sanitized_content.unwrap().contains("")); 451 assert!(!res 452 .sanitized_payload 453 .to_string() 454 .contains("sk_live_`99418294719247192`")); 455 let fingerprint = res.secret_fingerprint.unwrap(); 456 assert!(fingerprint.starts_with("HMAC-SHA256:")); 457 let salted = { 458 let mut hasher = Sha256::new(); 459 hasher.update(b"cortex_secret_salt:"); 460 hasher.update(b"sk_live_`99418294719247192`"); 461 format!("HMAC-SHA256:{:x}", hasher.finalize()) 462 }; 463 assert_ne!(fingerprint, salted); 464 } 465 466 #[test] 467 fn test_health_and_pii_classification() { 468 let res1 = SecurityMembrane::inspect_and_sanitize( 469 Some("Patient medical record notes: high blood pressure"), 470 &serde_json::json!({}), 471 None, 472 b"test-hmac-key", 473 ); 474 assert_eq!(res1.sensitivity, Some("health".to_string())); 475 476 let res2 = SecurityMembrane::inspect_and_sanitize( 477 Some("Her email is sarah@example.com for communication"), 478 &serde_json::json!({}), 479 None, 480 b"test-hmac-key", 481 ); 482 assert_eq!( 483 res2.sensitivity, 484 Some("third_party_personal_data".to_string()) 485 ); 486 } 487 488 #[test] 489 fn test_safe_event_view_quarantine() { 490 let sensitive_ev = CortexSessionEvent { 491 id: "ev-s1".to_string(), 492 session_id: "sess-1".to_string(), 493 sequence: 1, 494 branch_id: "main".to_string(), 495 parent_event_id: None, 496 event_type: "user_message".to_string(), 497 role: Some("user".to_string()), 498 content: Some("".to_string()), 499 payload: serde_json::json!({}), 500 created_at: "2026-09-21T00:00:00Z".to_string(), 501 content_hash: "hash".to_string(), 502 sensitivity: Some("do_not_remember".to_string()), 503 redacted: false, 504 segment_id: None, 505 }; 506 507 let view = SecurityMembrane::to_safe_view(&sensitive_ev, b"test-hmac-key"); 508 assert!(!view.extraction_allowed); 509 assert_eq!(view.safe_content, None); 510 } 511 512 #[test] 513 fn test_hmac_sha256_rfc4231_case1() { 514 let key = [0x0bu8; 20]; 515 let mac = SecurityMembrane::hmac_sha256(&key, b"Hi There"); 516 assert_eq!( 517 crate::evidence::hex_encode(&mac), 518 "`b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7`" 519 ); 520 } 521 }