api_leakage.rs (54351B)
1 use std::{ 2 collections::{BTreeMap, BTreeSet}, 3 fs, 4 path::{Component, Path, PathBuf}, 5 process::Command, 6 }; 7 8 use serde::Deserialize; 9 use syn::{ 10 Expr, ExprLit, Fields, ForeignItem, ImplItem, Item, Lit, Meta, Path as SynPath, TraitItem, 11 Type, UseTree, Visibility, visit::Visit, 12 }; 13 14 const API_BOUNDARIES_RELATIVE: &str = "contracts/releases/api_boundaries.toml"; 15 const API_DECISION_RELATIVE: &str = 16 "contracts/architecture/decisions/public_api_leakage_migration_baseline.v1.toml"; 17 const API_DECISION_ID: &str = "radroots.public_api_leakage_migration_baseline.v1"; 18 const SPEC_ID: &str = "radroots.crates.release.v2"; 19 const POLICY_SCHEMA_VERSION: u16 = 1; 20 const DECISION_SCHEMA_VERSION: u16 = 1; 21 const CURRENT_STEP: u16 = 313; 22 const HISTORICAL_EXCEPTION_IDS: [&str; 8] = [ 23 "RCRV1-API-001", 24 "RCRV1-API-002", 25 "RCRV1-API-003", 26 "RCRV1-API-004", 27 "RCRV1-API-005", 28 "RCRV1-API-006", 29 "RCRV1-API-007", 30 "RCRV1-API-008", 31 ]; 32 const FORBIDDEN_EXPANSION: [&str; 8] = [ 33 "broader_aliases", 34 "keyring", 35 "new_items", 36 "new_upstream_paths", 37 "platform_specific_types", 38 "reqwest", 39 "sqlx", 40 "tokio", 41 ]; 42 const REMOVAL_MILESTONES: [(&str, u16); 3] = [ 43 ("radroots_identity", 42), 44 ("radroots_nostr", 124), 45 ("radroots_nostr_connect", 140), 46 ]; 47 48 #[derive(Debug, Deserialize)] 49 #[serde(deny_unknown_fields)] 50 struct ApiBoundaryPolicy { 51 schema_version: u16, 52 spec_id: String, 53 forbidden_public_paths: Vec<String>, 54 package: Vec<ApiPackagePolicy>, 55 #[serde(default)] 56 exception: Vec<ApiException>, 57 } 58 59 #[derive(Debug, Deserialize)] 60 #[serde(deny_unknown_fields)] 61 struct ApiPackagePolicy { 62 name: String, 63 allowed_public_paths: Vec<String>, 64 } 65 66 #[derive(Debug, Deserialize)] 67 #[serde(deny_unknown_fields)] 68 struct ApiException { 69 id: String, 70 package: String, 71 source: String, 72 forbidden_path: String, 73 items: Vec<String>, 74 observed_paths: Vec<String>, 75 decision: String, 76 removal_step: u16, 77 rationale: String, 78 } 79 80 #[derive(Debug, Deserialize)] 81 #[serde(deny_unknown_fields)] 82 struct ApiLeakageDecision { 83 schema_version: u16, 84 decision_id: String, 85 status: String, 86 accepted_date: String, 87 completed_step: u16, 88 publication_authorized: bool, 89 exception_ids: Vec<String>, 90 active_exception_ids: Vec<String>, 91 forbidden_expansion: Vec<String>, 92 removal_milestone: Vec<ApiRemovalMilestone>, 93 } 94 95 #[derive(Debug, Deserialize)] 96 #[serde(deny_unknown_fields)] 97 struct ApiRemovalMilestone { 98 package: String, 99 step: u16, 100 } 101 102 #[derive(Debug, Deserialize)] 103 struct CargoMetadata { 104 packages: Vec<CargoPackage>, 105 workspace_members: Vec<String>, 106 } 107 108 #[derive(Debug, Deserialize)] 109 struct CargoPackage { 110 id: String, 111 name: String, 112 manifest_path: String, 113 targets: Vec<CargoTarget>, 114 } 115 116 #[derive(Debug, Deserialize)] 117 struct CargoTarget { 118 kind: Vec<String>, 119 src_path: String, 120 } 121 122 struct ModuleUnit { 123 module: Vec<String>, 124 parent: Option<Vec<String>>, 125 declared_public: bool, 126 initially_effective: bool, 127 source_relative: String, 128 items: Vec<Item>, 129 } 130 131 #[derive(Debug, Clone, Eq, Ord, PartialEq, PartialOrd)] 132 struct ApiFinding { 133 package: String, 134 source: String, 135 item: String, 136 forbidden_path: String, 137 observed_path: String, 138 } 139 140 #[derive(Debug)] 141 enum InternalExport { 142 Module(Vec<String>), 143 Item(Vec<String>, String), 144 External, 145 } 146 147 pub(super) fn validate_policy_catalog( 148 workspace_root: &Path, 149 expected_packages: &BTreeSet<String>, 150 ) -> Result<(), String> { 151 let policy = load_policy(workspace_root)?; 152 validate_policy(workspace_root, &policy, expected_packages) 153 } 154 155 pub(super) fn validate_public_api(workspace_root: &Path) -> Result<(), String> { 156 let policy = load_policy(workspace_root)?; 157 let expected_packages = policy 158 .package 159 .iter() 160 .map(|package| package.name.clone()) 161 .collect::<BTreeSet<_>>(); 162 validate_policy(workspace_root, &policy, &expected_packages)?; 163 let metadata = load_metadata(workspace_root)?; 164 let findings = scan_workspace(workspace_root, &policy, &metadata)?; 165 let unapproved = findings 166 .into_iter() 167 .filter(|finding| !exception_matches(&policy.exception, finding)) 168 .collect::<Vec<_>>(); 169 if unapproved.is_empty() { 170 Ok(()) 171 } else { 172 Err(format!( 173 "forbidden public implementation type leakage:\n{}", 174 unapproved 175 .iter() 176 .map(format_finding) 177 .collect::<Vec<_>>() 178 .join("\n") 179 )) 180 } 181 } 182 183 fn load_policy(workspace_root: &Path) -> Result<ApiBoundaryPolicy, String> { 184 let path = workspace_root.join(API_BOUNDARIES_RELATIVE); 185 let raw = 186 fs::read_to_string(&path).map_err(|error| format!("read {}: {error}", path.display()))?; 187 toml::from_str(&raw).map_err(|error| format!("parse {}: {error}", path.display())) 188 } 189 190 fn validate_policy( 191 workspace_root: &Path, 192 policy: &ApiBoundaryPolicy, 193 expected_packages: &BTreeSet<String>, 194 ) -> Result<(), String> { 195 if policy.schema_version != POLICY_SCHEMA_VERSION { 196 return Err(format!( 197 "{API_BOUNDARIES_RELATIVE} schema_version must be {POLICY_SCHEMA_VERSION}" 198 )); 199 } 200 if policy.spec_id != SPEC_ID { 201 return Err(format!( 202 "{API_BOUNDARIES_RELATIVE} spec_id must be {SPEC_ID}" 203 )); 204 } 205 let decision = load_and_validate_decision(workspace_root)?; 206 207 let forbidden = sorted_unique( 208 "forbidden_public_paths", 209 &policy.forbidden_public_paths, 210 false, 211 )?; 212 if forbidden.len() != policy.forbidden_public_paths.len() { 213 return Err(format!( 214 "{API_BOUNDARIES_RELATIVE} forbidden_public_paths must be unique" 215 )); 216 } 217 for required in [ 218 "keyring", 219 "nostr_sdk", 220 "reqwest", 221 "sqlx", 222 "std::os", 223 "tokio", 224 ] { 225 if !forbidden.contains(required) { 226 return Err(format!( 227 "{API_BOUNDARIES_RELATIVE} must forbid public {required} paths" 228 )); 229 } 230 } 231 232 let mut package_names = BTreeSet::new(); 233 for package in &policy.package { 234 if !package_names.insert(package.name.as_str()) { 235 return Err(format!( 236 "{API_BOUNDARIES_RELATIVE} package {} is declared more than once", 237 package.name 238 )); 239 } 240 let allowed = sorted_unique( 241 &format!("package {} allowed_public_paths", package.name), 242 &package.allowed_public_paths, 243 true, 244 )?; 245 for path in allowed { 246 if !forbidden.contains(path) { 247 return Err(format!( 248 "{API_BOUNDARIES_RELATIVE} package {} allows {path}, which is not forbidden globally", 249 package.name 250 )); 251 } 252 } 253 } 254 let actual_packages = package_names 255 .into_iter() 256 .map(str::to_owned) 257 .collect::<BTreeSet<_>>(); 258 if &actual_packages != expected_packages { 259 return Err(package_set_mismatch(expected_packages, &actual_packages)); 260 } 261 262 let package_policy = policy 263 .package 264 .iter() 265 .map(|package| (package.name.as_str(), package)) 266 .collect::<BTreeMap<_, _>>(); 267 let mut exception_ids = BTreeSet::new(); 268 let mut exception_keys = BTreeSet::new(); 269 for exception in &policy.exception { 270 if !exception_ids.insert(exception.id.as_str()) { 271 return Err(format!( 272 "{API_BOUNDARIES_RELATIVE} exception id {} is duplicated", 273 exception.id 274 )); 275 } 276 if !valid_exception_id(&exception.id) { 277 return Err(format!( 278 "{API_BOUNDARIES_RELATIVE} exception id {} must match RCRV1-API-NNN", 279 exception.id 280 )); 281 } 282 let package = package_policy 283 .get(exception.package.as_str()) 284 .ok_or_else(|| { 285 format!( 286 "{API_BOUNDARIES_RELATIVE} exception {} names unknown package {}", 287 exception.id, exception.package 288 ) 289 })?; 290 if !forbidden.contains(exception.forbidden_path.as_str()) { 291 return Err(format!( 292 "{API_BOUNDARIES_RELATIVE} exception {} names unknown forbidden path {}", 293 exception.id, exception.forbidden_path 294 )); 295 } 296 if package 297 .allowed_public_paths 298 .iter() 299 .any(|allowed| allowed == &exception.forbidden_path) 300 { 301 return Err(format!( 302 "{API_BOUNDARIES_RELATIVE} exception {} is redundant with package allowance {}", 303 exception.id, exception.forbidden_path 304 )); 305 } 306 validate_relative_source(&exception.id, &exception.source)?; 307 let items = sorted_unique( 308 &format!("exception {} items", exception.id), 309 &exception.items, 310 false, 311 )?; 312 if items.len() != exception.items.len() { 313 return Err(format!( 314 "{API_BOUNDARIES_RELATIVE} exception {} items must be unique", 315 exception.id 316 )); 317 } 318 let observed_paths = sorted_unique( 319 &format!("exception {} observed_paths", exception.id), 320 &exception.observed_paths, 321 false, 322 )?; 323 if observed_paths.len() != exception.observed_paths.len() 324 || observed_paths.iter().any(|path| { 325 !(path == &exception.forbidden_path 326 || path 327 .strip_prefix(&exception.forbidden_path) 328 .is_some_and(|suffix| suffix.starts_with("::"))) 329 }) 330 { 331 return Err(format!( 332 "{API_BOUNDARIES_RELATIVE} exception {} observed_paths must be sorted, unique, and rooted at {}", 333 exception.id, exception.forbidden_path 334 )); 335 } 336 if exception.removal_step <= CURRENT_STEP { 337 return Err(format!( 338 "{API_BOUNDARIES_RELATIVE} exception {} expired at Step {}", 339 exception.id, exception.removal_step 340 )); 341 } 342 if exception.rationale.trim().is_empty() { 343 return Err(format!( 344 "{API_BOUNDARIES_RELATIVE} exception {} must include a rationale", 345 exception.id 346 )); 347 } 348 validate_decision_reference(exception, &decision)?; 349 for item in &exception.items { 350 let key = ( 351 exception.package.as_str(), 352 exception.source.as_str(), 353 item.as_str(), 354 exception.forbidden_path.as_str(), 355 ); 356 if !exception_keys.insert(key) { 357 return Err(format!( 358 "{API_BOUNDARIES_RELATIVE} exception {} duplicates an item-scoped allowance", 359 exception.id 360 )); 361 } 362 } 363 } 364 let active_exception_ids = decision 365 .active_exception_ids 366 .iter() 367 .map(String::as_str) 368 .collect::<BTreeSet<_>>(); 369 if exception_ids != active_exception_ids { 370 return Err(format!( 371 "{API_BOUNDARIES_RELATIVE} active exception ids must exactly match {API_DECISION_RELATIVE}" 372 )); 373 } 374 Ok(()) 375 } 376 377 fn sorted_unique<'a>( 378 label: &str, 379 values: &'a [String], 380 allow_empty: bool, 381 ) -> Result<BTreeSet<&'a str>, String> { 382 if !allow_empty && values.is_empty() { 383 return Err(format!( 384 "{API_BOUNDARIES_RELATIVE} {label} must not be empty" 385 )); 386 } 387 let unique = values.iter().map(String::as_str).collect::<BTreeSet<_>>(); 388 if unique.iter().copied().ne(values.iter().map(String::as_str)) { 389 return Err(format!( 390 "{API_BOUNDARIES_RELATIVE} {label} must be sorted and unique" 391 )); 392 } 393 Ok(unique) 394 } 395 396 fn valid_exception_id(id: &str) -> bool { 397 id.strip_prefix("RCRV1-API-") 398 .is_some_and(|suffix| suffix.len() == 3 && suffix.bytes().all(|byte| byte.is_ascii_digit())) 399 } 400 401 fn validate_relative_source(id: &str, source: &str) -> Result<(), String> { 402 let path = Path::new(source); 403 if source.is_empty() 404 || path.is_absolute() 405 || path 406 .components() 407 .any(|component| !matches!(component, Component::Normal(_))) 408 || path.extension().and_then(|extension| extension.to_str()) != Some("rs") 409 { 410 return Err(format!( 411 "{API_BOUNDARIES_RELATIVE} exception {id} source must be a normalized relative Rust path" 412 )); 413 } 414 Ok(()) 415 } 416 417 fn load_and_validate_decision(workspace_root: &Path) -> Result<ApiLeakageDecision, String> { 418 let path = workspace_root.join(API_DECISION_RELATIVE); 419 let raw = 420 fs::read_to_string(&path).map_err(|error| format!("read {}: {error}", path.display()))?; 421 let decision = toml::from_str::<ApiLeakageDecision>(&raw) 422 .map_err(|error| format!("parse {}: {error}", path.display()))?; 423 424 if decision.schema_version != DECISION_SCHEMA_VERSION 425 || decision.decision_id != API_DECISION_ID 426 || decision.status != "accepted_historical" 427 || decision.accepted_date != "2026-07-27" 428 || decision.completed_step != CURRENT_STEP 429 || decision.publication_authorized 430 { 431 return Err(format!( 432 "{API_DECISION_RELATIVE} identity, lifecycle, or publication policy drifted" 433 )); 434 } 435 if decision 436 .exception_ids 437 .iter() 438 .map(String::as_str) 439 .ne(HISTORICAL_EXCEPTION_IDS) 440 { 441 return Err(format!( 442 "{API_DECISION_RELATIVE} must preserve the exact historical exception ids" 443 )); 444 } 445 if !decision.active_exception_ids.is_empty() { 446 return Err(format!( 447 "{API_DECISION_RELATIVE} must not authorize active exceptions after Step {CURRENT_STEP}" 448 )); 449 } 450 if decision 451 .forbidden_expansion 452 .iter() 453 .map(String::as_str) 454 .ne(FORBIDDEN_EXPANSION) 455 { 456 return Err(format!( 457 "{API_DECISION_RELATIVE} forbidden expansion set drifted" 458 )); 459 } 460 if decision 461 .removal_milestone 462 .iter() 463 .map(|milestone| (milestone.package.as_str(), milestone.step)) 464 .ne(REMOVAL_MILESTONES) 465 { 466 return Err(format!( 467 "{API_DECISION_RELATIVE} removal milestones drifted" 468 )); 469 } 470 Ok(decision) 471 } 472 473 fn validate_decision_reference( 474 exception: &ApiException, 475 decision: &ApiLeakageDecision, 476 ) -> Result<(), String> { 477 let path = Path::new(&exception.decision); 478 if exception.decision != API_DECISION_RELATIVE 479 || path.is_absolute() 480 || path 481 .components() 482 .any(|component| !matches!(component, Component::Normal(_))) 483 || path.extension().and_then(|extension| extension.to_str()) != Some("toml") 484 { 485 return Err(format!( 486 "{API_BOUNDARIES_RELATIVE} exception {} decision must be {API_DECISION_RELATIVE}", 487 exception.id 488 )); 489 } 490 if !decision 491 .active_exception_ids 492 .iter() 493 .any(|id| id == &exception.id) 494 { 495 return Err(format!( 496 "{API_BOUNDARIES_RELATIVE} exception {} is not active in {API_DECISION_RELATIVE}", 497 exception.id 498 )); 499 } 500 Ok(()) 501 } 502 503 fn package_set_mismatch(expected: &BTreeSet<String>, actual: &BTreeSet<String>) -> String { 504 let missing = expected 505 .difference(actual) 506 .cloned() 507 .collect::<Vec<_>>() 508 .join(", "); 509 let extra = actual 510 .difference(expected) 511 .cloned() 512 .collect::<Vec<_>>() 513 .join(", "); 514 format!( 515 "{API_BOUNDARIES_RELATIVE} package catalog mismatch; missing: {missing}; extra: {extra}" 516 ) 517 } 518 519 fn load_metadata(workspace_root: &Path) -> Result<CargoMetadata, String> { 520 let output = Command::new("cargo") 521 .args(["metadata", "--format-version", "1", "--locked", "--no-deps"]) 522 .current_dir(workspace_root) 523 .output() 524 .map_err(|error| format!("run cargo metadata: {error}"))?; 525 if !output.status.success() { 526 return Err(format!( 527 "cargo metadata failed while checking public API boundaries: {}", 528 String::from_utf8_lossy(&output.stderr).trim() 529 )); 530 } 531 serde_json::from_slice(&output.stdout) 532 .map_err(|error| format!("parse cargo metadata for public API boundaries: {error}")) 533 } 534 535 fn scan_workspace( 536 _workspace_root: &Path, 537 policy: &ApiBoundaryPolicy, 538 metadata: &CargoMetadata, 539 ) -> Result<Vec<ApiFinding>, String> { 540 let workspace_members = metadata 541 .workspace_members 542 .iter() 543 .map(String::as_str) 544 .collect::<BTreeSet<_>>(); 545 let package_policy = policy 546 .package 547 .iter() 548 .map(|package| (package.name.as_str(), package)) 549 .collect::<BTreeMap<_, _>>(); 550 let forbidden = policy 551 .forbidden_public_paths 552 .iter() 553 .map(String::as_str) 554 .collect::<BTreeSet<_>>(); 555 let mut findings = BTreeSet::new(); 556 557 for package in &metadata.packages { 558 if !workspace_members.contains(package.id.as_str()) { 559 continue; 560 } 561 let Some(package_policy) = package_policy.get(package.name.as_str()).copied() else { 562 continue; 563 }; 564 let manifest_path = Path::new(&package.manifest_path); 565 let package_root = manifest_path.parent().ok_or_else(|| { 566 format!( 567 "package {} manifest has no parent: {}", 568 package.name, package.manifest_path 569 ) 570 })?; 571 let allowed = package_policy 572 .allowed_public_paths 573 .iter() 574 .map(String::as_str) 575 .collect::<BTreeSet<_>>(); 576 let library_targets = package 577 .targets 578 .iter() 579 .filter(|target| { 580 target 581 .kind 582 .iter() 583 .any(|kind| kind == "lib" || kind == "proc-macro") 584 }) 585 .collect::<Vec<_>>(); 586 if library_targets.len() != 1 { 587 return Err(format!( 588 "public package {} must expose exactly one library target for API leakage analysis", 589 package.name 590 )); 591 } 592 let source_path = Path::new(&library_targets[0].src_path); 593 let source_module_directory = module_directory(source_path)?; 594 let mut units = BTreeMap::new(); 595 collect_module( 596 package_root, 597 Vec::new(), 598 None, 599 true, 600 true, 601 source_path, 602 &source_module_directory, 603 None, 604 &mut units, 605 )?; 606 findings.extend(scan_package_units( 607 &package.name, 608 &units, 609 &forbidden, 610 &allowed, 611 )?); 612 } 613 614 Ok(findings.into_iter().collect()) 615 } 616 617 #[allow(clippy::too_many_arguments)] 618 fn collect_module( 619 package_root: &Path, 620 module: Vec<String>, 621 parent: Option<Vec<String>>, 622 declared_public: bool, 623 initially_effective: bool, 624 source_path: &Path, 625 module_directory: &Path, 626 inline_items: Option<Vec<Item>>, 627 units: &mut BTreeMap<Vec<String>, ModuleUnit>, 628 ) -> Result<(), String> { 629 if units.contains_key(&module) { 630 return Ok(()); 631 } 632 let inside_inline_module = inline_items.is_some(); 633 let (items, source_relative) = if let Some(items) = inline_items { 634 let relative = source_path 635 .strip_prefix(package_root) 636 .map_err(|_| { 637 format!( 638 "module source {} escapes package {}", 639 source_path.display(), 640 package_root.display() 641 ) 642 })? 643 .to_string_lossy() 644 .replace('\\', "/"); 645 (items, relative) 646 } else { 647 let raw = fs::read_to_string(source_path) 648 .map_err(|error| format!("read {}: {error}", source_path.display()))?; 649 let file = syn::parse_file(&raw) 650 .map_err(|error| format!("parse {}: {error}", source_path.display()))?; 651 let relative = source_path 652 .strip_prefix(package_root) 653 .map_err(|_| { 654 format!( 655 "module source {} escapes package {}", 656 source_path.display(), 657 package_root.display() 658 ) 659 })? 660 .to_string_lossy() 661 .replace('\\', "/"); 662 (file.items, relative) 663 }; 664 665 let children = items 666 .iter() 667 .filter_map(|item| match item { 668 Item::Mod(item_mod) => Some(item_mod.clone()), 669 _ => None, 670 }) 671 .collect::<Vec<_>>(); 672 units.insert( 673 module.clone(), 674 ModuleUnit { 675 module: module.clone(), 676 parent, 677 declared_public, 678 initially_effective, 679 source_relative, 680 items, 681 }, 682 ); 683 684 for child in children { 685 let mut child_module = module.clone(); 686 child_module.push(child.ident.to_string()); 687 let child_public = is_public(&child.vis); 688 let child_effective = initially_effective && child_public; 689 let attribute_base = if inside_inline_module { 690 module_directory 691 } else { 692 source_path.parent().unwrap_or_else(|| Path::new(".")) 693 }; 694 let child_directory = path_attribute(&child) 695 .map(|path| attribute_base.join(path)) 696 .unwrap_or_else(|| module_directory.join(child.ident.to_string())); 697 if let Some((_, inline)) = child.content { 698 collect_module( 699 package_root, 700 child_module, 701 Some(module.clone()), 702 child_public, 703 child_effective, 704 source_path, 705 &child_directory, 706 Some(inline), 707 units, 708 )?; 709 } else { 710 let child_path = module_source_path(attribute_base, module_directory, &child)?; 711 collect_module( 712 package_root, 713 child_module, 714 Some(module.clone()), 715 child_public, 716 child_effective, 717 &child_path, 718 &self::module_directory(&child_path)?, 719 None, 720 units, 721 )?; 722 } 723 } 724 Ok(()) 725 } 726 727 fn module_directory(source_path: &Path) -> Result<PathBuf, String> { 728 let parent = source_path 729 .parent() 730 .ok_or_else(|| format!("module source has no parent: {}", source_path.display()))?; 731 let file_name = source_path.file_name().and_then(|name| name.to_str()); 732 if matches!(file_name, Some("lib.rs" | "main.rs" | "mod.rs")) { 733 Ok(parent.to_path_buf()) 734 } else { 735 Ok(parent.join( 736 source_path 737 .file_stem() 738 .ok_or_else(|| format!("module source has no stem: {}", source_path.display()))?, 739 )) 740 } 741 } 742 743 fn module_source_path( 744 attribute_base: &Path, 745 module_directory: &Path, 746 item_mod: &syn::ItemMod, 747 ) -> Result<PathBuf, String> { 748 if let Some(path) = path_attribute(item_mod) { 749 return Ok(attribute_base.join(path)); 750 } 751 let name = item_mod.ident.to_string(); 752 let flat = module_directory.join(format!("{name}.rs")); 753 let nested = module_directory.join(&name).join("mod.rs"); 754 match (flat.is_file(), nested.is_file()) { 755 (true, false) => Ok(flat), 756 (false, true) => Ok(nested), 757 (true, true) => Err(format!( 758 "module {} is ambiguous between {} and {}", 759 item_mod.ident, 760 flat.display(), 761 nested.display() 762 )), 763 (false, false) => Err(format!( 764 "module {} source is missing under {}", 765 item_mod.ident, 766 module_directory.display() 767 )), 768 } 769 } 770 771 fn path_attribute(item_mod: &syn::ItemMod) -> Option<String> { 772 item_mod.attrs.iter().find_map(|attribute| { 773 if !attribute.path().is_ident("path") { 774 return None; 775 } 776 let Meta::NameValue(value) = &attribute.meta else { 777 return None; 778 }; 779 let Expr::Lit(ExprLit { 780 lit: Lit::Str(path), 781 .. 782 }) = &value.value 783 else { 784 return None; 785 }; 786 Some(path.value()) 787 }) 788 } 789 790 fn scan_package_units( 791 package: &str, 792 units: &BTreeMap<Vec<String>, ModuleUnit>, 793 forbidden: &BTreeSet<&str>, 794 allowed: &BTreeSet<&str>, 795 ) -> Result<Vec<ApiFinding>, String> { 796 let mut effective = units 797 .values() 798 .filter(|unit| unit.initially_effective) 799 .map(|unit| unit.module.clone()) 800 .collect::<BTreeSet<_>>(); 801 let mut exported_items = BTreeSet::new(); 802 let mut changed = true; 803 while changed { 804 changed = propagate_public_modules(units, &mut effective); 805 let scopes = effective.iter().cloned().collect::<Vec<_>>(); 806 for scope in scopes { 807 let unit = units 808 .get(&scope) 809 .ok_or_else(|| format!("missing module unit {}", module_label(&scope)))?; 810 for item_use in unit.items.iter().filter_map(|item| match item { 811 Item::Use(item_use) if is_public(&item_use.vis) => Some(item_use), 812 _ => None, 813 }) { 814 for (segments, glob) in flatten_use_tree(&item_use.tree) { 815 match resolve_internal_export(&scope, &segments, glob, units) { 816 InternalExport::Module(module) => { 817 changed |= effective.insert(module); 818 } 819 InternalExport::Item(module, item) => { 820 changed |= exported_items.insert((module, item)); 821 } 822 InternalExport::External => {} 823 } 824 } 825 } 826 } 827 } 828 propagate_public_modules(units, &mut effective); 829 830 let mut findings = BTreeSet::new(); 831 for unit in units.values() { 832 let imports = import_map(&unit.items); 833 let unit_effective = effective.contains(&unit.module); 834 let explicitly_exported = exported_items 835 .iter() 836 .filter(|(module, _)| module == &unit.module) 837 .map(|(_, item)| item.as_str()) 838 .collect::<BTreeSet<_>>(); 839 840 for item in &unit.items { 841 if let Item::Use(item_use) = item { 842 if unit_effective && is_public(&item_use.vis) { 843 scan_public_use( 844 package, 845 unit, 846 item_use, 847 &imports, 848 forbidden, 849 allowed, 850 &mut findings, 851 ); 852 } 853 continue; 854 } 855 if let Item::Impl(item_impl) = item { 856 let Some(self_name) = impl_self_name(&item_impl.self_ty) else { 857 continue; 858 }; 859 if unit_effective || explicitly_exported.contains(self_name.as_str()) { 860 scan_impl( 861 package, 862 unit, 863 item_impl, 864 &self_name, 865 &imports, 866 forbidden, 867 allowed, 868 &mut findings, 869 ); 870 } 871 continue; 872 } 873 let Some(name) = item_name(item) else { 874 continue; 875 }; 876 if (unit_effective && item_is_public(item)) 877 || explicitly_exported.contains(name.as_str()) 878 { 879 scan_item( 880 package, 881 unit, 882 item, 883 &imports, 884 forbidden, 885 allowed, 886 &mut findings, 887 ); 888 } 889 } 890 } 891 Ok(findings.into_iter().collect()) 892 } 893 894 fn propagate_public_modules( 895 units: &BTreeMap<Vec<String>, ModuleUnit>, 896 effective: &mut BTreeSet<Vec<String>>, 897 ) -> bool { 898 let mut changed = false; 899 loop { 900 let before = effective.len(); 901 for unit in units.values() { 902 if unit.declared_public 903 && unit 904 .parent 905 .as_ref() 906 .is_some_and(|parent| effective.contains(parent)) 907 { 908 effective.insert(unit.module.clone()); 909 } 910 } 911 if effective.len() == before { 912 break; 913 } 914 changed = true; 915 } 916 changed 917 } 918 919 fn flatten_use_tree(tree: &UseTree) -> Vec<(Vec<String>, bool)> { 920 fn visit(tree: &UseTree, prefix: &mut Vec<String>, output: &mut Vec<(Vec<String>, bool)>) { 921 match tree { 922 UseTree::Path(path) => { 923 prefix.push(path.ident.to_string()); 924 visit(&path.tree, prefix, output); 925 prefix.pop(); 926 } 927 UseTree::Name(name) => { 928 if name.ident == "self" { 929 output.push((prefix.clone(), false)); 930 } else { 931 let mut path = prefix.clone(); 932 path.push(name.ident.to_string()); 933 output.push((path, false)); 934 } 935 } 936 UseTree::Rename(rename) => { 937 let mut path = prefix.clone(); 938 path.push(rename.ident.to_string()); 939 output.push((path, false)); 940 } 941 UseTree::Glob(_) => output.push((prefix.clone(), true)), 942 UseTree::Group(group) => { 943 for item in &group.items { 944 visit(item, prefix, output); 945 } 946 } 947 } 948 } 949 950 let mut output = Vec::new(); 951 visit(tree, &mut Vec::new(), &mut output); 952 output 953 } 954 955 fn resolve_internal_export( 956 current: &[String], 957 segments: &[String], 958 glob: bool, 959 units: &BTreeMap<Vec<String>, ModuleUnit>, 960 ) -> InternalExport { 961 if segments.is_empty() { 962 return InternalExport::External; 963 } 964 let candidates = internal_candidates(current, segments); 965 for candidate in candidates { 966 if glob && units.contains_key(&candidate) { 967 return InternalExport::Module(candidate); 968 } 969 if units.contains_key(&candidate) { 970 return InternalExport::Module(candidate); 971 } 972 if let Some((item, module)) = candidate.split_last() { 973 let module = module.to_vec(); 974 if units.contains_key(&module) { 975 return InternalExport::Item(module, item.clone()); 976 } 977 } 978 } 979 InternalExport::External 980 } 981 982 fn internal_candidates(current: &[String], segments: &[String]) -> Vec<Vec<String>> { 983 let mut candidates = Vec::new(); 984 match segments.first().map(String::as_str) { 985 Some("crate") => candidates.push(segments[1..].to_vec()), 986 Some("self") => { 987 let mut path = current.to_vec(); 988 path.extend_from_slice(&segments[1..]); 989 candidates.push(path); 990 } 991 Some("super") => { 992 let mut base = current.to_vec(); 993 let mut index = 0; 994 while segments.get(index).map(String::as_str) == Some("super") { 995 base.pop(); 996 index += 1; 997 } 998 base.extend_from_slice(&segments[index..]); 999 candidates.push(base); 1000 } 1001 _ => { 1002 candidates.push(segments.to_vec()); 1003 let mut local = current.to_vec(); 1004 local.extend_from_slice(segments); 1005 if !candidates.contains(&local) { 1006 candidates.push(local); 1007 } 1008 } 1009 } 1010 candidates 1011 } 1012 1013 fn import_map(items: &[Item]) -> BTreeMap<String, Vec<String>> { 1014 fn visit(tree: &UseTree, prefix: &mut Vec<String>, output: &mut BTreeMap<String, Vec<String>>) { 1015 match tree { 1016 UseTree::Path(path) => { 1017 prefix.push(path.ident.to_string()); 1018 visit(&path.tree, prefix, output); 1019 prefix.pop(); 1020 } 1021 UseTree::Name(name) => { 1022 if name.ident == "self" { 1023 if let Some(local) = prefix.last() { 1024 output.insert(local.clone(), prefix.clone()); 1025 } 1026 } else { 1027 let mut path = prefix.clone(); 1028 path.push(name.ident.to_string()); 1029 output.insert(name.ident.to_string(), path); 1030 } 1031 } 1032 UseTree::Rename(rename) => { 1033 let mut path = prefix.clone(); 1034 path.push(rename.ident.to_string()); 1035 output.insert(rename.rename.to_string(), path); 1036 } 1037 UseTree::Glob(_) => {} 1038 UseTree::Group(group) => { 1039 for item in &group.items { 1040 visit(item, prefix, output); 1041 } 1042 } 1043 } 1044 } 1045 1046 let mut output = BTreeMap::new(); 1047 for item_use in items.iter().filter_map(|item| match item { 1048 Item::Use(item_use) => Some(item_use), 1049 _ => None, 1050 }) { 1051 visit(&item_use.tree, &mut Vec::new(), &mut output); 1052 } 1053 output 1054 } 1055 1056 #[allow(clippy::too_many_arguments)] 1057 fn scan_item( 1058 package: &str, 1059 unit: &ModuleUnit, 1060 item: &Item, 1061 imports: &BTreeMap<String, Vec<String>>, 1062 forbidden: &BTreeSet<&str>, 1063 allowed: &BTreeSet<&str>, 1064 findings: &mut BTreeSet<ApiFinding>, 1065 ) { 1066 let name = item_name(item).unwrap_or_else(|| "<item>".to_owned()); 1067 let label = qualified_item(&unit.module, &name); 1068 let mut visitor = 1069 LeakageVisitor::new(package, unit, label, imports, forbidden, allowed, findings); 1070 match item { 1071 Item::Const(item) => visitor.visit_type(&item.ty), 1072 Item::Enum(item) => { 1073 visitor.visit_generics(&item.generics); 1074 for variant in &item.variants { 1075 visit_fields(&mut visitor, &variant.fields, true); 1076 } 1077 } 1078 Item::Fn(item) => visitor.visit_signature(&item.sig), 1079 Item::ForeignMod(item) => { 1080 for foreign in &item.items { 1081 if let ForeignItem::Fn(function) = foreign { 1082 visitor.visit_signature(&function.sig); 1083 } 1084 } 1085 } 1086 Item::Static(item) => visitor.visit_type(&item.ty), 1087 Item::Struct(item) => { 1088 visitor.visit_generics(&item.generics); 1089 visit_fields(&mut visitor, &item.fields, false); 1090 } 1091 Item::Trait(item) => { 1092 visitor.visit_generics(&item.generics); 1093 for bound in &item.supertraits { 1094 visitor.visit_type_param_bound(bound); 1095 } 1096 for trait_item in &item.items { 1097 match trait_item { 1098 TraitItem::Const(item) => visitor.visit_type(&item.ty), 1099 TraitItem::Fn(item) => visitor.visit_signature(&item.sig), 1100 TraitItem::Type(item) => { 1101 visitor.visit_generics(&item.generics); 1102 for bound in &item.bounds { 1103 visitor.visit_type_param_bound(bound); 1104 } 1105 if let Some((_, ty)) = &item.default { 1106 visitor.visit_type(ty); 1107 } 1108 } 1109 _ => {} 1110 } 1111 } 1112 } 1113 Item::TraitAlias(item) => { 1114 visitor.visit_generics(&item.generics); 1115 for bound in &item.bounds { 1116 visitor.visit_type_param_bound(bound); 1117 } 1118 } 1119 Item::Type(item) => { 1120 visitor.visit_generics(&item.generics); 1121 visitor.visit_type(&item.ty); 1122 } 1123 Item::Union(item) => { 1124 visitor.visit_generics(&item.generics); 1125 for field in &item.fields.named { 1126 if is_public(&field.vis) { 1127 visitor.visit_type(&field.ty); 1128 } 1129 } 1130 } 1131 _ => {} 1132 } 1133 } 1134 1135 fn visit_fields(visitor: &mut LeakageVisitor<'_>, fields: &Fields, all_visible: bool) { 1136 for field in fields { 1137 if all_visible || is_public(&field.vis) { 1138 visitor.visit_type(&field.ty); 1139 } 1140 } 1141 } 1142 1143 #[allow(clippy::too_many_arguments)] 1144 fn scan_impl( 1145 package: &str, 1146 unit: &ModuleUnit, 1147 item_impl: &syn::ItemImpl, 1148 self_name: &str, 1149 imports: &BTreeMap<String, Vec<String>>, 1150 forbidden: &BTreeSet<&str>, 1151 allowed: &BTreeSet<&str>, 1152 findings: &mut BTreeSet<ApiFinding>, 1153 ) { 1154 let trait_impl = item_impl.trait_.is_some(); 1155 for item in &item_impl.items { 1156 let (name, is_exposed) = match item { 1157 ImplItem::Const(item) => (item.ident.to_string(), trait_impl || is_public(&item.vis)), 1158 ImplItem::Fn(item) => ( 1159 item.sig.ident.to_string(), 1160 trait_impl || is_public(&item.vis), 1161 ), 1162 ImplItem::Type(item) => (item.ident.to_string(), trait_impl || is_public(&item.vis)), 1163 _ => continue, 1164 }; 1165 if !is_exposed { 1166 continue; 1167 } 1168 let label = format!("{}::{name}", qualified_item(&unit.module, self_name)); 1169 let mut visitor = 1170 LeakageVisitor::new(package, unit, label, imports, forbidden, allowed, findings); 1171 if let Some((_, trait_path, _)) = &item_impl.trait_ { 1172 visitor.visit_path(trait_path); 1173 } 1174 match item { 1175 ImplItem::Const(item) => visitor.visit_type(&item.ty), 1176 ImplItem::Fn(item) => visitor.visit_signature(&item.sig), 1177 ImplItem::Type(item) => { 1178 visitor.visit_generics(&item.generics); 1179 visitor.visit_type(&item.ty); 1180 } 1181 _ => {} 1182 } 1183 } 1184 } 1185 1186 #[allow(clippy::too_many_arguments)] 1187 fn scan_public_use( 1188 package: &str, 1189 unit: &ModuleUnit, 1190 item_use: &syn::ItemUse, 1191 imports: &BTreeMap<String, Vec<String>>, 1192 forbidden: &BTreeSet<&str>, 1193 allowed: &BTreeSet<&str>, 1194 findings: &mut BTreeSet<ApiFinding>, 1195 ) { 1196 for (segments, _) in flatten_use_tree(&item_use.tree) { 1197 if segments.is_empty() { 1198 continue; 1199 } 1200 let label = format!("{}::pub use", module_label(&unit.module)); 1201 record_path( 1202 package, unit, &label, &segments, imports, forbidden, allowed, findings, 1203 ); 1204 } 1205 } 1206 1207 struct LeakageVisitor<'a> { 1208 package: &'a str, 1209 unit: &'a ModuleUnit, 1210 item: String, 1211 imports: &'a BTreeMap<String, Vec<String>>, 1212 forbidden: &'a BTreeSet<&'a str>, 1213 allowed: &'a BTreeSet<&'a str>, 1214 findings: &'a mut BTreeSet<ApiFinding>, 1215 } 1216 1217 impl<'a> LeakageVisitor<'a> { 1218 #[allow(clippy::too_many_arguments)] 1219 fn new( 1220 package: &'a str, 1221 unit: &'a ModuleUnit, 1222 item: String, 1223 imports: &'a BTreeMap<String, Vec<String>>, 1224 forbidden: &'a BTreeSet<&'a str>, 1225 allowed: &'a BTreeSet<&'a str>, 1226 findings: &'a mut BTreeSet<ApiFinding>, 1227 ) -> Self { 1228 Self { 1229 package, 1230 unit, 1231 item, 1232 imports, 1233 forbidden, 1234 allowed, 1235 findings, 1236 } 1237 } 1238 } 1239 1240 impl<'ast> Visit<'ast> for LeakageVisitor<'_> { 1241 fn visit_path(&mut self, path: &'ast SynPath) { 1242 let segments = path 1243 .segments 1244 .iter() 1245 .map(|segment| segment.ident.to_string()) 1246 .collect::<Vec<_>>(); 1247 record_path( 1248 self.package, 1249 self.unit, 1250 &self.item, 1251 &segments, 1252 self.imports, 1253 self.forbidden, 1254 self.allowed, 1255 self.findings, 1256 ); 1257 syn::visit::visit_path(self, path); 1258 } 1259 } 1260 1261 #[allow(clippy::too_many_arguments)] 1262 fn record_path( 1263 package: &str, 1264 unit: &ModuleUnit, 1265 item: &str, 1266 segments: &[String], 1267 imports: &BTreeMap<String, Vec<String>>, 1268 forbidden: &BTreeSet<&str>, 1269 allowed: &BTreeSet<&str>, 1270 findings: &mut BTreeSet<ApiFinding>, 1271 ) { 1272 if segments.is_empty() { 1273 return; 1274 } 1275 let resolved = if let Some(imported) = imports.get(&segments[0]) { 1276 let mut resolved = imported.clone(); 1277 resolved.extend_from_slice(&segments[1..]); 1278 resolved 1279 } else { 1280 segments.to_vec() 1281 }; 1282 let observed = resolved.join("::"); 1283 for forbidden_path in forbidden { 1284 if allowed.contains(forbidden_path) 1285 || !(observed == *forbidden_path 1286 || observed 1287 .strip_prefix(forbidden_path) 1288 .is_some_and(|suffix| suffix.starts_with("::"))) 1289 { 1290 continue; 1291 } 1292 findings.insert(ApiFinding { 1293 package: package.to_owned(), 1294 source: unit.source_relative.clone(), 1295 item: item.to_owned(), 1296 forbidden_path: (*forbidden_path).to_owned(), 1297 observed_path: observed.clone(), 1298 }); 1299 } 1300 } 1301 1302 fn exception_matches(exceptions: &[ApiException], finding: &ApiFinding) -> bool { 1303 exceptions.iter().any(|exception| { 1304 exception.package == finding.package 1305 && exception.source == finding.source 1306 && exception.forbidden_path == finding.forbidden_path 1307 && exception.items.binary_search(&finding.item).is_ok() 1308 && exception 1309 .observed_paths 1310 .binary_search(&finding.observed_path) 1311 .is_ok() 1312 }) 1313 } 1314 1315 fn format_finding(finding: &ApiFinding) -> String { 1316 format!( 1317 "package={} source={} item={} forbidden_path={} observed_path={}", 1318 finding.package, 1319 finding.source, 1320 finding.item, 1321 finding.forbidden_path, 1322 finding.observed_path 1323 ) 1324 } 1325 1326 fn item_is_public(item: &Item) -> bool { 1327 match item { 1328 Item::Const(item) => is_public(&item.vis), 1329 Item::Enum(item) => is_public(&item.vis), 1330 Item::Fn(item) => is_public(&item.vis), 1331 Item::ForeignMod(_) => true, 1332 Item::Static(item) => is_public(&item.vis), 1333 Item::Struct(item) => is_public(&item.vis), 1334 Item::Trait(item) => is_public(&item.vis), 1335 Item::TraitAlias(item) => is_public(&item.vis), 1336 Item::Type(item) => is_public(&item.vis), 1337 Item::Union(item) => is_public(&item.vis), 1338 _ => false, 1339 } 1340 } 1341 1342 fn item_name(item: &Item) -> Option<String> { 1343 match item { 1344 Item::Const(item) => Some(item.ident.to_string()), 1345 Item::Enum(item) => Some(item.ident.to_string()), 1346 Item::Fn(item) => Some(item.sig.ident.to_string()), 1347 Item::Static(item) => Some(item.ident.to_string()), 1348 Item::Struct(item) => Some(item.ident.to_string()), 1349 Item::Trait(item) => Some(item.ident.to_string()), 1350 Item::TraitAlias(item) => Some(item.ident.to_string()), 1351 Item::Type(item) => Some(item.ident.to_string()), 1352 Item::Union(item) => Some(item.ident.to_string()), 1353 _ => None, 1354 } 1355 } 1356 1357 fn impl_self_name(self_ty: &Type) -> Option<String> { 1358 let Type::Path(path) = self_ty else { 1359 return None; 1360 }; 1361 path.path 1362 .segments 1363 .last() 1364 .map(|segment| segment.ident.to_string()) 1365 } 1366 1367 fn is_public(visibility: &Visibility) -> bool { 1368 matches!(visibility, Visibility::Public(_)) 1369 } 1370 1371 fn qualified_item(module: &[String], item: &str) -> String { 1372 if module.is_empty() { 1373 item.to_owned() 1374 } else { 1375 format!("{}::{item}", module.join("::")) 1376 } 1377 } 1378 1379 fn module_label(module: &[String]) -> String { 1380 if module.is_empty() { 1381 "crate".to_owned() 1382 } else { 1383 module.join("::") 1384 } 1385 } 1386 1387 #[cfg(test)] 1388 mod tests { 1389 use super::{ 1390 API_DECISION_RELATIVE, ApiBoundaryPolicy, ApiException, CargoMetadata, scan_workspace, 1391 validate_policy, 1392 }; 1393 use serde::Deserialize; 1394 use std::{collections::BTreeSet, fs}; 1395 1396 const POLICY: &str = include_str!("../../../../contracts/releases/api_boundaries.toml"); 1397 const DECISION: &str = include_str!( 1398 "../../../../contracts/architecture/decisions/public_api_leakage_migration_baseline.v1.toml" 1399 ); 1400 const ARCHITECTURE: &str = include_str!("../../../../contracts/crates/release.v2.toml"); 1401 const GENERIC_SQLX: &str = include_str!("../../tests/fixtures/api-leakage/generic-sqlx.rs"); 1402 const GENERIC_RENAMED_TOKIO: &str = 1403 include_str!("../../tests/fixtures/api-leakage/generic-renamed-tokio.rs"); 1404 const ALLOWED_ADAPTER: &str = 1405 include_str!("../../tests/fixtures/api-leakage/allowed-concrete-adapter.rs"); 1406 const PRIVATE_IMPLEMENTATION: &str = 1407 include_str!("../../tests/fixtures/api-leakage/private-implementation.rs"); 1408 #[derive(Deserialize)] 1409 struct ArchitectureCatalog { 1410 public_packages: Vec<String>, 1411 } 1412 1413 fn policy() -> ApiBoundaryPolicy { 1414 toml::from_str(POLICY).expect("API boundary policy") 1415 } 1416 1417 fn expected_packages() -> BTreeSet<String> { 1418 toml::from_str::<ArchitectureCatalog>(ARCHITECTURE) 1419 .expect("architecture") 1420 .public_packages 1421 .into_iter() 1422 .collect() 1423 } 1424 1425 fn fixture_metadata(root: &std::path::Path, package: &str, source: &str) -> CargoMetadata { 1426 let package_root = root.join(package); 1427 fs::create_dir_all(package_root.join("src")).expect("create fixture source"); 1428 fs::write( 1429 package_root.join("Cargo.toml"), 1430 "[package]\nname='fixture'\n", 1431 ) 1432 .expect("write fixture manifest"); 1433 fs::write(package_root.join("src/lib.rs"), source).expect("write fixture source"); 1434 let id = format!("fixture#{package}@0.1.0"); 1435 CargoMetadata { 1436 workspace_members: vec![id.clone()], 1437 packages: vec![super::CargoPackage { 1438 id, 1439 name: package.to_owned(), 1440 manifest_path: package_root 1441 .join("Cargo.toml") 1442 .to_string_lossy() 1443 .into_owned(), 1444 targets: vec![super::CargoTarget { 1445 kind: vec!["lib".to_owned()], 1446 src_path: package_root 1447 .join("src/lib.rs") 1448 .to_string_lossy() 1449 .into_owned(), 1450 }], 1451 }], 1452 } 1453 } 1454 1455 fn scan_fixture(package: &str, source: &str) -> Vec<super::ApiFinding> { 1456 let root = tempfile::TempDir::new().expect("fixture root"); 1457 scan_workspace( 1458 root.path(), 1459 &policy(), 1460 &fixture_metadata(root.path(), package, source), 1461 ) 1462 .expect("scan fixture") 1463 } 1464 1465 #[test] 1466 fn path_attributes_follow_physical_files_and_inline_module_directories() { 1467 // Rust Reference items.mod.outlined.path: inline paths include their 1468 // module directories; a redirected file owns its physical child path. 1469 for (source, branch, leaf) in [ 1470 ( 1471 "pub mod branch;", 1472 Some(( 1473 "src/branch.rs", 1474 "pub mod inline { #[path = \"leaf.rs\"] pub mod leaf; }", 1475 )), 1476 "src/branch/inline/leaf.rs", 1477 ), 1478 ( 1479 "pub mod branch;", 1480 Some(( 1481 "src/branch/mod.rs", 1482 "pub mod inline { #[path = \"leaf.rs\"] pub mod leaf; }", 1483 )), 1484 "src/branch/inline/leaf.rs", 1485 ), 1486 ( 1487 "pub mod outer { pub mod inner { #[path = \"leaf.rs\"] pub mod leaf; } }", 1488 None, 1489 "src/outer/inner/leaf.rs", 1490 ), 1491 ( 1492 "#[path = \"thread_files\"] pub mod thread { #[path = \"leaf.rs\"] pub mod leaf; }", 1493 None, 1494 "src/thread_files/leaf.rs", 1495 ), 1496 ( 1497 "#[path = \"redirect/payload.rs\"] pub mod branch;", 1498 Some(("src/redirect/payload.rs", "pub mod leaf;")), 1499 "src/redirect/payload/leaf.rs", 1500 ), 1501 ] { 1502 let root = tempfile::TempDir::new().unwrap(); 1503 let package = "radroots_signing"; 1504 let metadata = fixture_metadata(root.path(), package, source); 1505 let base = root.path().join(package); 1506 if let Some((name, body)) = branch { 1507 let path = base.join(name); 1508 fs::create_dir_all(path.parent().unwrap()).unwrap(); 1509 fs::write(path, body).unwrap(); 1510 } 1511 let path = base.join(leaf); 1512 fs::create_dir_all(path.parent().unwrap()).unwrap(); 1513 fs::write( 1514 path, 1515 "pub fn exposed() -> tokio::runtime::Runtime { todo!() }", 1516 ) 1517 .unwrap(); 1518 let findings = scan_workspace(root.path(), &policy(), &metadata).unwrap(); 1519 assert!( 1520 findings 1521 .iter() 1522 .any(|finding| finding.source == leaf && finding.forbidden_path == "tokio"), 1523 "{leaf}: {findings:?}" 1524 ); 1525 } 1526 } 1527 1528 fn write_baseline_decision(root: &std::path::Path) { 1529 fs::create_dir_all(root.join("contracts/architecture/decisions")) 1530 .expect("baseline decision directory"); 1531 fs::write( 1532 root.join( 1533 "contracts/architecture/decisions/public_api_leakage_migration_baseline.v1.toml", 1534 ), 1535 DECISION, 1536 ) 1537 .expect("baseline decision"); 1538 } 1539 1540 #[test] 1541 fn policy_covers_exact_architecture_catalog() { 1542 let root = tempfile::TempDir::new().expect("policy root"); 1543 write_baseline_decision(root.path()); 1544 validate_policy(root.path(), &policy(), &expected_packages()) 1545 .expect("policy without exceptions"); 1546 } 1547 1548 #[test] 1549 fn generic_sqlx_public_field_is_forbidden() { 1550 let findings = scan_fixture("radroots_storage", GENERIC_SQLX); 1551 assert_eq!(findings.len(), 1); 1552 assert_eq!(findings[0].item, "StorageHandle"); 1553 assert_eq!(findings[0].forbidden_path, "sqlx"); 1554 assert_eq!(findings[0].observed_path, "sqlx::SqlitePool"); 1555 } 1556 1557 #[test] 1558 fn renamed_tokio_return_type_is_resolved() { 1559 let findings = scan_fixture("radroots_sync", GENERIC_RENAMED_TOKIO); 1560 assert_eq!(findings.len(), 1); 1561 assert_eq!(findings[0].item, "executor"); 1562 assert_eq!(findings[0].forbidden_path, "tokio"); 1563 assert_eq!(findings[0].observed_path, "tokio::runtime::Handle"); 1564 } 1565 1566 #[test] 1567 fn specified_nostr_adapter_may_expose_protocol_types() { 1568 let findings = scan_fixture("radroots_nostr", ALLOWED_ADAPTER); 1569 assert!(findings.is_empty()); 1570 } 1571 1572 #[test] 1573 fn private_implementation_types_are_not_public_api() { 1574 let findings = scan_fixture("radroots_sdk", PRIVATE_IMPLEMENTATION); 1575 assert!(findings.is_empty()); 1576 } 1577 1578 #[test] 1579 fn invented_exception_is_rejected_by_the_completed_decision() { 1580 let root = tempfile::TempDir::new().expect("exception root"); 1581 write_baseline_decision(root.path()); 1582 let mut policy = policy(); 1583 policy.exception.push(ApiException { 1584 id: "RCRV1-API-999".to_owned(), 1585 package: "radroots_sdk".to_owned(), 1586 source: "src/lib.rs".to_owned(), 1587 forbidden_path: "reqwest".to_owned(), 1588 items: vec!["temporary_client".to_owned()], 1589 observed_paths: vec!["reqwest::Client".to_owned()], 1590 decision: API_DECISION_RELATIVE.to_owned(), 1591 removal_step: 400, 1592 rationale: "test-only exception".to_owned(), 1593 }); 1594 let error = validate_policy(root.path(), &policy, &expected_packages()) 1595 .expect_err("invented exception must fail"); 1596 assert!(error.contains("is not active")); 1597 } 1598 1599 #[test] 1600 fn expired_historical_exception_cannot_return() { 1601 let root = tempfile::TempDir::new().expect("expired exception root"); 1602 write_baseline_decision(root.path()); 1603 let mut policy = policy(); 1604 policy.exception.push(ApiException { 1605 id: "RCRV1-API-006".to_owned(), 1606 package: "radroots_nostr_connect".to_owned(), 1607 source: "src/client.rs".to_owned(), 1608 forbidden_path: "nostr".to_owned(), 1609 items: vec!["client::RadrootsNostrConnectClientTarget".to_owned()], 1610 observed_paths: vec!["nostr::PublicKey".to_owned()], 1611 decision: API_DECISION_RELATIVE.to_owned(), 1612 removal_step: 313, 1613 rationale: "retired historical exception".to_owned(), 1614 }); 1615 let error = validate_policy(root.path(), &policy, &expected_packages()) 1616 .expect_err("expired historical exception must fail"); 1617 assert!(error.contains("expired at Step 313")); 1618 } 1619 1620 #[test] 1621 fn malformed_or_publication_authorizing_decision_fails_closed() { 1622 let root = tempfile::TempDir::new().expect("decision validation root"); 1623 write_baseline_decision(root.path()); 1624 let decision_path = root.path().join(API_DECISION_RELATIVE); 1625 fs::write(&decision_path, "not valid toml = [\n").expect("malformed decision"); 1626 let malformed = validate_policy(root.path(), &policy(), &expected_packages()) 1627 .expect_err("malformed decision must fail"); 1628 assert!(malformed.contains("parse")); 1629 1630 fs::write( 1631 &decision_path, 1632 DECISION.replace( 1633 "publication_authorized = false", 1634 "publication_authorized = true", 1635 ), 1636 ) 1637 .expect("publication-authorizing decision"); 1638 let authorized = validate_policy(root.path(), &policy(), &expected_packages()) 1639 .expect_err("publication authorization must fail"); 1640 assert!(authorized.contains("publication policy drifted")); 1641 } 1642 }