aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / aienos-aegis / src / capability.rs
| 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 | //! Unforgeable capability tokens and the AEGIS Directed Acyclic Capability Graph (ยง13). |
| 17 | |
| 18 | use aienos_agent_state::LogicalAgentId; |
| 19 | use aienos_kernel::crypto::sha256; |
| 20 | use core::fmt; |
| 21 | use serde::{Deserialize, Serialize}; |
| 22 | use std::collections::{HashMap, HashSet}; |
| 23 | use std::path::{Component, Path}; |
| 24 | |
| 25 | /// Check a lexical absolute path boundary. Handlers must still resolve symlinks safely. |
| 26 | pub(crate) fn path_within(path: &str, prefix: &str) -> bool { |
| 27 | let path = Path::new(path); |
| 28 | let prefix = Path::new(prefix); |
| 29 | path.is_absolute() |
| 30 | && prefix.is_absolute() |
| 31 | && !path.components().any(|part| part == Component::ParentDir) |
| 32 | && !prefix.components().any(|part| part == Component::ParentDir) |
| 33 | && path.starts_with(prefix) |
| 34 | } |
| 35 | |
| 36 | /// Errors occurring in capability evaluation and graph operations. |
| 37 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 38 | pub enum AegisError { |
| 39 | InvalidSignature, |
| 40 | TokenExpired, |
| 41 | TokenRevoked, |
| 42 | TokenNotFound([u8; 16]), |
| 43 | UnauthorizedAgent, |
| 44 | ScopeExceeded(String), |
| 45 | DelegationDepthExceeded, |
| 46 | IrreversibleEffectDenied(String), |
| 47 | MissingOperatorGrant, |
| 48 | ExecutionFailed(String), |
| 49 | } |
| 50 | |
| 51 | impl fmt::Display for AegisError { |
| 52 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 53 | match self { |
| 54 | Self::InvalidSignature => write!(f, "Invalid capability cryptographic signature"), |
| 55 | Self::TokenExpired => write!(f, "Capability token has expired"), |
| 56 | Self::TokenRevoked => write!(f, "Capability token has been revoked"), |
| 57 | Self::TokenNotFound(id) => write!(f, "Capability token not found: {:02x?}", id), |
| 58 | Self::UnauthorizedAgent => { |
| 59 | write!(f, "Agent is not the authorized holder of capability") |
| 60 | } |
| 61 | Self::ScopeExceeded(msg) => { |
| 62 | write!(f, "Requested action exceeds capability scope: {}", msg) |
| 63 | } |
| 64 | Self::DelegationDepthExceeded => write!(f, "Maximum delegation depth exceeded"), |
| 65 | Self::IrreversibleEffectDenied(msg) => { |
| 66 | write!(f, "Irreversible effect denied by policy: {}", msg) |
| 67 | } |
| 68 | Self::MissingOperatorGrant => { |
| 69 | write!( |
| 70 | f, |
| 71 | "Irreversible effect requires explicit operator cryptographic grant" |
| 72 | ) |
| 73 | } |
| 74 | Self::ExecutionFailed(msg) => write!(f, "Effect execution failed: {}", msg), |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Scope definition for granular capability permissions. |
| 80 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 81 | pub enum CapabilityScope { |
| 82 | Filesystem { |
| 83 | path_prefix: String, |
| 84 | read_only: bool, |
| 85 | }, |
| 86 | Network { |
| 87 | host: String, |
| 88 | port: u16, |
| 89 | }, |
| 90 | Model { |
| 91 | model_name: String, |
| 92 | max_tokens: u32, |
| 93 | }, |
| 94 | Device { |
| 95 | device_name: String, |
| 96 | read_only: bool, |
| 97 | }, |
| 98 | World { |
| 99 | max_depth: u32, |
| 100 | }, |
| 101 | /// Standing capability for autonomous external network fetches (ADR 0004). |
| 102 | StandingFetch { |
| 103 | host: String, |
| 104 | }, |
| 105 | SystemAdmin, |
| 106 | Custom { |
| 107 | namespace: String, |
| 108 | action: String, |
| 109 | }, |
| 110 | } |
| 111 | |
| 112 | impl CapabilityScope { |
| 113 | /// Check if child scope is an attenuation (equal or stricter subset) of self. |
| 114 | pub fn contains(&self, child: &CapabilityScope) -> bool { |
| 115 | match (self, child) { |
| 116 | (CapabilityScope::SystemAdmin, _) => true, |
| 117 | ( |
| 118 | CapabilityScope::StandingFetch { host: h_parent }, |
| 119 | CapabilityScope::StandingFetch { host: h_child }, |
| 120 | ) => h_parent == "*" || h_parent == h_child, |
| 121 | ( |
| 122 | CapabilityScope::Filesystem { |
| 123 | path_prefix: p_parent, |
| 124 | read_only: ro_parent, |
| 125 | }, |
| 126 | CapabilityScope::Filesystem { |
| 127 | path_prefix: p_child, |
| 128 | read_only: ro_child, |
| 129 | }, |
| 130 | ) => path_within(p_child, p_parent) && (*ro_parent == *ro_child || *ro_child), |
| 131 | ( |
| 132 | CapabilityScope::Network { |
| 133 | host: h_parent, |
| 134 | port: p_parent, |
| 135 | }, |
| 136 | CapabilityScope::Network { |
| 137 | host: h_child, |
| 138 | port: p_child, |
| 139 | }, |
| 140 | ) => { |
| 141 | (h_parent == "*" || h_parent == h_child) && (*p_parent == 0 || p_parent == p_child) |
| 142 | } |
| 143 | ( |
| 144 | CapabilityScope::Model { |
| 145 | model_name: m_parent, |
| 146 | max_tokens: tok_parent, |
| 147 | }, |
| 148 | CapabilityScope::Model { |
| 149 | model_name: m_child, |
| 150 | max_tokens: tok_child, |
| 151 | }, |
| 152 | ) => (m_parent == "*" || m_parent == m_child) && tok_child <= tok_parent, |
| 153 | ( |
| 154 | CapabilityScope::World { |
| 155 | max_depth: d_parent, |
| 156 | }, |
| 157 | CapabilityScope::World { max_depth: d_child }, |
| 158 | ) => d_child <= d_parent, |
| 159 | ( |
| 160 | CapabilityScope::Custom { |
| 161 | namespace: ns_p, |
| 162 | action: act_p, |
| 163 | }, |
| 164 | CapabilityScope::Custom { |
| 165 | namespace: ns_c, |
| 166 | action: act_c, |
| 167 | }, |
| 168 | ) => ns_p == ns_c && (act_p == "*" || act_p == act_c), |
| 169 | _ => false, |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Unforgeable cryptographic capability token. |
| 175 | #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] |
| 176 | pub struct CapabilityToken { |
| 177 | pub id: [u8; 16], |
| 178 | pub parent_id: Option<[u8; 16]>, |
| 179 | pub issuer: String, |
| 180 | pub holder: LogicalAgentId, |
| 181 | pub scope: CapabilityScope, |
| 182 | pub delegation_depth: u32, |
| 183 | pub valid_until_utc: u64, |
| 184 | pub signature: [u8; 32], |
| 185 | } |
| 186 | |
| 187 | impl CapabilityToken { |
| 188 | /// Compute HMAC-SHA256 signature over token payload. |
| 189 | #[allow(clippy::too_many_arguments)] |
| 190 | pub fn compute_signature( |
| 191 | secret: &[u8; 32], |
| 192 | id: &[u8; 16], |
| 193 | parent_id: Option<&[u8; 16]>, |
| 194 | issuer: &str, |
| 195 | holder: &LogicalAgentId, |
| 196 | scope: &CapabilityScope, |
| 197 | delegation_depth: u32, |
| 198 | valid_until_utc: u64, |
| 199 | ) -> [u8; 32] { |
| 200 | let parent_marker = [u8::from(parent_id.is_some())]; |
| 201 | let absent_parent = [0u8; 16]; |
| 202 | let parent = parent_id.unwrap_or(&absent_parent); |
| 203 | let issuer_len = (issuer.len() as u64).to_be_bytes(); |
| 204 | let scope_bytes = serde_json::to_vec(scope).unwrap_or_default(); |
| 205 | let scope_len = (scope_bytes.len() as u64).to_be_bytes(); |
| 206 | sha256::hmac_sha256( |
| 207 | secret, |
| 208 | &[ |
| 209 | b"AIENOS_CAP_V1", |
| 210 | id, |
| 211 | &parent_marker, |
| 212 | parent, |
| 213 | &issuer_len, |
| 214 | issuer.as_bytes(), |
| 215 | holder.as_bytes(), |
| 216 | &scope_len, |
| 217 | &scope_bytes, |
| 218 | &delegation_depth.to_be_bytes(), |
| 219 | &valid_until_utc.to_be_bytes(), |
| 220 | ], |
| 221 | ) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// Directed Acyclic Capability Graph managing root authorities, delegations, and revocations. |
| 226 | pub struct CapabilityGraph { |
| 227 | master_secret: [u8; 32], |
| 228 | tokens: HashMap<[u8; 16], CapabilityToken>, |
| 229 | child_map: HashMap<[u8; 16], Vec<[u8; 16]>>, |
| 230 | revoked_tokens: HashSet<[u8; 16]>, |
| 231 | } |
| 232 | |
| 233 | impl CapabilityGraph { |
| 234 | /// Initialize capability graph with master kernel authority secret. |
| 235 | pub fn new(master_secret: [u8; 32]) -> Self { |
| 236 | Self { |
| 237 | master_secret, |
| 238 | tokens: HashMap::new(), |
| 239 | child_map: HashMap::new(), |
| 240 | revoked_tokens: HashSet::new(), |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | /// Issue a root capability granted directly by the operator. |
| 245 | pub fn issue_root_token( |
| 246 | &mut self, |
| 247 | id: [u8; 16], |
| 248 | holder: LogicalAgentId, |
| 249 | scope: CapabilityScope, |
| 250 | delegation_depth: u32, |
| 251 | valid_until_utc: u64, |
| 252 | ) -> CapabilityToken { |
| 253 | let signature = CapabilityToken::compute_signature( |
| 254 | &self.master_secret, |
| 255 | &id, |
| 256 | None, |
| 257 | "root.authority", |
| 258 | &holder, |
| 259 | &scope, |
| 260 | delegation_depth, |
| 261 | valid_until_utc, |
| 262 | ); |
| 263 | |
| 264 | let token = CapabilityToken { |
| 265 | id, |
| 266 | parent_id: None, |
| 267 | issuer: "root.authority".to_string(), |
| 268 | holder, |
| 269 | scope, |
| 270 | delegation_depth, |
| 271 | valid_until_utc, |
| 272 | signature, |
| 273 | }; |
| 274 | |
| 275 | self.tokens.insert(id, token.clone()); |
| 276 | token |
| 277 | } |
| 278 | |
| 279 | /// Derive an attenuated child capability token. |
| 280 | pub fn derive_child_token( |
| 281 | &mut self, |
| 282 | parent_id: [u8; 16], |
| 283 | child_id: [u8; 16], |
| 284 | new_holder: LogicalAgentId, |
| 285 | child_scope: CapabilityScope, |
| 286 | now_utc: u64, |
| 287 | ) -> Result<CapabilityToken, AegisError> { |
| 288 | let parent = self.get_token(&parent_id)?; |
| 289 | self.validate_token(&parent, now_utc)?; |
| 290 | |
| 291 | if parent.delegation_depth == 0 { |
| 292 | return Err(AegisError::DelegationDepthExceeded); |
| 293 | } |
| 294 | |
| 295 | if !parent.scope.contains(&child_scope) { |
| 296 | return Err(AegisError::ScopeExceeded(format!( |
| 297 | "Child scope {:?} not contained in parent scope {:?}", |
| 298 | child_scope, parent.scope |
| 299 | ))); |
| 300 | } |
| 301 | |
| 302 | let delegation_depth = parent.delegation_depth - 1; |
| 303 | let valid_until_utc = parent.valid_until_utc; |
| 304 | |
| 305 | let signature = CapabilityToken::compute_signature( |
| 306 | &self.master_secret, |
| 307 | &child_id, |
| 308 | Some(&parent_id), |
| 309 | &format!("cap:{:02x?}", parent_id), |
| 310 | &new_holder, |
| 311 | &child_scope, |
| 312 | delegation_depth, |
| 313 | valid_until_utc, |
| 314 | ); |
| 315 | |
| 316 | let child = CapabilityToken { |
| 317 | id: child_id, |
| 318 | parent_id: Some(parent_id), |
| 319 | issuer: format!("cap:{:02x?}", parent_id), |
| 320 | holder: new_holder, |
| 321 | scope: child_scope, |
| 322 | delegation_depth, |
| 323 | valid_until_utc, |
| 324 | signature, |
| 325 | }; |
| 326 | |
| 327 | self.tokens.insert(child_id, child.clone()); |
| 328 | self.child_map.entry(parent_id).or_default().push(child_id); |
| 329 | |
| 330 | Ok(child) |
| 331 | } |
| 332 | |
| 333 | /// Revoke a capability token and all downstream delegated descendants. |
| 334 | pub fn revoke(&mut self, token_id: [u8; 16]) { |
| 335 | let mut queue = vec![token_id]; |
| 336 | while let Some(current) = queue.pop() { |
| 337 | self.revoked_tokens.insert(current); |
| 338 | if let Some(children) = self.child_map.get(¤t) { |
| 339 | for &child in children { |
| 340 | queue.push(child); |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | /// Get token by ID. |
| 347 | pub fn get_token(&self, id: &[u8; 16]) -> Result<CapabilityToken, AegisError> { |
| 348 | self.tokens |
| 349 | .get(id) |
| 350 | .cloned() |
| 351 | .ok_or(AegisError::TokenNotFound(*id)) |
| 352 | } |
| 353 | |
| 354 | /// Cryptographically validate token authenticity, expiry, and revocation. |
| 355 | pub fn validate_token(&self, token: &CapabilityToken, now_utc: u64) -> Result<(), AegisError> { |
| 356 | if self.revoked_tokens.contains(&token.id) { |
| 357 | return Err(AegisError::TokenRevoked); |
| 358 | } |
| 359 | |
| 360 | // Cascading ancestor revocation check |
| 361 | let mut curr_parent = token.parent_id; |
| 362 | while let Some(pid) = curr_parent { |
| 363 | if self.revoked_tokens.contains(&pid) { |
| 364 | return Err(AegisError::TokenRevoked); |
| 365 | } |
| 366 | curr_parent = self.tokens.get(&pid).and_then(|p| p.parent_id); |
| 367 | } |
| 368 | |
| 369 | if now_utc > token.valid_until_utc { |
| 370 | return Err(AegisError::TokenExpired); |
| 371 | } |
| 372 | |
| 373 | let expected_sig = CapabilityToken::compute_signature( |
| 374 | &self.master_secret, |
| 375 | &token.id, |
| 376 | token.parent_id.as_ref(), |
| 377 | &token.issuer, |
| 378 | &token.holder, |
| 379 | &token.scope, |
| 380 | token.delegation_depth, |
| 381 | token.valid_until_utc, |
| 382 | ); |
| 383 | |
| 384 | if token.signature != expected_sig { |
| 385 | return Err(AegisError::InvalidSignature); |
| 386 | } |
| 387 | |
| 388 | Ok(()) |
| 389 | } |
| 390 | } |
| 391 | |
| 392 | #[cfg(test)] |
| 393 | mod tests { |
| 394 | use super::*; |
| 395 | |
| 396 | #[test] |
| 397 | fn filesystem_scope_rejects_sibling_and_traversal_paths() { |
| 398 | assert!(path_within("/workspace/src/main.rs", "/workspace")); |
| 399 | assert!(path_within("/workspace", "/workspace")); |
| 400 | assert!(!path_within("/workspace-extra/file", "/workspace")); |
| 401 | assert!(!path_within("/workspace/../etc/passwd", "/workspace")); |
| 402 | assert!(!path_within("workspace/file", "/workspace")); |
| 403 | |
| 404 | let parent = CapabilityScope::Filesystem { |
| 405 | path_prefix: "/workspace".into(), |
| 406 | read_only: false, |
| 407 | }; |
| 408 | for escaped in ["/workspace-extra", "/workspace/../etc"] { |
| 409 | assert!(!parent.contains(&CapabilityScope::Filesystem { |
| 410 | path_prefix: escaped.into(), |
| 411 | read_only: true, |
| 412 | })); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | #[test] |
| 417 | fn test_capability_attenuation_and_cascading_revocation() { |
| 418 | let master_secret = [0x5Au8; 32]; |
| 419 | let mut graph = CapabilityGraph::new(master_secret); |
| 420 | let root_agent = LogicalAgentId::from_seed("root_agent"); |
| 421 | let sub_agent = LogicalAgentId::from_seed("sub_agent"); |
| 422 | |
| 423 | let root_id = [1u8; 16]; |
| 424 | let root_token = graph.issue_root_token( |
| 425 | root_id, |
| 426 | root_agent, |
| 427 | CapabilityScope::Filesystem { |
| 428 | path_prefix: "/workspace".to_string(), |
| 429 | read_only: false, |
| 430 | }, |
| 431 | 3, |
| 432 | 2000, |
| 433 | ); |
| 434 | assert!(graph.validate_token(&root_token, 100).is_ok()); |
| 435 | |
| 436 | // 1. Derive attenuated child token (read-only subset) |
| 437 | let child_id = [2u8; 16]; |
| 438 | let child_token = graph |
| 439 | .derive_child_token( |
| 440 | root_id, |
| 441 | child_id, |
| 442 | sub_agent, |
| 443 | CapabilityScope::Filesystem { |
| 444 | path_prefix: "/workspace/src".to_string(), |
| 445 | read_only: true, |
| 446 | }, |
| 447 | 101, |
| 448 | ) |
| 449 | .expect("Attenuated derivation must succeed"); |
| 450 | assert!(graph.validate_token(&child_token, 101).is_ok()); |
| 451 | |
| 452 | // 2. Scope expansion attempt must fail (trying to claim root path or rw) |
| 453 | let invalid_child_id = [3u8; 16]; |
| 454 | let expanded_res = graph.derive_child_token( |
| 455 | root_id, |
| 456 | invalid_child_id, |
| 457 | sub_agent, |
| 458 | CapabilityScope::Filesystem { |
| 459 | path_prefix: "/etc".to_string(), |
| 460 | read_only: false, |
| 461 | }, |
| 462 | 102, |
| 463 | ); |
| 464 | assert!(matches!(expanded_res, Err(AegisError::ScopeExceeded(_)))); |
| 465 | |
| 466 | // 3. Expiration check |
| 467 | assert!(matches!( |
| 468 | graph.validate_token(&child_token, 2001), |
| 469 | Err(AegisError::TokenExpired) |
| 470 | )); |
| 471 | |
| 472 | // 4. Cascading revocation: revoking root must invalidate child |
| 473 | graph.revoke(root_id); |
| 474 | assert!(matches!( |
| 475 | graph.validate_token(&root_token, 105), |
| 476 | Err(AegisError::TokenRevoked) |
| 477 | )); |
| 478 | assert!(matches!( |
| 479 | graph.validate_token(&child_token, 105), |
| 480 | Err(AegisError::TokenRevoked) |
| 481 | )); |
| 482 | } |
| 483 | } |