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/synapse/blob/main/crates/synapse-auth/tests/f1_capability_chains.rs # synapse A component of the AienOS ecosystem. 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 `synapse / crates / synapse-auth / tests / f1_capability_chains.rs` 1306 lines ยท 47485 bytes Raw Blame History 1 //! ADR 0003 section 9 step F1: attenuated capability chains with path, reference, and change 2 //! scope, `Undo`, and partitioned rate, storage, and footprint quotas. 3 //! 4 //! Acceptance (each item names the test that proves it): 5 //! * no derived grant exceeds its parent in operations, paths, references, change scope, quotas, 6 //! or expiry: `f1_property_no_derived_grant_exceeds_its_parent` 7 //! * child quotas never sum above the parent's: `f1_property_child_quotas_never_sum_above_the_parent` 8 //! * forged chains refused: `f1_forged_chains_are_refused` 9 //! * stripped chains refused: `f1_stripped_chains_are_refused` 10 //! * reordered chains refused: `f1_reordered_chains_are_refused` 11 //! * a link bound to another repository refused: `f1_link_bound_to_another_repository_is_refused` 12 //! * a link bound to another audience refused: `f1_link_bound_to_another_audience_is_refused` 13 //! * out-of-scope path refused: `f1_out_of_scope_path_is_refused` 14 //! * a chain with an ancestor revoked at the request's `WalSeq` refused: 15 //! `f1_chain_with_an_ancestor_revoked_at_the_request_walseq_is_refused` 16 //! 17 //! The property tests use a seeded SplitMix64 generator (no new dependency); the seed and case 18 //! count are constants below and every failure message prints the seed, case, and caveats. 19 20 use `ed25519`_dalek::SigningKey; 21 use synapse_auth::{ 22 AuditOutcome, BoundaryKind, Capability, CapabilityChain, CapabilityLink, ChainQuotas, 23 ChainedRequest, ChangeScope, LinkCaveats, LinkDigest, OperationSet, PathScope, PolicyEnforcer, 24 ReferenceKind, ReferenceScope, RequestScope, MAX_CHAIN_DEPTH, ROOT_PARENT, 25 }; 26 use synapse_core::{encode_did_key_`ed25519`, ChangeId, RefusalCode, RepoId, WalSeq}; 27 28 const PROPERTY_SEED: u64 = 0xF1F1_0003_0025_5EED; 29 const NARROWING_CASES: u64 = 256; 30 const PARTITION_CASES: u64 = 256; 31 32 const ALL_CAPS: [Capability; 6] = [ 33 Capability::Read, 34 Capability::Propose, 35 Capability::Evaluate, 36 Capability::Review, 37 Capability::Publish, 38 Capability::Undo, 39 ]; 40 const ALL_OPS_BITS: u8 = 0b0011_1111; 41 const ALL_REF_BITS: u8 = 0b0000_0011; 42 43 struct SplitMix64(u64); 44 45 impl SplitMix64 { 46 fn new(seed: u64) -> Self { 47 Self(seed) 48 } 49 fn next(&mut self) -> u64 { 50 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15); 51 let mut z = self.0; 52 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); 53 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); 54 z ^ (z >> 31) 55 } 56 /// Uniform in `0..=max`. 57 fn upto(&mut self, max: u64) -> u64 { 58 if max == u64::MAX { 59 self.next() 60 } else { 61 self.next() % (max + 1) 62 } 63 } 64 fn below(&mut self, n: u64) -> u64 { 65 self.next() % n 66 } 67 fn chance(&mut self, num: u64, den: u64) -> bool { 68 self.below(den) < num 69 } 70 fn bytes32(&mut self) -> [u8; 32] { 71 let mut out = [0u8; 32]; 72 for chunk in out.chunks_mut(8) { 73 chunk.copy_from_slice(&self.next().to_le_bytes()); 74 } 75 out 76 } 77 fn key(&mut self) -> SigningKey { 78 SigningKey::from_bytes(&self.bytes32()) 79 } 80 } 81 82 fn repo() -> RepoId { 83 RepoId::new("aien-spark/synapse").unwrap() 84 } 85 86 fn pubkey(k: &SigningKey) -> [u8; 32] { 87 k.verifying_key().to_bytes() 88 } 89 90 fn change_id(n: u8) -> ChangeId { 91 ChangeId([n; 16]) 92 } 93 94 fn wide_caveats() -> LinkCaveats { 95 LinkCaveats { 96 operations: OperationSet::from_capabilities(&ALL_CAPS), 97 paths: PathScope::whole_repository(), 98 references: ReferenceScope::from_kinds(&[ 99 ReferenceKind::OwnDrafts, 100 ReferenceKind::CanonicalViaPromotionQueue, 101 ]), 102 changes: ChangeScope::any(), 103 quotas: ChainQuotas { 104 max_ops_per_window: 1_000, 105 window_duration_ms: 60_000, 106 storage_bytes: 1 << 30, 107 footprint_paths: 1 << 20, 108 max_bytes_per_op: 1 << 20, 109 }, 110 issued_at_ms: 1_000, 111 expires_at_ms: 100_000, 112 } 113 } 114 115 const NOW: u64 = 2_000; 116 117 /// Authority A issues root to orchestrator O; O delegates `mid` to worker W; W delegates `leaf` 118 /// to sub-worker S. Granted at `WalSeq` 1, 2, 3. 119 struct Fx { 120 enforcer: PolicyEnforcer, 121 authority: SigningKey, 122 o: SigningKey, 123 w: SigningKey, 124 s: SigningKey, 125 root: CapabilityLink, 126 mid: CapabilityLink, 127 leaf: CapabilityLink, 128 } 129 130 impl Fx { 131 fn new() -> Self { 132 let authority = SigningKey::from_bytes(&[1u8; 32]); 133 let o = SigningKey::from_bytes(&[2u8; 32]); 134 let w = SigningKey::from_bytes(&[3u8; 32]); 135 let s = SigningKey::from_bytes(&[4u8; 32]); 136 let mut enforcer = PolicyEnforcer::new(); 137 enforcer.register_repo_authority(repo(), encode_did_key_`ed25519`(&pubkey(&authority))); 138 139 let root = CapabilityLink::issue( 140 &authority, 141 ROOT_PARENT, 142 [0xA0; 32], 143 repo(), 144 pubkey(&o), 145 wide_caveats(), 146 ); 147 let mut mid_cav = wide_caveats(); 148 mid_cav.paths = PathScope::new(vec!["crates/synapse-auth".into(), "docs".into()]).unwrap(); 149 mid_cav.quotas.max_ops_per_window = 500; 150 mid_cav.quotas.storage_bytes = 1 << 29; 151 mid_cav.quotas.footprint_paths = 1 << 19; 152 let mid = CapabilityLink::issue(&o, root.digest(), [0xA1; 32], repo(), pubkey(&w), mid_cav); 153 let mut leaf_cav = mid.caveats.clone(); 154 leaf_cav.operations = 155 OperationSet::from_capabilities(&[Capability::Read, Capability::Propose]); 156 leaf_cav.paths = PathScope::new(vec!["crates/synapse-auth".into()]).unwrap(); 157 leaf_cav.references = ReferenceScope::from_kinds(&[ReferenceKind::OwnDrafts]); 158 leaf_cav.changes = ChangeScope::only(vec![change_id(1)]).unwrap(); 159 leaf_cav.quotas.max_ops_per_window = 250; 160 leaf_cav.quotas.storage_bytes = 1 << 28; 161 leaf_cav.quotas.footprint_paths = 1 << 18; 162 let leaf = 163 CapabilityLink::issue(&w, mid.digest(), [0xA2; 32], repo(), pubkey(&s), leaf_cav); 164 165 let mut fx = Self { 166 enforcer, 167 authority, 168 o, 169 w, 170 s, 171 root, 172 mid, 173 leaf, 174 }; 175 let c1 = fx.chain(&[&fx.root.clone()]); 176 let c2 = fx.chain(&[&fx.root.clone(), &fx.mid.clone()]); 177 let c3 = fx.full_chain(); 178 fx.enforcer.grant_link(&c1, WalSeq(1), NOW).unwrap(); 179 fx.enforcer.grant_link(&c2, WalSeq(2), NOW).unwrap(); 180 fx.enforcer.grant_link(&c3, WalSeq(3), NOW).unwrap(); 181 fx 182 } 183 184 fn chain(&self, links: &[&CapabilityLink]) -> CapabilityChain { 185 CapabilityChain::new(links.iter().map(|l| (*l).clone()).collect()) 186 } 187 188 fn full_chain(&self) -> CapabilityChain { 189 self.chain(&[&self.root, &self.mid, &self.leaf]) 190 } 191 192 fn request( 193 &self, 194 signer: &SigningKey, 195 chain: CapabilityChain, 196 cap: Capability, 197 scope: RequestScope, 198 nonce: u8, 199 ) -> ChainedRequest { 200 ChainedRequest::sign_new( 201 signer, 202 chain, 203 repo(), 204 cap, 205 scope, 206 [nonce; 32], 207 NOW, 208 b"payload".to_vec(), 209 ) 210 } 211 212 fn authorize(&mut self, req: &ChainedRequest, seq: u64) -> Result<(), RefusalCode> { 213 self.enforcer 214 .authorize_chain( 215 BoundaryKind::Api, 216 "submit", 217 &repo(), 218 req.required_capability, 219 req, 220 WalSeq(seq), 221 NOW, 222 ) 223 .map_err(|e| e.code) 224 } 225 } 226 227 fn paths(p: &[&str]) -> RequestScope { 228 RequestScope { 229 paths: p.iter().map(|s| s.to_string()).collect(), 230 ..RequestScope::default() 231 } 232 } 233 234 fn in_scope() -> RequestScope { 235 paths(&["crates/synapse-auth/src/lib.rs"]) 236 } 237 #[test] 238 fn chained_authorization_backpressures_before_evaluating_request() { 239 use synapse_auth::{AuditOutcome, MAX_AUDIT_ENTRIES}; 240 let mut fx = Fx::new(); 241 let req = fx.request(&fx.s, fx.full_chain(), Capability::Propose, in_scope(), 42); 242 for _ in 0..MAX_AUDIT_ENTRIES { 243 fx.enforcer 244 .audit_log_mut() 245 .record( 246 NOW, 247 BoundaryKind::Api, 248 repo(), 249 "untrusted".into(), 250 Capability::Propose, 251 "wire_submit", 252 AuditOutcome::Refused { 253 code: RefusalCode::AuthChainBroken, 254 reason: "invalid".into(), 255 }, 256 ) 257 .unwrap(); 258 } 259 let head = fx.enforcer.audit_log().verify_chain().unwrap(); 260 assert_eq!( 261 fx.authorize(&req, 4), 262 Err(RefusalCode::BackpressureOverCapacity) 263 ); 264 assert_eq!(fx.enforcer.audit_log().verify_chain().unwrap(), head); 265 } 266 267 // --------------------------------------------------------------------------------------------- 268 // Property: no derived grant exceeds its parent. 269 // --------------------------------------------------------------------------------------------- 270 271 /// Independent model of prefix coverage at segment boundaries (not the crate's code). 272 fn oracle_covers(prefixes: &[String], path: &str) -> bool { 273 prefixes.iter().any(|p| { 274 if p.is_empty() { 275 return true; 276 } 277 if path.is_empty() { 278 return false; 279 } 280 let ps: Vec<&str> = p.split('/').collect(); 281 let xs: Vec<&str> = path.split('/').collect(); 282 xs.len() >= ps.len() && xs[..ps.len()] == ps[..] 283 }) 284 } 285 286 /// The first dimension in which `child` exceeds `parent` under the independent model. 287 fn oracle_exceeds(child: &LinkCaveats, parent: &LinkCaveats) -> Option<&'static str> { 288 if child.operations.bits() & !parent.operations.bits() != 0 { 289 return Some("operations"); 290 } 291 let parent_prefixes = parent.paths.prefixes(); 292 for c in child.paths.prefixes() { 293 let probes = [c.clone(), format!("{c}/probe"), format!("{c}/probe/deeper")]; 294 for probe in probes.iter() { 295 let probe = probe.trim_start_matches('/'); 296 if oracle_covers(child.paths.prefixes(), probe) 297 && !oracle_covers(parent_prefixes, probe) 298 { 299 return Some("paths"); 300 } 301 } 302 } 303 if child.references.bits() & !parent.references.bits() != 0 { 304 return Some("references"); 305 } 306 match (child.changes.ids(), parent.changes.ids()) { 307 (_, None) => {} 308 (None, Some(_)) => return Some("change scope"), 309 (Some(c), Some(p)) => { 310 if c.iter().any(|id| !p.contains(id)) { 311 return Some("change scope"); 312 } 313 } 314 } 315 let (c, p) = (&child.quotas, &parent.quotas); 316 if c.window_duration_ms != p.window_duration_ms 317 || c.max_ops_per_window > p.max_ops_per_window 318 || c.storage_bytes > p.storage_bytes 319 || c.footprint_paths > p.footprint_paths 320 || c.max_bytes_per_op > p.max_bytes_per_op 321 { 322 return Some("quotas"); 323 } 324 if child.issued_at_ms < parent.issued_at_ms || child.expires_at_ms > parent.expires_at_ms { 325 return Some("expiry"); 326 } 327 None 328 } 329 330 const SEGMENTS: [&str; 8] = ["src", "docs", "crates", "tests", "a", "b", "ab", "a-b"]; 331 332 fn random_prefix(rng: &mut SplitMix64) -> String { 333 let depth = 1 + rng.below(2) as usize; 334 (0..depth) 335 .map(|_| SEGMENTS[rng.below(SEGMENTS.len() as u64) as usize]) 336 .collect::>() 337 .join("/") 338 } 339 340 fn random_change_ids(rng: &mut SplitMix64, pool: u8, max: u64) -> Vec { 341 (0..rng.upto(max)) 342 .map(|_| change_id(1 + rng.below(pool as u64) as u8)) 343 .collect() 344 } 345 346 fn random_root_caveats(rng: &mut SplitMix64) -> LinkCaveats { 347 let paths = if rng.chance(1, 10) { 348 PathScope::whole_repository() 349 } else { 350 PathScope::new((0..1 + rng.below(3)).map(|_| random_prefix(rng)).collect()).unwrap() 351 }; 352 let changes = if rng.chance(1, 5) { 353 ChangeScope::any() 354 } else { 355 ChangeScope::only(random_change_ids(rng, 8, 4)).unwrap() 356 }; 357 let issued = 1_000 + rng.below(500); 358 LinkCaveats { 359 operations: OperationSet::from_bits(rng.upto(ALL_OPS_BITS as u64) as u8).unwrap(), 360 paths, 361 references: ReferenceScope::from_bits(rng.upto(ALL_REF_BITS as u64) as u8).unwrap(), 362 changes, 363 quotas: ChainQuotas { 364 max_ops_per_window: 1 + rng.below(1_000) as u32, 365 window_duration_ms: if rng.chance(1, 2) { 1_000 } else { 60_000 }, 366 storage_bytes: 1 + rng.below(1 << 30), 367 footprint_paths: 1 + rng.below(1 << 20), 368 max_bytes_per_op: 1 + rng.below(1 << 20), 369 }, 370 issued_at_ms: issued, 371 expires_at_ms: NOW + 1 + rng.below(1_000_000), 372 } 373 } 374 375 /// A child that narrows `parent` in every dimension; partitioned quotas take at most a quarter 376 /// so up to three siblings always fit. 377 fn narrowed(rng: &mut SplitMix64, parent: &LinkCaveats) -> LinkCaveats { 378 let paths = if parent.paths.prefixes().iter().any(String::is_empty) { 379 if rng.chance(1, 4) { 380 PathScope::whole_repository() 381 } else { 382 PathScope::new((0..1 + rng.below(2)).map(|_| random_prefix(rng)).collect()).unwrap() 383 } 384 } else { 385 let mut picked = Vec::new(); 386 for p in parent.paths.prefixes() { 387 match rng.below(3) { 388 0 => {} 389 1 => picked.push(p.clone()), 390 _ => picked.push(format!("{p}/{}", random_prefix(rng))), 391 } 392 } 393 PathScope::new(picked).unwrap() 394 }; 395 let changes = match parent.changes.ids() { 396 None if rng.chance(1, 2) => ChangeScope::any(), 397 None => ChangeScope::only(random_change_ids(rng, 8, 3)).unwrap(), 398 Some(ids) => { 399 ChangeScope::only(ids.iter().copied().filter(|_| rng.chance(1, 2)).collect()).unwrap() 400 } 401 }; 402 let q = &parent.quotas; 403 LinkCaveats { 404 operations: OperationSet::from_bits(parent.operations.bits() & rng.next() as u8).unwrap(), 405 paths, 406 references: ReferenceScope::from_bits(parent.references.bits() & rng.next() as u8).unwrap(), 407 changes, 408 quotas: ChainQuotas { 409 max_ops_per_window: rng.upto(u64::from(q.max_ops_per_window / 4)) as u32, 410 window_duration_ms: q.window_duration_ms, 411 storage_bytes: rng.upto(q.storage_bytes / 4), 412 footprint_paths: rng.upto(q.footprint_paths / 4), 413 max_bytes_per_op: rng.upto(q.max_bytes_per_op), 414 }, 415 issued_at_ms: parent.issued_at_ms + rng.upto(NOW - parent.issued_at_ms), 416 expires_at_ms: NOW + rng.upto(parent.expires_at_ms - NOW), 417 } 418 } 419 420 const DIMENSIONS: [&str; 6] = [ 421 "operations", 422 "paths", 423 "references", 424 "change scope", 425 "quotas", 426 "expiry", 427 ]; 428 429 /// A child that is `narrowed` except wider than `parent` in dimension `dim`; `None` when the 430 /// parent is already maximal in that dimension. 431 fn widened(rng: &mut SplitMix64, parent: &LinkCaveats, dim: usize) -> Option { 432 let mut c = narrowed(rng, parent); 433 match DIMENSIONS[dim] { 434 "operations" => { 435 let missing = ALL_OPS_BITS & !parent.operations.bits(); 436 if missing == 0 { 437 return None; 438 } 439 let bit = 1u8 << missing.trailing_zeros(); 440 c.operations = OperationSet::from_bits(c.operations.bits() | bit).unwrap(); 441 } 442 "paths" => { 443 if parent.paths.prefixes().iter().any(String::is_empty) { 444 return None; 445 } 446 c.paths = if rng.chance(1, 3) { 447 PathScope::whole_repository() 448 } else { 449 let mut p = c.paths.prefixes().to_vec(); 450 p.push(format!("zz{}", rng.below(1_000))); 451 PathScope::new(p).unwrap() 452 }; 453 } 454 "references" => { 455 let missing = ALL_REF_BITS & !parent.references.bits(); 456 if missing == 0 { 457 return None; 458 } 459 let bit = 1u8 << missing.trailing_zeros(); 460 c.references = ReferenceScope::from_bits(c.references.bits() | bit).unwrap(); 461 } 462 "change scope" => { 463 let ids = parent.changes.ids()?; 464 c.changes = if rng.chance(1, 3) { 465 ChangeScope::any() 466 } else { 467 let mut v = c.changes.ids().unwrap_or(&[]).to_vec(); 468 v.push(change_id(100 + rng.below(100) as u8)); 469 debug_assert!(!ids.contains(v.last().unwrap())); 470 ChangeScope::only(v).unwrap() 471 }; 472 } 473 "quotas" => { 474 let q = &parent.quotas; 475 match rng.below(5) { 476 0 => c.quotas.max_ops_per_window = q.max_ops_per_window.checked_add(1)?, 477 1 => c.quotas.storage_bytes = q.storage_bytes.checked_add(1)?, 478 2 => c.quotas.footprint_paths = q.footprint_paths.checked_add(1)?, 479 3 => c.quotas.max_bytes_per_op = q.max_bytes_per_op.checked_add(1)?, 480 _ => c.quotas.window_duration_ms = q.window_duration_ms + 1, 481 } 482 } 483 "expiry" => { 484 if rng.chance(1, 2) { 485 c.expires_at_ms = parent.expires_at_ms + 1 + rng.below(1_000); 486 } else { 487 c.issued_at_ms = parent.issued_at_ms - 1; 488 } 489 } 490 _ => unreachable!(), 491 } 492 Some(c) 493 } 494 495 struct Node { 496 chain: CapabilityChain, 497 holder: SigningKey, 498 } 499 500 #[test] 501 fn f1_property_no_derived_grant_exceeds_its_parent() { 502 let mut accepted_narrowed = 0u64; 503 let mut refused_by_dim = [0u64; 6]; 504 for case in 0..NARROWING_CASES { 505 let mut rng = SplitMix64::new(PROPERTY_SEED ^ case.wrapping_mul(0x2545_F491_4F6C_DD1D)); 506 let authority = rng.key(); 507 let mut enforcer = PolicyEnforcer::new(); 508 enforcer.register_repo_authority(repo(), encode_did_key_`ed25519`(&pubkey(&authority))); 509 let root_holder = rng.key(); 510 let root = CapabilityLink::issue( 511 &authority, 512 ROOT_PARENT, 513 rng.bytes32(), 514 repo(), 515 pubkey(&root_holder), 516 random_root_caveats(&mut rng), 517 ); 518 let root_chain = CapabilityChain::new(vec![root]); 519 let mut seq = 1u64; 520 enforcer 521 .grant_link(&root_chain, WalSeq(seq), NOW) 522 .unwrap_or_else(|e| panic!("seed {PROPERTY_SEED:#x} case {case}: root refused {e}")); 523 let mut frontier = vec![Node { 524 chain: root_chain, 525 holder: root_holder, 526 }]; 527 while let Some(node) = frontier.pop() { 528 if node.chain.links.len() >= 4 { 529 continue; 530 } 531 let parent = node.chain.leaf().unwrap().clone(); 532 for _ in 0..1 + rng.below(3) { 533 let audience = rng.key(); 534 let wide_dim = if rng.chance(1, 2) { 535 None 536 } else { 537 Some(rng.below(6) as usize) 538 }; 539 let caveats = match wide_dim { 540 None => narrowed(&mut rng, &parent.caveats), 541 Some(d) => match widened(&mut rng, &parent.caveats, d) { 542 Some(c) => c, 543 None => continue, 544 }, 545 }; 546 let child = CapabilityLink::issue( 547 &node.holder, 548 parent.digest(), 549 rng.bytes32(), 550 repo(), 551 pubkey(&audience), 552 caveats.clone(), 553 ); 554 let chain = node.chain.extended(child); 555 seq += 1; 556 let granted = enforcer 557 .grant_link(&chain, WalSeq(seq), NOW) 558 .map_err(|e| e.code); 559 560 // The property: every link the server accepts lies inside its parent and inside 561 // every ancestor, under the independent model. 562 if granted.is_ok() { 563 for (i, ancestor) in chain.links[..chain.links.len() - 1].iter().enumerate() { 564 if let Some(dim) = oracle_exceeds(&caveats, &ancestor.caveats) { 565 panic!( 566 "seed {PROPERTY_SEED:#x} case {case}: accepted link exceeds \ 567 ancestor {i} in {dim}\n child {caveats:#?}\n ancestor {:#?}", 568 ancestor.caveats 569 ); 570 } 571 } 572 } 573 match wide_dim { 574 None => { 575 assert_eq!( 576 granted.map(|_| ()), 577 Ok(()), 578 "seed {PROPERTY_SEED:#x} case {case}: narrowed link refused\n \ 579 child {caveats:#?}\n parent {:#?}", 580 parent.caveats 581 ); 582 accepted_narrowed += 1; 583 frontier.push(Node { 584 chain, 585 holder: audience, 586 }); 587 } 588 Some(d) => { 589 assert_eq!( 590 granted.map(|_| ()), 591 Err(RefusalCode::AuthScopeEscalation), 592 "seed {PROPERTY_SEED:#x} case {case}: link wider in {} not refused", 593 DIMENSIONS[d] 594 ); 595 // The same widened chain presented on a request is refused too. 596 let req = ChainedRequest::sign_new( 597 &audience, 598 chain, 599 repo(), 600 Capability::Read, 601 RequestScope::default(), 602 rng.bytes32(), 603 NOW, 604 Vec::new(), 605 ); 606 let got = enforcer 607 .authorize_chain( 608 BoundaryKind::Api, 609 "read", 610 &repo(), 611 Capability::Read, 612 &req, 613 WalSeq(seq), 614 NOW, 615 ) 616 .map_err(|e| e.code); 617 assert_eq!( 618 got, 619 Err(RefusalCode::AuthScopeEscalation), 620 "seed {PROPERTY_SEED:#x} case {case}: request through a link wider \ 621 in {} not refused", 622 DIMENSIONS[d] 623 ); 624 refused_by_dim[d] += 1; 625 } 626 } 627 } 628 } 629 } 630 println!( 631 "seed {PROPERTY_SEED:#x}, {NARROWING_CASES} cases: {accepted_narrowed} narrowed links \ 632 accepted; widened links refused per dimension {DIMENSIONS:?} = {refused_by_dim:?}" 633 ); 634 assert!(accepted_narrowed > 0, "no narrowed link was generated"); 635 for (d, n) in refused_by_dim.iter().enumerate() { 636 assert!(*n > 0, "no widened link generated in {}", DIMENSIONS[d]); 637 } 638 } 639 640 // --------------------------------------------------------------------------------------------- 641 // Property: child quotas never sum above the parent's. 642 // --------------------------------------------------------------------------------------------- 643 644 #[derive(Clone, Copy, Default, Debug, PartialEq)] 645 struct Sum { 646 ops: u64, 647 storage: u64, 648 footprint: u64, 649 } 650 651 #[test] 652 fn f1_property_child_quotas_never_sum_above_the_parent() { 653 let (mut accepted, mut refused) = (0u64, 0u64); 654 for case in 0..PARTITION_CASES { 655 let mut rng = SplitMix64::new(PROPERTY_SEED ^ 0xC0FF_EE00 ^ case.wrapping_mul(0x9E37)); 656 let authority = rng.key(); 657 let mut enforcer = PolicyEnforcer::new(); 658 enforcer.register_repo_authority(repo(), encode_did_key_`ed25519`(&pubkey(&authority))); 659 let mut root_cav = wide_caveats(); 660 root_cav.quotas = ChainQuotas { 661 max_ops_per_window: rng.upto(200) as u32, 662 window_duration_ms: 60_000, 663 storage_bytes: rng.upto(10_000), 664 footprint_paths: rng.upto(1_000), 665 max_bytes_per_op: 1 << 20, 666 }; 667 let holder = rng.key(); 668 let root = CapabilityLink::issue( 669 &authority, 670 ROOT_PARENT, 671 rng.bytes32(), 672 repo(), 673 pubkey(&holder), 674 root_cav, 675 ); 676 let mut nodes = vec![(CapabilityChain::new(vec![root]), holder)]; 677 let mut seq = 1u64; 678 enforcer.grant_link(&nodes[0].0, WalSeq(seq), NOW).unwrap(); 679 let mut children_sum = vec![Sum::default()]; 680 for _ in 0..16 { 681 let pi = rng.below(nodes.len() as u64) as usize; 682 if nodes[pi].0.links.len() >= MAX_CHAIN_DEPTH { 683 continue; 684 } 685 let parent = nodes[pi].0.leaf().unwrap().clone(); 686 let pq = parent.caveats.quotas; 687 let mut cav = parent.caveats.clone(); 688 cav.quotas.max_ops_per_window = rng.upto(u64::from(pq.max_ops_per_window)) as u32; 689 cav.quotas.storage_bytes = rng.upto(pq.storage_bytes); 690 cav.quotas.footprint_paths = rng.upto(pq.footprint_paths); 691 let audience = rng.key(); 692 let child = CapabilityLink::issue( 693 &nodes[pi].1, 694 parent.digest(), 695 rng.bytes32(), 696 repo(), 697 pubkey(&audience), 698 cav.clone(), 699 ); 700 let chain = nodes[pi].0.extended(child); 701 let s = children_sum[pi]; 702 let next = Sum { 703 ops: s.ops + u64::from(cav.quotas.max_ops_per_window), 704 storage: s.storage + cav.quotas.storage_bytes, 705 footprint: s.footprint + cav.quotas.footprint_paths, 706 }; 707 let fits = next.ops <= u64::from(pq.max_ops_per_window) 708 && next.storage <= pq.storage_bytes 709 && next.footprint <= pq.footprint_paths; 710 seq += 1; 711 let got = enforcer 712 .grant_link(&chain, WalSeq(seq), NOW) 713 .map_err(|e| e.code); 714 match got { 715 Ok(_) => { 716 // The property: what the server accepted keeps the children's sum within 717 // the parent's rate, storage, and footprint quotas. 718 assert!( 719 fits, 720 "seed {PROPERTY_SEED:#x} case {case}: accepted child makes children sum \ 721 {next:?} above parent quotas {pq:?}" 722 ); 723 children_sum[pi] = next; 724 children_sum.push(Sum::default()); 725 nodes.push((chain, audience)); 726 accepted += 1; 727 } 728 Err(code) => { 729 assert!( 730 !fits, 731 "seed {PROPERTY_SEED:#x} case {case}: child that fits refused with \ 732 {code:?} (sum {next:?}, parent {pq:?})" 733 ); 734 assert_eq!( 735 code, 736 RefusalCode::QuotaPartitionExceeded, 737 "seed {PROPERTY_SEED:#x} case {case}" 738 ); 739 refused += 1; 740 } 741 } 742 } 743 // What each granted link keeps for itself is its quota minus what it handed down. 744 for (i, (chain, _)) in nodes.iter().enumerate() { 745 let leaf = chain.leaf().unwrap(); 746 let q = leaf.caveats.quotas; 747 let own = enforcer.unallocated_quota(&leaf.digest()); 748 let expect = ChainQuotas { 749 max_ops_per_window: q.max_ops_per_window - children_sum[i].ops as u32, 750 storage_bytes: q.storage_bytes - children_sum[i].storage, 751 footprint_paths: q.footprint_paths - children_sum[i].footprint, 752 ..q 753 }; 754 assert_eq!( 755 own, 756 Some(expect), 757 "seed {PROPERTY_SEED:#x} case {case} node {i}" 758 ); 759 } 760 } 761 println!( 762 "seed {PROPERTY_SEED:#x}, {PARTITION_CASES} cases: {accepted} children accepted, \ 763 {refused} refused with QuotaPartitionExceeded" 764 ); 765 assert!(accepted > 0 && refused > 0); 766 } 767 768 #[test] 769 fn f1_partitioned_rate_parent_keeps_only_what_it_has_not_handed_down() { 770 let mut fx = Fx::new(); 771 // mid (500 ops) handed 250 to leaf; a second child asking 251 does not fit. 772 let mut cav = fx.mid.caveats.clone(); 773 cav.quotas.max_ops_per_window = 251; 774 cav.quotas.storage_bytes = 0; 775 cav.quotas.footprint_paths = 0; 776 let extra = CapabilityLink::issue(&fx.w, fx.mid.digest(), [0xB0; 32], repo(), [9u8; 32], cav); 777 let chain = fx.chain(&[&fx.root, &fx.mid, &extra]); 778 assert_eq!( 779 fx.enforcer 780 .grant_link(&chain, WalSeq(4), NOW) 781 .map_err(|e| e.code), 782 Err(RefusalCode::QuotaPartitionExceeded) 783 ); 784 let own = fx.enforcer.unallocated_quota(&fx.mid.digest()).unwrap(); 785 assert_eq!(own.max_ops_per_window, 250); 786 787 // A link whose rate is fully handed down cannot make requests itself. 788 let mut cav = fx.leaf.caveats.clone(); 789 cav.quotas.max_ops_per_window = 1; 790 cav.quotas.storage_bytes = 0; 791 cav.quotas.footprint_paths = 0; 792 let sub_key = SigningKey::from_bytes(&[5u8; 32]); 793 let sub = CapabilityLink::issue( 794 &fx.s, 795 fx.leaf.digest(), 796 [0xB1; 32], 797 repo(), 798 pubkey(&sub_key), 799 cav, 800 ); 801 // Shrink the leaf's own allowance to zero by handing all 250 to children. 802 let mut big = fx.leaf.caveats.clone(); 803 big.quotas.max_ops_per_window = 249; 804 big.quotas.storage_bytes = 0; 805 big.quotas.footprint_paths = 0; 806 let other = CapabilityLink::issue(&fx.s, fx.leaf.digest(), [0xB2; 32], repo(), [8u8; 32], big); 807 let full = fx.full_chain(); 808 fx.enforcer 809 .grant_link(&full.extended(sub.clone()), WalSeq(5), NOW) 810 .unwrap(); 811 fx.enforcer 812 .grant_link(&full.extended(other), WalSeq(6), NOW) 813 .unwrap(); 814 assert_eq!( 815 fx.enforcer 816 .unallocated_quota(&fx.leaf.digest()) 817 .unwrap() 818 .max_ops_per_window, 819 0 820 ); 821 let req = fx.request(&fx.s.clone(), full.clone(), Capability::Read, in_scope(), 1); 822 assert_eq!( 823 fx.authorize(&req, 7), 824 Err(RefusalCode::QuotaRateLimitExceeded) 825 ); 826 827 // The child with one op gets exactly one request in the window. 828 let sub_chain = full.extended(sub); 829 let r1 = fx.request(&sub_key, sub_chain.clone(), Capability::Read, in_scope(), 2); 830 assert_eq!(fx.authorize(&r1, 8), Ok(())); 831 let r2 = fx.request(&sub_key, sub_chain, Capability::Read, in_scope(), 3); 832 assert_eq!( 833 fx.authorize(&r2, 9), 834 Err(RefusalCode::QuotaRateLimitExceeded) 835 ); 836 } 837 838 // --------------------------------------------------------------------------------------------- 839 // Forged, stripped, and reordered chains; links bound to another repository or audience. 840 // --------------------------------------------------------------------------------------------- 841 842 #[test] 843 fn f1_forged_chains_are_refused() { 844 let mut fx = Fx::new(); 845 // Positive control: the genuine chain is admitted and audited. 846 let ok = fx.request( 847 &fx.s.clone(), 848 fx.full_chain(), 849 Capability::Propose, 850 in_scope(), 851 1, 852 ); 853 assert_eq!(fx.authorize(&ok, 4), Ok(())); 854 let last = fx.enforcer.audit_log().entries().last().cloned(); 855 assert_eq!(last.map(|e| e.outcome), Some(AuditOutcome::Admitted)); 856 857 // A link whose caveats were widened after signing. 858 let mut mid_forged = fx.mid.clone(); 859 mid_forged.caveats.paths = PathScope::whole_repository(); 860 let chain = fx.chain(&[&fx.root, &mid_forged, &fx.leaf]); 861 let req = fx.request( 862 &fx.s.clone(), 863 chain.clone(), 864 Capability::Propose, 865 in_scope(), 866 2, 867 ); 868 assert_eq!( 869 fx.authorize(&req, 4), 870 Err(RefusalCode::AuthGrantSignatureInvalid) 871 ); 872 assert_eq!( 873 fx.enforcer 874 .grant_link(&fx.chain(&[&fx.root, &mid_forged]), WalSeq(4), NOW) 875 .map_err(|e| e.code), 876 Err(RefusalCode::AuthGrantSignatureInvalid) 877 ); 878 879 // A link with signature bytes that were never produced by its issuer. 880 let mut leaf_forged = fx.leaf.clone(); 881 leaf_forged.signature = [0x5A; 64]; 882 let chain = fx.chain(&[&fx.root, &fx.mid, &leaf_forged]); 883 let req = fx.request(&fx.s.clone(), chain, Capability::Propose, in_scope(), 3); 884 assert_eq!( 885 fx.authorize(&req, 4), 886 Err(RefusalCode::AuthGrantSignatureInvalid) 887 ); 888 889 // A leaf whose audience was swapped to the attacker, presented by the attacker. 890 let attacker = SigningKey::from_bytes(&[66u8; 32]); 891 let mut leaf_stolen = fx.leaf.clone(); 892 leaf_stolen.audience_key = pubkey(&attacker); 893 let chain = fx.chain(&[&fx.root, &fx.mid, &leaf_stolen]); 894 let req = fx.request(&attacker, chain, Capability::Propose, in_scope(), 4); 895 assert_eq!( 896 fx.authorize(&req, 4), 897 Err(RefusalCode::AuthGrantSignatureInvalid) 898 ); 899 900 // A root the attacker signed for itself (not a trusted repository authority). 901 let fake_root = CapabilityLink::issue( 902 &attacker, 903 ROOT_PARENT, 904 [0xEE; 32], 905 repo(), 906 pubkey(&attacker), 907 wide_caveats(), 908 ); 909 let chain = CapabilityChain::new(vec![fake_root]); 910 let req = fx.request(&attacker, chain.clone(), Capability::Propose, in_scope(), 5); 911 assert_eq!( 912 fx.authorize(&req, 4), 913 Err(RefusalCode::AuthGrantSignatureInvalid) 914 ); 915 assert_eq!( 916 fx.enforcer 917 .grant_link(&chain, WalSeq(4), NOW) 918 .map_err(|e| e.code), 919 Err(RefusalCode::AuthGrantSignatureInvalid) 920 ); 921 } 922 923 #[test] 924 fn f1_stripped_chains_are_refused() { 925 let mut fx = Fx::new(); 926 let ok = fx.request( 927 &fx.s.clone(), 928 fx.full_chain(), 929 Capability::Read, 930 in_scope(), 931 1, 932 ); 933 assert_eq!(fx.authorize(&ok, 4), Ok(())); 934 let cases: Vec<(&str, CapabilityChain)> = vec![ 935 ("middle link dropped", fx.chain(&[&fx.root, &fx.leaf])), 936 ("root dropped", fx.chain(&[&fx.mid, &fx.leaf])), 937 ("only the leaf", fx.chain(&[&fx.leaf])), 938 ("empty chain", CapabilityChain::new(Vec::new())), 939 ]; 940 for (i, (what, chain)) in cases.into_iter().enumerate() { 941 let req = fx.request( 942 &fx.s.clone(), 943 chain, 944 Capability::Read, 945 in_scope(), 946 10 + i as u8, 947 ); 948 assert_eq!( 949 fx.authorize(&req, 4), 950 Err(RefusalCode::AuthChainBroken), 951 "{what}" 952 ); 953 } 954 } 955 956 #[test] 957 fn f1_reordered_chains_are_refused() { 958 let mut fx = Fx::new(); 959 let links = [fx.root.clone(), fx.mid.clone(), fx.leaf.clone()]; 960 let orders = [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]; 961 let ok = fx.request( 962 &fx.s.clone(), 963 fx.full_chain(), 964 Capability::Read, 965 in_scope(), 966 1, 967 ); 968 assert_eq!(fx.authorize(&ok, 4), Ok(())); 969 for (i, order) in orders.iter().enumerate() { 970 let chain = CapabilityChain::new(order.iter().map(|&j| links[j].clone()).collect()); 971 let req = fx.request( 972 &fx.s.clone(), 973 chain, 974 Capability::Read, 975 in_scope(), 976 10 + i as u8, 977 ); 978 assert_eq!( 979 fx.authorize(&req, 4), 980 Err(RefusalCode::AuthChainBroken), 981 "order {order:?}" 982 ); 983 } 984 } 985 986 #[test] 987 fn f1_link_bound_to_another_repository_is_refused() { 988 let mut fx = Fx::new(); 989 let other = RepoId::new("aien-spark/aien-sovereign-core").unwrap(); 990 fx.enforcer.register_repo_authority( 991 other.clone(), 992 encode_did_key_`ed25519`(&pubkey(&fx.authority)), 993 ); 994 995 // A properly signed leaf bound to another repository, spliced under this repository's chain. 996 let leaf_other = CapabilityLink::issue( 997 &fx.w, 998 fx.mid.digest(), 999 [0xC0; 32], 1000 other.clone(), 1001 pubkey(&fx.s), 1002 fx.leaf.caveats.clone(), 1003 ); 1004 let chain = fx.chain(&[&fx.root, &fx.mid, &leaf_other]); 1005 assert_eq!( 1006 fx.enforcer 1007 .grant_link(&chain, WalSeq(4), NOW) 1008 .map_err(|e| e.code), 1009 Err(RefusalCode::AuthCrossRepoDenied) 1010 ); 1011 let req = fx.request(&fx.s.clone(), chain, Capability::Read, in_scope(), 1); 1012 assert_eq!(fx.authorize(&req, 4), Err(RefusalCode::AuthCrossRepoDenied)); 1013 1014 // This repository's whole chain presented to another repository. 1015 let req = ChainedRequest::sign_new( 1016 &fx.s, 1017 fx.full_chain(), 1018 other.clone(), 1019 Capability::Read, 1020 in_scope(), 1021 [2u8; 32], 1022 NOW, 1023 Vec::new(), 1024 ); 1025 let got = fx 1026 .enforcer 1027 .authorize_chain( 1028 BoundaryKind::Api, 1029 "read", 1030 &other, 1031 Capability::Read, 1032 &req, 1033 WalSeq(4), 1034 NOW, 1035 ) 1036 .map_err(|e| e.code); 1037 assert_eq!(got, Err(RefusalCode::AuthCrossRepoDenied)); 1038 } 1039 1040 #[test] 1041 fn f1_link_bound_to_another_audience_is_refused() { 1042 let mut fx = Fx::new(); 1043 let x = SigningKey::from_bytes(&[77u8; 32]); 1044 1045 // The chain names S as its audience; X presents it with X's own valid signature. 1046 let req = fx.request(&x, fx.full_chain(), Capability::Read, in_scope(), 1); 1047 assert_eq!( 1048 fx.authorize(&req, 4), 1049 Err(RefusalCode::AuthAudienceMismatch) 1050 ); 1051 1052 // X signs a child under mid, but mid is bound to audience W, so X cannot extend it. 1053 let rogue = CapabilityLink::issue( 1054 &x, 1055 fx.mid.digest(), 1056 [0xD0; 32], 1057 repo(), 1058 pubkey(&x), 1059 fx.leaf.caveats.clone(), 1060 ); 1061 let chain = fx.chain(&[&fx.root, &fx.mid, &rogue]); 1062 assert_eq!( 1063 fx.enforcer 1064 .grant_link(&chain, WalSeq(4), NOW) 1065 .map_err(|e| e.code), 1066 Err(RefusalCode::AuthAudienceMismatch) 1067 ); 1068 let req = fx.request(&x, chain, Capability::Read, in_scope(), 2); 1069 assert_eq!( 1070 fx.authorize(&req, 4), 1071 Err(RefusalCode::AuthAudienceMismatch) 1072 ); 1073 1074 // A request that claims S as presenter but was signed by X. 1075 let mut req = fx.request(&x, fx.full_chain(), Capability::Read, in_scope(), 3); 1076 req.agent_key = pubkey(&fx.s); 1077 assert_eq!( 1078 fx.authorize(&req, 4), 1079 Err(RefusalCode::AuthSignatureInvalid) 1080 ); 1081 1082 // An ancestor's holder (W) cannot present the leaf bound to S. 1083 let req = fx.request( 1084 &fx.w.clone(), 1085 fx.full_chain(), 1086 Capability::Read, 1087 in_scope(), 1088 4, 1089 ); 1090 assert_eq!( 1091 fx.authorize(&req, 4), 1092 Err(RefusalCode::AuthAudienceMismatch) 1093 ); 1094 1095 let ok = fx.request( 1096 &fx.s.clone(), 1097 fx.full_chain(), 1098 Capability::Read, 1099 in_scope(), 1100 5, 1101 ); 1102 assert_eq!(fx.authorize(&ok, 4), Ok(())); 1103 } 1104 1105 // --------------------------------------------------------------------------------------------- 1106 // Scope at request time and revocation at the request's WalSeq. 1107 // --------------------------------------------------------------------------------------------- 1108 1109 #[test] 1110 fn f1_out_of_scope_path_is_refused() { 1111 let mut fx = Fx::new(); 1112 let s = fx.s.clone(); 1113 let chain = fx.full_chain(); 1114 let mut nonce = 0u8; 1115 let mut run = |fx: &mut Fx, scope: RequestScope| { 1116 nonce += 1; 1117 let req = fx.request(&s, chain.clone(), Capability::Propose, scope, nonce); 1118 fx.authorize(&req, 4) 1119 }; 1120 assert_eq!(run(&mut fx, in_scope()), Ok(())); 1121 assert_eq!( 1122 run(&mut fx, paths(&["crates/synapse-core/src/lib.rs"])), 1123 Err(RefusalCode::AuthPathOutOfScope) 1124 ); 1125 // Prefixes match whole segments: `crates/synapse-auth` does not cover `crates/synapse-authz`. 1126 assert_eq!( 1127 run(&mut fx, paths(&["crates/synapse-authz/src/lib.rs"])), 1128 Err(RefusalCode::AuthPathOutOfScope) 1129 ); 1130 // `docs` is in the parent's scope but not the leaf's. 1131 assert_eq!( 1132 run( 1133 &mut fx, 1134 paths(&["crates/synapse-auth/src/lib.rs", "docs/F1.md"]) 1135 ), 1136 Err(RefusalCode::AuthPathOutOfScope) 1137 ); 1138 assert_eq!( 1139 run( 1140 &mut fx, 1141 paths(&["crates/synapse-auth/../synapse-core/src/lib.rs"]) 1142 ), 1143 Err(RefusalCode::PathInvalid) 1144 ); 1145 let with_ref = |k| RequestScope { 1146 reference: Some(k), 1147 ..in_scope() 1148 }; 1149 assert_eq!(run(&mut fx, with_ref(ReferenceKind::OwnDrafts)), Ok(())); 1150 assert_eq!( 1151 run(&mut fx, with_ref(ReferenceKind::CanonicalViaPromotionQueue)), 1152 Err(RefusalCode::AuthReferenceOutOfScope) 1153 ); 1154 let with_change = |id| RequestScope { 1155 join_change: Some(id), 1156 ..in_scope() 1157 }; 1158 assert_eq!(run(&mut fx, with_change(change_id(1))), Ok(())); 1159 assert_eq!( 1160 run(&mut fx, with_change(change_id(2))), 1161 Err(RefusalCode::AuthChangeOutOfScope) 1162 ); 1163 } 1164 1165 #[test] 1166 fn f1_chain_with_an_ancestor_revoked_at_the_request_walseq_is_refused() { 1167 let mut fx = Fx::new(); 1168 let s = fx.s.clone(); 1169 let chain = fx.full_chain(); 1170 let mut nonce = 0u8; 1171 let mut at = |fx: &mut Fx, seq: u64| { 1172 nonce += 1; 1173 let req = fx.request(&s, chain.clone(), Capability::Propose, in_scope(), nonce); 1174 fx.authorize(&req, seq) 1175 }; 1176 assert_eq!(at(&mut fx, 9), Ok(())); 1177 1178 fx.enforcer 1179 .revoke_link(fx.mid.digest(), WalSeq(10)) 1180 .unwrap(); 1181 // Revocation applies from its own WalSeq on, not before. 1182 assert_eq!(at(&mut fx, 9), Ok(())); 1183 assert_eq!(at(&mut fx, 10), Err(RefusalCode::AuthGrantRevoked)); 1184 assert_eq!(at(&mut fx, 11), Err(RefusalCode::AuthGrantRevoked)); 1185 1186 // A later revocation never moves the first one, so revocation cannot be undone that way. 1187 fx.enforcer 1188 .revoke_link(fx.mid.digest(), WalSeq(20)) 1189 .unwrap(); 1190 assert_eq!(at(&mut fx, 15), Err(RefusalCode::AuthGrantRevoked)); 1191 1192 // No new child can be granted under the revoked ancestor. 1193 let mut cav = fx.leaf.caveats.clone(); 1194 cav.quotas.max_ops_per_window = 0; 1195 cav.quotas.storage_bytes = 0; 1196 cav.quotas.footprint_paths = 0; 1197 let late = CapabilityLink::issue(&fx.w, fx.mid.digest(), [0xF0; 32], repo(), [7u8; 32], cav); 1198 assert_eq!( 1199 fx.enforcer 1200 .grant_link(&fx.chain(&[&fx.root, &fx.mid, &late]), WalSeq(12), NOW) 1201 .map_err(|e| e.code), 1202 Err(RefusalCode::AuthGrantRevoked) 1203 ); 1204 1205 // Revoking the root refuses even a chain of the root alone held by O. 1206 fx.enforcer 1207 .revoke_link(fx.root.digest(), WalSeq(30)) 1208 .unwrap(); 1209 let req = fx.request( 1210 &fx.o.clone(), 1211 fx.chain(&[&fx.root]), 1212 Capability::Read, 1213 in_scope(), 1214 200, 1215 ); 1216 assert_eq!(fx.authorize(&req, 30), Err(RefusalCode::AuthGrantRevoked)); 1217 1218 // The leaf is granted at WalSeq 3: a request at WalSeq 2 predates it (no link is revoked 1219 // at WalSeq 2, so this refusal is about the grant, not the revocations above). 1220 assert_eq!(at(&mut fx, 2), Err(RefusalCode::AuthChainBroken)); 1221 } 1222 1223 // --------------------------------------------------------------------------------------------- 1224 // Binary encoding (ADR 0003 principle P5). 1225 // --------------------------------------------------------------------------------------------- 1226 1227 #[test] 1228 fn f1_link_and_chain_binary_encoding_is_canonical_and_malformed_bytes_are_refused() { 1229 let fx = Fx::new(); 1230 let leaf = fx.leaf.clone(); 1231 let bytes = leaf.encode(); 1232 // Documented layout: version u16 LE, nonce, parent digest, repo (u32 LE length + bytes). 1233 assert_eq!(&bytes[0..2], &1u16.to_le_bytes()); 1234 assert_eq!(&bytes[2..34], &leaf.nonce); 1235 assert_eq!(&bytes[34..66], &fx.mid.digest().0); 1236 let repo_len = repo().as_str().len(); 1237 assert_eq!(&bytes[66..70], &(repo_len as u32).to_le_bytes()); 1238 assert_eq!(&bytes[bytes.len() - 64..], &leaf.signature); 1239 1240 let back = CapabilityLink::decode(&bytes).map_err(|e| e.code); 1241 assert_eq!(back.as_ref(), Ok(&leaf)); 1242 assert_eq!(back.unwrap().encode(), bytes); 1243 1244 let chain = fx.full_chain(); 1245 let chain_bytes = chain.encode(); 1246 let chain_back = CapabilityChain::decode(&chain_bytes).map_err(|e| e.code); 1247 assert_eq!(chain_back.as_ref(), Ok(&chain)); 1248 assert_eq!(chain_back.unwrap().encode(), chain_bytes); 1249 assert_eq!( 1250 chain.link_digests(), 1251 vec![fx.root.digest(), fx.mid.digest(), leaf.digest()] 1252 ); 1253 1254 let malformed = |b: &[u8]| CapabilityChain::decode(b).map_err(|e| e.code); 1255 for cut in 0..chain_bytes.len() { 1256 assert_eq!( 1257 malformed(&chain_bytes[..cut]), 1258 Err(RefusalCode::AuthChainMalformed), 1259 "truncated at {cut}" 1260 ); 1261 } 1262 let mut trailing = chain_bytes.clone(); 1263 trailing.push(0); 1264 assert_eq!(malformed(&trailing), Err(RefusalCode::AuthChainMalformed)); 1265 let mut v2 = chain_bytes.clone(); 1266 v2[0] = 2; 1267 assert_eq!(malformed(&v2), Err(RefusalCode::AuthChainMalformed)); 1268 for count in [0u8, (MAX_CHAIN_DEPTH + 1) as u8] { 1269 let mut c = chain_bytes.clone(); 1270 c[2] = count; 1271 assert_eq!(malformed(&c), Err(RefusalCode::AuthChainMalformed)); 1272 } 1273 1274 let link_err = |b: &[u8]| CapabilityLink::decode(b).map_err(|e| e.code); 1275 let ops_at = 2 + 32 + 32 + 4 + repo_len + 32 + 32; 1276 let mut bad_ops = bytes.clone(); 1277 bad_ops[ops_at] |= 0x40; 1278 assert_eq!(link_err(&bad_ops), Err(RefusalCode::AuthChainMalformed)); 1279 let mut bad_refs = bytes.clone(); 1280 bad_refs[ops_at + 1] |= 0x04; 1281 assert_eq!(link_err(&bad_refs), Err(RefusalCode::AuthChainMalformed)); 1282 let mut huge_paths = bytes.clone(); 1283 huge_paths[ops_at + 2..ops_at + 6].copy_from_slice(&u32::MAX.to_le_bytes()); 1284 assert_eq!(link_err(&huge_paths), Err(RefusalCode::AuthChainMalformed)); 1285 1286 // Path prefixes out of order are not the canonical form. 1287 let mut cav = wide_caveats(); 1288 cav.paths = PathScope::new(vec!["a".into(), "b".into()]).unwrap(); 1289 let two = CapabilityLink::issue(&fx.authority, ROOT_PARENT, [1; 32], repo(), [2; 32], cav); 1290 let mut swapped = two.encode(); 1291 let first = ops_at + 2 + 4 + 4; 1292 let second = first + 1 + 4; 1293 assert_eq!((swapped[first], swapped[second]), (b'a', b'b')); 1294 swapped.swap(first, second); 1295 assert_eq!(link_err(&swapped), Err(RefusalCode::AuthChainMalformed)); 1296 // Unknown change-scope tag. 1297 let mut bad_change = two.encode(); 1298 bad_change[second + 1] = 2; 1299 assert_eq!(link_err(&bad_change), Err(RefusalCode::AuthChainMalformed)); 1300 1301 // Every link digest differs once any signed byte differs. 1302 let d: LinkDigest = fx.leaf.digest(); 1303 let mut other = fx.leaf.clone(); 1304 other.caveats.expires_at_ms -= 1; 1305 assert_ne!(other.digest(), d); 1306 }