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/aienux/blob/main/crates/aienos-aegis/src/broker.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. 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 `aienux / crates / aienos-aegis / src / broker.rs` 471 lines · 17008 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 //! AEGIS Effect Broker: Dispatching approved intents to hardware and drivers (§5). 17 18 use crate::capability::{AegisError, CapabilityGraph}; 19 use crate::effect::{EffectIntent, OperatorGrant}; 20 use crate::evaluator::{AegisDecision, AegisEvaluator}; 21 use crate::world::{JSpaceWorld, WorldStatus}; 22 use serde::{Deserialize, Serialize}; 23 use std::collections::HashMap; 24 25 /// Immutable audit record of an effect evaluation and execution attempt. 26 #[derive(Clone, Debug, Serialize, Deserialize)] 27 pub struct EffectAuditRecord { 28 pub intent_id: [u8; 16], 29 pub action: String, 30 pub timestamp_utc: u64, 31 pub decision: AegisDecision, 32 pub executed: bool, 33 pub error: Option, 34 } 35 36 pub type EffectHandlerFn = Box Result + Send + Sync>; 37 38 /// Sovereign Effect Broker enforcing authorization before hardware execution. 39 pub struct EffectBroker { 40 evaluator: AegisEvaluator, 41 handlers: HashMap, 42 worlds: HashMap<[u8; 16], JSpaceWorld>, 43 audit_ledger: Vec, 44 } 45 46 impl EffectBroker { 47 /// Initialize Effect Broker with an evaluator. 48 pub fn new(evaluator: AegisEvaluator) -> Self { 49 Self { 50 evaluator, 51 handlers: HashMap::new(), 52 worlds: HashMap::new(), 53 audit_ledger: Vec::new(), 54 } 55 } 56 57 /// Register a native driver/subsystem effect handler. 58 pub fn register_handler(&mut self, action_prefix: &str, handler: F) 59 where 60 F: Fn(&EffectIntent) -> Result + Send + Sync + 'static, 61 { 62 self.handlers 63 .insert(action_prefix.to_string(), Box::new(handler)); 64 } 65 66 /// Give the broker ownership of a transactional World delta. 67 pub fn register_world(&mut self, world: JSpaceWorld) -> Result<(), AegisError> { 68 if world.status != WorldStatus::Active || self.worlds.contains_key(&world.world_id) { 69 return Err(AegisError::ExecutionFailed( 70 "World must be active with a unique ID".to_string(), 71 )); 72 } 73 self.worlds.insert(world.world_id, world); 74 Ok(()) 75 } 76 77 /// Inspect a broker-owned World without mutating its delta. 78 pub fn world(&self, id: &[u8; 16]) -> Option<&JSpaceWorld> { 79 self.worlds.get(id) 80 } 81 82 /// Discard every pending change in a broker-owned World. 83 pub fn rollback_world(&mut self, id: &[u8; 16]) -> Result<(), AegisError> { 84 let world = self 85 .worlds 86 .get_mut(id) 87 .ok_or_else(|| AegisError::ExecutionFailed("World is not registered".to_string()))?; 88 world.rollback(); 89 Ok(()) 90 } 91 92 fn apply_world_effect(&mut self, intent: &EffectIntent) -> Result { 93 let world_id = intent 94 .world_id 95 .ok_or_else(|| AegisError::ExecutionFailed("World ID is required".to_string()))?; 96 let world = self 97 .worlds 98 .get_mut(&world_id) 99 .ok_or_else(|| AegisError::ExecutionFailed("World is not registered".to_string()))?; 100 if world.status != WorldStatus::Active { 101 return Err(AegisError::ExecutionFailed( 102 "World is not active".to_string(), 103 )); 104 } 105 let path = intent.parameters.get("path").ok_or_else(|| { 106 AegisError::ExecutionFailed("Filesystem path is required".to_string()) 107 })?; 108 match intent.action.as_str() { 109 "fs.write" => { 110 let content = intent.parameters.get("content").ok_or_else(|| { 111 AegisError::ExecutionFailed("World write content is required".to_string()) 112 })?; 113 world.write_file(path, content.as_bytes().to_vec()); 114 Ok("World delta write committed".to_string()) 115 } 116 "fs.delete" => { 117 world.delete_file(path); 118 Ok("World delta deletion committed".to_string()) 119 } 120 _ => Err(AegisError::ExecutionFailed( 121 "Action has no World delta handler".to_string(), 122 )), 123 } 124 } 125 126 /// Dispatch an effect intent through AEGIS authorization. 127 /// 128 /// Rejects any irreversible effect originating from an unapproved intent. 129 pub fn dispatch( 130 &mut self, 131 intent: &EffectIntent, 132 graph: &CapabilityGraph, 133 grant: Option<&OperatorGrant>, 134 now_utc: u64, 135 ) -> Result { 136 let world_fs_effect = 137 intent.world_id.is_some() && matches!(intent.action.as_str(), "fs.write" | "fs.delete"); 138 let world_bound = world_fs_effect 139 && intent.world_id.is_some_and(|id| { 140 self.worlds 141 .get(&id) 142 .is_some_and(|world| world.status == WorldStatus::Active) 143 }); 144 let decision = 145 self.evaluator 146 .evaluate_with_world_binding(intent, graph, grant, now_utc, world_bound); 147 148 match &decision { 149 AegisDecision::Approved { .. } => { 150 // Prefer the most specific matching action prefix. 151 let handler = self 152 .handlers 153 .iter() 154 .filter(|(prefix, _)| intent.action.starts_with(prefix.as_str())) 155 .max_by_key(|(prefix, _)| prefix.len()) 156 .map(|(_, h)| h); 157 158 let result = if world_fs_effect { 159 self.apply_world_effect(intent) 160 } else if let Some(h) = handler { 161 h(intent).map_err(AegisError::ExecutionFailed) 162 } else { 163 Err(AegisError::ExecutionFailed(format!( 164 "no handler registered for {}", 165 intent.action 166 ))) 167 }; 168 169 let is_ok = result.is_ok(); 170 let err_msg = result.as_ref().err().map(|e| e.to_string()); 171 172 self.audit_ledger.push(EffectAuditRecord { 173 intent_id: intent.id, 174 action: intent.action.clone(), 175 timestamp_utc: now_utc, 176 decision: decision.clone(), 177 executed: is_ok, 178 error: err_msg, 179 }); 180 181 result 182 } 183 AegisDecision::RequiresOperatorApproval { reason, .. } => { 184 let err_reason = reason.clone(); 185 self.audit_ledger.push(EffectAuditRecord { 186 intent_id: intent.id, 187 action: intent.action.clone(), 188 timestamp_utc: now_utc, 189 decision, 190 executed: false, 191 error: Some(err_reason), 192 }); 193 Err(AegisError::MissingOperatorGrant) 194 } 195 AegisDecision::Rejected { reason } => { 196 let err_reason = reason.clone(); 197 self.audit_ledger.push(EffectAuditRecord { 198 intent_id: intent.id, 199 action: intent.action.clone(), 200 timestamp_utc: now_utc, 201 decision, 202 executed: false, 203 error: Some(err_reason.clone()), 204 }); 205 Err(AegisError::IrreversibleEffectDenied(err_reason)) 206 } 207 } 208 } 209 210 /// Audit ledger of all effect attempts. 211 pub fn audit_ledger(&self) -> &[EffectAuditRecord] { 212 &self.audit_ledger 213 } 214 } 215 216 #[cfg(test)] 217 mod tests { 218 use super::*; 219 use crate::capability::CapabilityScope; 220 use aienos_agent_state::LogicalAgentId; 221 use std::collections::BTreeMap; 222 use std::sync::atomic::{AtomicBool, Ordering}; 223 use std::sync::Arc; 224 225 #[test] 226 fn test_aegis_reversible_vs_irreversible_enforcement() { 227 let master_secret = [0x42u8; 32]; 228 let operator_secret = [0x99u8; 32]; 229 230 let mut graph = CapabilityGraph::new(master_secret); 231 let agent = LogicalAgentId::from_seed("aegis-test-agent"); 232 233 let fs_cap_id = [1u8; 16]; 234 graph.issue_root_token( 235 fs_cap_id, 236 agent, 237 CapabilityScope::Filesystem { 238 path_prefix: "/workspace".to_string(), 239 read_only: false, 240 }, 241 3, 242 2000, 243 ); 244 245 let evaluator = AegisEvaluator::new(operator_secret); 246 let mut broker = EffectBroker::new(evaluator); 247 248 // 1. A claimed World does not prove the handler is isolated. 249 let mut params = BTreeMap::new(); 250 params.insert("path".to_string(), "/workspace/test.txt".to_string()); 251 let world_id = Some([0xAAu8; 16]); 252 253 let reversible_intent = EffectIntent::new( 254 agent, 255 "fs.write", 256 params.clone(), 257 fs_cap_id, 258 true, // is_reversible 259 world_id, 260 ); 261 262 let missing_handler = broker.dispatch(&reversible_intent, &graph, None, 99); 263 assert!(matches!( 264 missing_handler, 265 Err(AegisError::MissingOperatorGrant) 266 )); 267 assert!(!broker.audit_ledger()[0].executed); 268 broker.register_handler("fs.write", |_| Ok("mock file write".to_string())); 269 broker.register_handler("net.fetch", |_| Ok("mock network fetch".to_string())); 270 271 let rev_result = broker.dispatch(&reversible_intent, &graph, None, 100); 272 assert!(matches!(rev_result, Err(AegisError::MissingOperatorGrant))); 273 274 // 2. IRREVERSIBLE: outside world without Operator Grant -> REJECTED 275 let irreversible_intent = EffectIntent::new( 276 agent, 277 "fs.write", 278 params.clone(), 279 fs_cap_id, 280 false, // is_reversible == false 281 None, 282 ); 283 284 let unapproved_res = broker.dispatch(&irreversible_intent, &graph, None, 101); 285 assert!( 286 matches!(unapproved_res, Err(AegisError::MissingOperatorGrant)), 287 "Irreversible intent without operator grant must be rejected" 288 ); 289 290 // 3. IRREVERSIBLE with valid Operator Grant -> APPROVED 291 let grant = OperatorGrant::issue( 292 irreversible_intent.id, 293 "human_operator_1", 294 &operator_secret, 295 102, 296 ); 297 298 let approved_res = broker.dispatch(&irreversible_intent, &graph, Some(&grant), 102); 299 assert!( 300 approved_res.is_ok(), 301 "Irreversible intent with operator grant must succeed" 302 ); 303 304 // 4. Verification that forged operator grant fails 305 let bad_secret = [0x00u8; 32]; 306 let forged_grant = 307 OperatorGrant::issue(irreversible_intent.id, "forged_operator", &bad_secret, 103); 308 let forged_res = broker.dispatch(&irreversible_intent, &graph, Some(&forged_grant), 103); 309 assert!( 310 forged_res.is_err(), 311 "Forged operator grant must be strictly rejected" 312 ); 313 314 // 5. ADR 0004: Autonomous external outbound fetch via Standing Capability 315 let standing_cap_id = [2u8; 16]; 316 graph.issue_root_token( 317 standing_cap_id, 318 agent, 319 CapabilityScope::StandingFetch { 320 host: "api.sovereign.local".to_string(), 321 }, 322 2, 323 2000, 324 ); 325 326 let mut fetch_params = BTreeMap::new(); 327 fetch_params.insert("host".to_string(), "api.sovereign.local".to_string()); 328 let fetch_intent = EffectIntent::new( 329 agent, 330 "net.fetch", 331 fetch_params, 332 standing_cap_id, 333 false, // external effect crossing boundary 334 None, 335 ); 336 337 // Dispatches autonomously without requiring interactive human prompt 338 let fetch_res = broker.dispatch(&fetch_intent, &graph, None, 104); 339 assert!( 340 fetch_res.is_ok(), 341 "Standing capability autonomous fetch must be authorized" 342 ); 343 } 344 345 #[test] 346 fn claimed_world_cannot_authorize_network_or_escaped_filesystem_effects() { 347 let mut graph = CapabilityGraph::new([0x42; 32]); 348 let agent = LogicalAgentId::from_seed("boundary-test-agent"); 349 let evaluator = AegisEvaluator::new([0x99; 32]); 350 351 let net_id = [1; 16]; 352 graph.issue_root_token( 353 net_id, 354 agent, 355 CapabilityScope::Network { 356 host: "example.org".into(), 357 port: 443, 358 }, 359 0, 360 2000, 361 ); 362 let mut net_params = BTreeMap::new(); 363 net_params.insert("host".into(), "example.org".into()); 364 net_params.insert("port".into(), "443".into()); 365 let net_intent = EffectIntent::new( 366 agent, 367 "net.connect", 368 net_params, 369 net_id, 370 true, 371 Some([9; 16]), 372 ); 373 assert!(matches!( 374 evaluator.evaluate(&net_intent, &graph, None, 100), 375 AegisDecision::RequiresOperatorApproval { .. } 376 )); 377 378 let fs_id = [2; 16]; 379 graph.issue_root_token( 380 fs_id, 381 agent, 382 CapabilityScope::Filesystem { 383 path_prefix: "/workspace".into(), 384 read_only: false, 385 }, 386 0, 387 2000, 388 ); 389 for path in ["/workspace-extra/file", "/workspace/../etc/passwd"] { 390 let mut params = BTreeMap::new(); 391 params.insert("path".into(), path.into()); 392 let intent = EffectIntent::new(agent, "fs.write", params, fs_id, true, Some([9; 16])); 393 assert!(matches!( 394 evaluator.evaluate(&intent, &graph, None, 100), 395 AegisDecision::Rejected { .. } 396 )); 397 } 398 } 399 400 #[test] 401 fn world_bound_write_uses_delta_and_rollback_discards_it() { 402 let mut graph = CapabilityGraph::new([0x42; 32]); 403 let agent = LogicalAgentId::from_seed("world-bound-agent"); 404 let fs_id = [1; 16]; 405 let world_id = [9; 16]; 406 graph.issue_root_token( 407 fs_id, 408 agent, 409 CapabilityScope::Filesystem { 410 path_prefix: "/workspace".into(), 411 read_only: false, 412 }, 413 0, 414 2000, 415 ); 416 let mut broker = EffectBroker::new(AegisEvaluator::new([0x99; 32])); 417 broker 418 .register_world(JSpaceWorld::new(world_id, None)) 419 .unwrap(); 420 let host_handler_called = Arc::new(AtomicBool::new(false)); 421 let called = Arc::clone(&host_handler_called); 422 broker.register_handler("fs.write", move |_| { 423 called.store(true, Ordering::SeqCst); 424 Ok("host write".into()) 425 }); 426 427 let mut params = BTreeMap::new(); 428 params.insert("path".into(), "/workspace/note.txt".into()); 429 params.insert("content".into(), "draft".into()); 430 let intent = EffectIntent::new(agent, "fs.write", params, fs_id, true, Some(world_id)); 431 assert!(broker.dispatch(&intent, &graph, None, 100).is_ok()); 432 assert!(!host_handler_called.load(Ordering::SeqCst)); 433 assert_eq!( 434 broker 435 .world(&world_id) 436 .unwrap() 437 .read_file("/workspace/note.txt", |_| None), 438 Some(b"draft".to_vec()) 439 ); 440 let mut delete_params = BTreeMap::new(); 441 delete_params.insert("path".into(), "/workspace/note.txt".into()); 442 let delete = EffectIntent::new( 443 agent, 444 "fs.delete", 445 delete_params, 446 fs_id, 447 true, 448 Some(world_id), 449 ); 450 assert!(broker.dispatch(&delete, &graph, None, 100).is_ok()); 451 assert_eq!( 452 broker 453 .world(&world_id) 454 .unwrap() 455 .read_file("/workspace/note.txt", |_| Some(b"base".to_vec())), 456 None 457 ); 458 broker.rollback_world(&world_id).unwrap(); 459 assert_eq!( 460 broker 461 .world(&world_id) 462 .unwrap() 463 .read_file("/workspace/note.txt", |_| None), 464 None 465 ); 466 assert!(matches!( 467 broker.dispatch(&intent, &graph, None, 101), 468 Err(AegisError::MissingOperatorGrant) 469 )); 470 } 471 }