lib.rs (131576B)
1 pub mod affected; 2 pub mod runtime_ownership; 3 4 use sha2::{Digest, Sha256}; 5 use std::collections::BTreeSet; 6 use std::fs::{self, OpenOptions}; 7 use std::io::{ErrorKind, Read}; 8 use std::path::{Component, Path, PathBuf}; 9 use std::process::Command as ProcessCommand; 10 use std::str::FromStr; 11 12 #[cfg(unix)] 13 use std::os::unix::fs::{MetadataExt, OpenOptionsExt}; 14 15 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 16 pub enum Command { 17 DesignSourceAudit, 18 RepoAudit, 19 NamespaceAudit, 20 ProvenanceCheck, 21 QualificationReport, 22 } 23 24 impl FromStr for Command { 25 type Err = String; 26 27 fn from_str(value: &str) -> Result<Self, Self::Err> { 28 match value { 29 "design-source-audit" => Ok(Self::DesignSourceAudit), 30 "repo-audit" => Ok(Self::RepoAudit), 31 "namespace-audit" => Ok(Self::NamespaceAudit), 32 "provenance-check" => Ok(Self::ProvenanceCheck), 33 "qualification-report" => Ok(Self::QualificationReport), 34 _ => Err(format!("unknown xtask command: {value}")), 35 } 36 } 37 } 38 39 pub fn run(root: &Path, command: Command) -> Result<String, Vec<String>> { 40 let root = validate_product_root(root).map_err(|finding| vec![finding])?; 41 let root = root.as_path(); 42 let build_mode = 43 std::env::var("HARVESTCIRCLE_BUILD_MODE").unwrap_or_else(|_| "standalone".to_owned()); 44 if command == Command::QualificationReport 45 && !matches!(build_mode.as_str(), "standalone" | "governed") 46 { 47 return Err(vec![format!( 48 "unknown qualification build mode: {build_mode}" 49 )]); 50 } 51 let inventory = Inventory::load(root).map_err(|finding| vec![finding])?; 52 let mut findings = Vec::new(); 53 let ownership = load_ownership(root).map_err(|finding| vec![finding])?; 54 ownership 55 .validate_native_inputs(&inventory.paths) 56 .map_err(|finding| vec![finding])?; 57 let mut native_paths = Vec::new(); 58 let mut ownership_reasons = Vec::new(); 59 for path in &inventory.paths { 60 let classification = ownership.classify(path).map_err(|finding| vec![finding])?; 61 if classification 62 .owners 63 .contains(&runtime_ownership::Owner::Native) 64 { 65 native_paths.push(path.clone()); 66 } 67 if let Some(reason) = classification.reason { 68 ownership_reasons.push(reason); 69 } 70 } 71 let native_inventory = Inventory { 72 paths: native_paths, 73 git_aware: inventory.git_aware, 74 }; 75 // Every command retains global safety. Only native-owned inputs enter the 76 // existing native implementation rules; unknown inputs widen conservatively. 77 if !matches!(command, Command::RepoAudit | Command::QualificationReport) { 78 global_source_audit(root, &inventory, &mut findings); 79 } 80 match command { 81 Command::DesignSourceAudit => design_source_audit(root, &native_inventory, &mut findings), 82 Command::RepoAudit => repo_audit(root, &inventory, &mut findings), 83 Command::NamespaceAudit => namespace_audit(root, &native_inventory, &mut findings), 84 Command::ProvenanceCheck => provenance_check(root, &native_inventory, &mut findings), 85 Command::QualificationReport => { 86 repo_audit(root, &inventory, &mut findings); 87 namespace_audit(root, &native_inventory, &mut findings); 88 provenance_check(root, &native_inventory, &mut findings); 89 design_source_audit(root, &native_inventory, &mut findings); 90 product_shell_audit(root, &native_inventory, &mut findings); 91 } 92 } 93 findings.sort(); 94 findings.dedup(); 95 if findings.is_empty() { 96 let inventory_kind = if inventory.git_aware { 97 "git" 98 } else { 99 "archive" 100 }; 101 let command_name = match command { 102 Command::DesignSourceAudit => "design-source-audit", 103 Command::RepoAudit => "repo-audit", 104 Command::NamespaceAudit => "namespace-audit", 105 Command::ProvenanceCheck => "provenance-check", 106 Command::QualificationReport => "qualification-report", 107 }; 108 let mode = if command == Command::QualificationReport { 109 format!("harvestcircle.build.mode={build_mode}\n") 110 } else { 111 String::new() 112 }; 113 Ok(format!( 114 "harvestcircle.xtask.command={command_name}\nharvestcircle.xtask.inventory={inventory_kind}\n{mode}harvestcircle.xtask.global_source_safety=checked\nharvestcircle.xtask.native_inputs={}\nharvestcircle.xtask.web_qualification=unclaimed\n{}harvestcircle.xtask.result=pass\n", 115 native_inventory.paths.len(), 116 ownership_reasons 117 .into_iter() 118 .map(|reason| format!("harvestcircle.xtask.ownership_reason={reason}\n")) 119 .collect::<String>() 120 )) 121 } else { 122 Err(findings) 123 } 124 } 125 126 fn validate_product_root(root: &Path) -> Result<PathBuf, String> { 127 let metadata = fs::symlink_metadata(root) 128 .map_err(|error| format!("HarvestCircle product root cannot be inspected: {error}"))?; 129 if metadata.file_type().is_symlink() || !metadata.is_dir() { 130 return Err( 131 "HarvestCircle product root must be a directory, not a symbolic link".to_owned(), 132 ); 133 } 134 let root = root 135 .canonicalize() 136 .map_err(|error| format!("HarvestCircle product root cannot be resolved: {error}"))?; 137 for marker in [ 138 "Makefile", 139 "settings.gradle.kts", 140 "build.gradle.kts", 141 "gradlew", 142 "config/product/harvestcircle-v1.properties", 143 "radroots.lib.source-lock.v1.toml", 144 "core/Cargo.toml", 145 "core/Cargo.lock", 146 "core/rust-toolchain.toml", 147 "tools/xtask/Cargo.toml", 148 "tools/xtask/Cargo.lock", 149 "core/crates/harvestcircle_domain/Cargo.toml", 150 "core/crates/harvestcircle_domain/src/lib.rs", 151 "contracts/rshr-201-step-gates.v1.json", 152 "contracts/release/harvestcircle-artifact-contract.v3.json", 153 ] { 154 validate_git_inventory_path(&root, Path::new(marker)) 155 .map_err(|finding| format!("invalid HarvestCircle product root: {finding}"))?; 156 } 157 for (manifest, identity) in [ 158 ( 159 "core/crates/harvestcircle_domain/Cargo.toml", 160 "harvestcircle_domain", 161 ), 162 ("tools/xtask/Cargo.toml", "harvestcircle_xtask"), 163 ] { 164 let source = bounded_no_follow_bytes(&root, Path::new(manifest), 1024 * 1024) 165 .map_err(|finding| format!("invalid HarvestCircle product root: {finding}"))?; 166 let source = std::str::from_utf8(&source) 167 .map_err(|_| format!("invalid HarvestCircle product root: {manifest} is not UTF-8"))?; 168 if !source 169 .lines() 170 .any(|line| line.trim() == format!("name = \"{identity}\"")) 171 { 172 return Err(format!( 173 "invalid HarvestCircle product root: {manifest} has the wrong product identity" 174 )); 175 } 176 } 177 Ok(root) 178 } 179 180 fn git_command(root: &Path) -> ProcessCommand { 181 let mut command = ProcessCommand::new("git"); 182 command.arg("-C").arg(root); 183 for variable in [ 184 "GIT_DIR", 185 "GIT_WORK_TREE", 186 "GIT_INDEX_FILE", 187 "GIT_COMMON_DIR", 188 "GIT_OBJECT_DIRECTORY", 189 "GIT_ALTERNATE_OBJECT_DIRECTORIES", 190 ] { 191 command.env_remove(variable); 192 } 193 command 194 } 195 196 fn has_git_context(root: &Path) -> Result<bool, String> { 197 for directory in root.ancestors() { 198 match fs::symlink_metadata(directory.join(".git")) { 199 Ok(metadata) => { 200 if metadata.file_type().is_symlink() || !(metadata.is_file() || metadata.is_dir()) { 201 return Err("Git metadata is not a regular file or directory".to_owned()); 202 } 203 let output = git_command(root) 204 .args(["rev-parse", "--is-inside-work-tree"]) 205 .output() 206 .map_err(|error| format!("unable to inspect Git context: {error}"))?; 207 if !output.status.success() || output.stdout != b"true\n" { 208 return Err("invalid Git metadata for HarvestCircle inventory".to_owned()); 209 } 210 return Ok(true); 211 } 212 Err(error) if error.kind() == ErrorKind::NotFound => {} 213 Err(error) => return Err(format!("unable to inspect Git metadata: {error}")), 214 } 215 } 216 Ok(false) 217 } 218 219 #[derive(Debug)] 220 struct Inventory { 221 paths: Vec<String>, 222 git_aware: bool, 223 } 224 225 impl Inventory { 226 fn load(root: &Path) -> Result<Self, String> { 227 if has_git_context(root)? { 228 let output = git_command(root) 229 .args([ 230 "ls-files", 231 "--cached", 232 "--others", 233 "--exclude-standard", 234 "-z", 235 "--", 236 ".", 237 ]) 238 .output() 239 .map_err(|error| { 240 format!("unable to enumerate tracked HarvestCircle sources: {error}") 241 })?; 242 if !output.status.success() { 243 return Err("unable to enumerate tracked HarvestCircle sources".to_owned()); 244 } 245 let mut paths = Vec::new(); 246 for raw_path in output 247 .stdout 248 .split(|byte| *byte == 0) 249 .filter(|path| !path.is_empty()) 250 { 251 let path = String::from_utf8(raw_path.to_vec()) 252 .map_err(|_| "Git inventory path is not valid UTF-8".to_owned())?; 253 validate_git_inventory_path(root, Path::new(&path))?; 254 paths.push(path); 255 } 256 paths.sort(); 257 paths.dedup(); 258 Ok(Self { 259 paths, 260 git_aware: true, 261 }) 262 } else { 263 let mut paths = Vec::new(); 264 archive_paths(root, root, &mut paths)?; 265 paths.sort(); 266 paths.dedup(); 267 Ok(Self { 268 paths, 269 git_aware: false, 270 }) 271 } 272 } 273 } 274 275 fn validate_git_inventory_path(root: &Path, relative: &Path) -> Result<(), String> { 276 if relative.is_absolute() 277 || relative.components().next().is_none() 278 || relative 279 .components() 280 .any(|component| !matches!(component, Component::Normal(_))) 281 { 282 return Err(format!( 283 "{}: Git inventory path must be normalized and relative", 284 relative.display() 285 )); 286 } 287 let components = relative.components().collect::<Vec<_>>(); 288 let mut current = root.to_path_buf(); 289 for (index, component) in components.iter().enumerate() { 290 current.push(component.as_os_str()); 291 let metadata = match fs::symlink_metadata(¤t) { 292 Ok(metadata) => metadata, 293 Err(error) if error.kind() == ErrorKind::NotFound => { 294 return Err(format!( 295 "{}: Git inventory path is missing", 296 relative.display() 297 )); 298 } 299 Err(error) => { 300 return Err(format!( 301 "{}: unable to inspect Git inventory path: {error}", 302 relative.display() 303 )); 304 } 305 }; 306 if metadata.file_type().is_symlink() { 307 return Err(format!( 308 "{}: Git inventory path traverses a symbolic link", 309 relative.display() 310 )); 311 } 312 if index + 1 < components.len() { 313 if !metadata.is_dir() { 314 return Err(format!( 315 "{}: Git inventory path parent is not a directory", 316 relative.display() 317 )); 318 } 319 } else if !metadata.is_file() { 320 return Err(format!( 321 "{}: Git inventory path is not a regular file", 322 relative.display() 323 )); 324 } 325 } 326 Ok(()) 327 } 328 329 fn archive_paths(root: &Path, directory: &Path, paths: &mut Vec<String>) -> Result<(), String> { 330 let entries = fs::read_dir(directory).map_err(|error| { 331 format!( 332 "{}: unable to read archive inventory: {error}", 333 directory.display() 334 ) 335 })?; 336 for entry in entries { 337 let entry = entry.map_err(|error| format!("archive inventory entry failed: {error}"))?; 338 let path = entry.path(); 339 let relative = relative(root, &path)?; 340 let first = relative.split('/').next().unwrap_or_default(); 341 if matches!( 342 first, 343 ".git" | ".gradle" | ".kotlin" | ".idea" | "build" | "target" | "out" 344 ) || is_web_output_path(&relative) 345 || relative 346 .split('/') 347 .any(|part| matches!(part, "build" | "target" | "out")) 348 { 349 continue; 350 } 351 let file_type = entry 352 .file_type() 353 .map_err(|error| format!("unable to classify archive entry: {error}"))?; 354 if file_type.is_symlink() { 355 return Err(format!( 356 "{relative}: archive inventory traverses a symbolic link" 357 )); 358 } 359 if !file_type.is_dir() && !file_type.is_file() { 360 return Err(format!( 361 "{relative}: archive inventory path is not a regular file" 362 )); 363 } 364 paths.push(relative.clone()); 365 if file_type.is_dir() { 366 archive_paths(root, &path, paths)?; 367 } else { 368 validate_git_inventory_path(root, Path::new(&relative))?; 369 } 370 } 371 Ok(()) 372 } 373 374 fn repo_audit(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 375 global_source_audit(root, inventory, findings); 376 runtime_ownership_audit(root, inventory, findings); 377 runtime_guidance_audit(root, findings); 378 git_source_policy(root, inventory, findings); 379 native_runtime_boundary(root, findings); 380 } 381 382 fn global_source_audit(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 383 let required = [ 384 "README.md", 385 "NOTICE", 386 "CONTRIBUTING.md", 387 "SECURITY.md", 388 "LICENSE", 389 "LICENSES/GPL-3.0-only.txt", 390 "LICENSES/OFL-1.1.txt", 391 ]; 392 for required_path in required { 393 if !inventory.paths.iter().any(|path| path == required_path) { 394 findings.push(format!( 395 "{required_path}: required public repository file is missing" 396 )); 397 } 398 if read_text(root, required_path, findings).trim().is_empty() { 399 findings.push(format!( 400 "{required_path}: required public repository text is empty" 401 )); 402 } 403 } 404 for path in &inventory.paths { 405 let normalized = path.to_ascii_lowercase(); 406 if is_forbidden_documentation_or_workflow_path(&normalized) { 407 findings.push(format!("{path}: forbidden repository root")); 408 } 409 let symbolic_link = fs::symlink_metadata(root.join(path)) 410 .is_ok_and(|metadata| metadata.file_type().is_symlink()); 411 if symbolic_link { 412 findings.push(format!( 413 "{path}: symbolic links are not allowed in public sources" 414 )); 415 } 416 let generated_output = is_generated_output_path(&normalized); 417 if generated_output { 418 findings.push(format!( 419 "{path}: generated build output must not be source controlled" 420 )); 421 } 422 let secret_path = normalized 423 .split('/') 424 .any(|part| part == ".env" || part.starts_with(".env.")) 425 || [".pem", ".key", ".p12", ".pfx", ".jks", ".keystore", ".env"] 426 .iter() 427 .any(|suffix| normalized.ends_with(suffix)) 428 || normalized.contains("/credentials/"); 429 if secret_path { 430 findings.push(format!("{path}: credential or secret-shaped source path")); 431 } 432 // Output and secret-shaped paths fail by identity; do not inspect their contents. 433 if is_source_safety_text(path) && !symbolic_link && !generated_output && !secret_path { 434 let source = match bounded_no_follow_bytes(root, Path::new(path), 8 * 1024 * 1024) 435 .and_then(|bytes| { 436 String::from_utf8(bytes) 437 .map_err(|error| format!("invalid source UTF-8: {error}")) 438 }) { 439 Ok(source) => source, 440 Err(error) => { 441 findings.push(format!("{path}: unable to inspect source text: {error}")); 442 continue; 443 } 444 }; 445 let markers = [ 446 ["-----BEGIN ", "PRIVATE KEY-----"].concat(), 447 ["AWS_", "SECRET_ACCESS_KEY="].concat(), 448 ["gh", "p_"].concat(), 449 ["sk_", "live_"].concat(), 450 ]; 451 if markers.iter().any(|marker| source.contains(marker)) { 452 findings.push(format!( 453 "{path}: credential or private-key material in source text" 454 )); 455 } 456 } 457 } 458 } 459 460 fn is_web_output_path(path: &str) -> bool { 461 path.starts_with("web/") 462 && (path.split('/').any(|part| part == "node_modules") 463 || matches!( 464 path.split('/').nth(1), 465 Some(".svelte-kit" | "build" | "coverage" | "test-results" | "playwright-report") 466 )) 467 } 468 469 fn is_generated_output_path(path: &str) -> bool { 470 path.split('/') 471 .any(|part| matches!(part, "node_modules" | ".svelte-kit" | "build" | "target")) 472 || is_web_output_path(path) 473 || path.contains("/generated/") 474 || path.contains("generated/uniffi") 475 || [".dylib", ".so", ".dll", ".class", ".wasm", ".node"] 476 .iter() 477 .any(|suffix| path.ends_with(suffix)) 478 } 479 480 fn runtime_ownership_audit(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 481 let result = load_ownership(root).and_then(|map| map.validate_native_inputs(&inventory.paths)); 482 if let Err(error) = result { 483 findings.push(format!("{}: {error}", runtime_ownership::MAP_PATH)); 484 } 485 } 486 487 fn load_ownership(root: &Path) -> Result<runtime_ownership::OwnershipMap, String> { 488 bounded_no_follow_bytes(root, Path::new(runtime_ownership::MAP_PATH), 64 * 1024) 489 .and_then(|bytes| { 490 String::from_utf8(bytes).map_err(|error| format!("invalid ownership UTF-8: {error}")) 491 }) 492 .and_then(|source| runtime_ownership::OwnershipMap::parse(&source)) 493 } 494 495 // These small text contracts guard instruction scope, not runtime ownership or 496 // product implementation. Keep the existing native/source checks independent. 497 fn runtime_guidance_audit(root: &Path, findings: &mut Vec<String>) { 498 let contracts: &[(&str, &[&str])] = &[ 499 ( 500 "AGENTS.md", 501 &[ 502 "public HarvestCircle product with separate native and browser runtimes", 503 "## Common application and security boundaries", 504 "## Native runtime boundaries", 505 "native storage, OS custody, transport, and ABI rules below apply only to the native runtime", 506 "SQLx is the only high-level SQLite library.", 507 "schema v3, storage API v3, FFI v4.5, snapshot v1, custody, and the exact Radroots source pin remain unchanged", 508 "Private keys and signing operations remain behind the generated native boundary.", 509 "platform/ABI", 510 "must not depend on private parent code", 511 "All `docs/**`, `spec/**`, `.github/**`, and `.act/**` paths are forbidden here.", 512 "HCAV-021 and later desktop availability work remain paused", 513 "do not wire browser dependencies into native commands or require native tools for ordinary browser install, check, or build", 514 ], 515 ), 516 ( 517 "web/AGENTS.md", 518 &[ 519 "instructions apply only to `web/**`", 520 "guidance alone is not an implemented application or a passing qualification", 521 "Browser persistence uses bounded IndexedDB", 522 "desktop SQLx database, operating-system keyring, and UniFFI implementation", 523 "Identity and signing require explicit extension interaction", 524 "Generic Nostr belongs in `src/lib/nostr`, using qualified Applesauce", 525 "WASM launch dependency", 526 "dependency on parent documentation", 527 "Do not introduce `docs/**`, `spec/**`, `.github/**`, or `.act/**` anywhere in this standalone repository.", 528 "do not invent commands or claim an absent web suite passed", 529 ], 530 ), 531 ]; 532 for (path, markers) in contracts { 533 let source = match bounded_no_follow_bytes(root, Path::new(path), 64 * 1024) 534 .and_then(|bytes| String::from_utf8(bytes).map_err(|error| error.to_string())) 535 { 536 Ok(source) => source, 537 Err(error) => { 538 findings.push(format!("{path}: unable to read runtime guidance: {error}")); 539 continue; 540 } 541 }; 542 let text = source.split_whitespace().collect::<Vec<_>>().join(" "); 543 for marker in *markers { 544 if !text.contains(marker) { 545 findings.push(format!( 546 "{path}: required runtime guidance is missing: {marker}" 547 )); 548 } 549 } 550 } 551 } 552 553 fn native_runtime_boundary(root: &Path, findings: &mut Vec<String>) { 554 if root 555 .join("core/crates/harvestcircle_domain/src/relay.rs") 556 .exists() 557 || read_text( 558 root, 559 "core/crates/harvestcircle_domain/src/lib.rs", 560 findings, 561 ) 562 .contains("mod relay") 563 { 564 findings 565 .push("harvestcircle_domain: duplicate relay policy surface is forbidden".to_owned()); 566 } 567 568 let nostr_manifest = read_text(root, "core/crates/harvestcircle_nostr/Cargo.toml", findings); 569 let production_manifest = nostr_manifest 570 .split_once("[dev-dependencies]") 571 .map_or(nostr_manifest.as_str(), |(production, _)| production); 572 if production_manifest.contains("nostr-sdk") { 573 findings.push( 574 "harvestcircle_nostr: production nostr-sdk connection authority is forbidden" 575 .to_owned(), 576 ); 577 } 578 let nostr_client = read_text( 579 root, 580 "core/crates/harvestcircle_nostr/src/client.rs", 581 findings, 582 ); 583 for required in [ 584 "radroots_transport_nostr::{Config, NostrTransport, RelayEndpoint, RelayProfile}", 585 "parse_verified_kind0", 586 "FetchBounds::new(MAX_PROFILE_EVENTS_PER_FETCH", 587 ] { 588 if !nostr_client.contains(required) { 589 findings.push(format!( 590 "harvestcircle_nostr: governed transport boundary is missing {required}" 591 )); 592 } 593 } 594 595 for (path, forbidden) in [ 596 ("core/crates/harvestcircle_ffi/src/commands.rs", "OnceLock"), 597 ( 598 "core/crates/harvestcircle_ffi/src/commands.rs", 599 "PoisonError::into_inner", 600 ), 601 ( 602 "core/crates/harvestcircle_ffi/src/observer.rs", 603 "PoisonError::into_inner", 604 ), 605 ( 606 "core/crates/harvestcircle_application/src/app_core.rs", 607 "PoisonError::into_inner", 608 ), 609 ( 610 "core/crates/harvestcircle_application/src/custody.rs", 611 "PoisonError::into_inner", 612 ), 613 ( 614 "core/crates/harvestcircle_application/src/secrets.rs", 615 "PoisonError::into_inner", 616 ), 617 ] { 618 if read_text(root, path, findings).contains(forbidden) { 619 findings.push(format!("{path}: forbidden runtime boundary {forbidden}")); 620 } 621 } 622 623 let runtime = read_text( 624 root, 625 "core/crates/harvestcircle_ffi/src/host_runtime.rs", 626 findings, 627 ); 628 let keyring = read_text( 629 root, 630 "core/crates/harvestcircle_ffi/src/keyring_worker.rs", 631 findings, 632 ); 633 for (source, required, owner) in [ 634 (&runtime, "pub(crate) struct HostRuntime", "host runtime"), 635 (&runtime, "pub(crate) async fn shutdown", "host runtime"), 636 ( 637 &keyring, 638 "const KEYRING_QUEUE_CAPACITY: usize = 8", 639 "keyring worker", 640 ), 641 ( 642 &keyring, 643 "pub(crate) struct BoundedKeyringWorker", 644 "keyring worker", 645 ), 646 ( 647 &keyring, 648 "use tokio::sync::{oneshot, watch}", 649 "keyring worker", 650 ), 651 (&keyring, "response_receiver.await", "keyring worker"), 652 ( 653 &keyring, 654 "const KEYRING_SHUTDOWN_DEADLINE: Duration = Duration::from_secs(30)", 655 "keyring worker", 656 ), 657 (&keyring, "OPERATION_QUEUED", "keyring worker"), 658 (&keyring, "OPERATION_STARTED", "keyring worker"), 659 (&keyring, "OPERATION_COMPLETED", "keyring worker"), 660 (&keyring, "OPERATION_CANCELLED", "keyring worker"), 661 ] { 662 if !source.contains(required) { 663 findings.push(format!( 664 "harvestcircle_ffi: {owner} contract is missing {required}" 665 )); 666 } 667 } 668 if keyring.contains("response_receiver.recv") { 669 findings 670 .push("harvestcircle_ffi: keyring response blocks a Tokio runtime thread".to_owned()); 671 } 672 if keyring.contains("std::sync::mpsc::Receiver") { 673 findings.push("harvestcircle_ffi: keyring response exposes a blocking receiver".to_owned()); 674 } 675 let native_keyring = read_text( 676 root, 677 "core/crates/harvestcircle_storage/src/os_keyring.rs", 678 findings, 679 ); 680 let native_verify = native_keyring 681 .split_once(" fn verify<'a>(") 682 .and_then(|(_, source)| source.split_once("\n fn load(")) 683 .map(|(body, _)| body) 684 .unwrap_or_default(); 685 for required in [ 686 "request_id: &'a DurableRequestId", 687 "secret: SecretKeyInput", 688 "self.operation()?", 689 "Zeroizing::new(platform_read(&account).map_err(map_read_error)?)", 690 "verify_replay_binding(request_id, &secret, encoded.as_slice())", 691 ] { 692 if !native_verify.contains(required) { 693 findings.push(format!( 694 "harvestcircle_storage: read-only verification is missing {required}" 695 )); 696 } 697 } 698 for forbidden in ["platform_create(", "platform_delete(", ".put(", ".delete("] { 699 if native_verify.contains(forbidden) { 700 findings.push(format!( 701 "harvestcircle_storage: verification mutates custody through {forbidden}" 702 )); 703 } 704 } 705 let worker_verify = keyring 706 .split_once("Request::Verify(request_id, public_key, secret, phase, response) => {") 707 .and_then(|(_, source)| source.split_once("Request::Load(")) 708 .map(|(body, _)| body) 709 .unwrap_or_default(); 710 for required in [ 711 "start_operation(&phase)", 712 "store.verify(&request_id, public_key, secret).await", 713 "finish_operation(&phase)", 714 "response.send(result)", 715 ] { 716 if !worker_verify.contains(required) { 717 findings.push(format!( 718 "harvestcircle_ffi: verification lifecycle is missing {required}" 719 )); 720 } 721 } 722 let worker_submit = keyring 723 .split_once(" fn verify<'a>(") 724 .and_then(|(_, source)| source.split_once("\n fn load(")) 725 .map(|(body, _)| body) 726 .unwrap_or_default(); 727 if !worker_submit.contains("self.submit(|phase, response|") 728 || !worker_submit 729 .contains("Request::Verify(request_id.clone(), public_key, secret, phase, response)") 730 || worker_submit.contains("Request::Put(") 731 { 732 findings.push( 733 "harvestcircle_ffi: verification bypasses the bounded read-only worker submission" 734 .to_owned(), 735 ); 736 } 737 } 738 739 fn namespace_audit(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 740 let legacy = ["stu", "dio"].concat(); 741 let temporary_namespace = ["org", "radroots", "harvestcircle"].join("."); 742 let inherited_preferences = [ 743 ["use", "radroots", "dns"].join("_"), 744 ["use", "radroots", "subnets"].join("_"), 745 ["vpn", "on", "demand", "enabled"].join("_"), 746 ["run", "as", "exit", "node"].join("_"), 747 ["automatically", "check", "for", "updates"].join("_"), 748 ["update", "channel"].join("_"), 749 ["last", "update", "check", "summary"].join("_"), 750 ["alternate", "server", "url"].join("_"), 751 ]; 752 for path in &inventory.paths { 753 let normalized = path.to_ascii_lowercase(); 754 if normalized.contains(&legacy) { 755 findings.push(format!("{path}: legacy product name in source path")); 756 } 757 if normalized.starts_with("app/") 758 && normalized.contains("/kotlin/") 759 && normalized.ends_with(".kt") 760 { 761 let package_path = normalized 762 .split_once("/kotlin/") 763 .map(|(_, value)| value) 764 .unwrap_or_default(); 765 if !package_path.starts_with("org/harvestcircle/") { 766 findings.push(format!( 767 "{path}: Kotlin source is outside the final namespace" 768 )); 769 } 770 } 771 if !is_text(path) { 772 continue; 773 } 774 let source = read_text(root, path, findings); 775 if source.to_ascii_lowercase().contains(&legacy) { 776 findings.push(format!("{path}: legacy product name in source text")); 777 } 778 if source.contains(&temporary_namespace) 779 || source.contains(&temporary_namespace.replace('.', "/")) 780 { 781 findings.push(format!("{path}: temporary product namespace")); 782 } 783 let production_kotlin = path.ends_with(".kt") 784 && path.starts_with("app/") 785 && ["/src/main/", "/src/commonMain/", "/src/desktopMain/"] 786 .iter() 787 .any(|segment| path.contains(segment)); 788 let bounded_health = path 789 == "app/desktop/src/main/kotlin/org/harvestcircle/desktop/Main.kt" 790 && source.contains("HEALTH_CHECK_ARGUMENT") 791 && source.contains("withTimeout(HEALTH_TIMEOUT_MILLIS)"); 792 if production_kotlin && source.contains(&["run", "Blocking"].concat()) && !bounded_health { 793 findings.push(format!( 794 "{path}: blocking coroutine bridge in application source" 795 )); 796 } 797 if production_kotlin 798 && (source.contains(&["Atomic", "Long"].concat()) 799 || source.contains(&["desktop", "-operation:"].concat())) 800 { 801 findings.push(format!("{path}: process-local operation counter")); 802 } 803 if path.starts_with("app/shared/src/commonMain/") 804 && [ 805 ["org.harvestcircle.", "ffi"].concat(), 806 ["com.sun.", "jna"].concat(), 807 "java.".to_owned(), 808 "javax.".to_owned(), 809 ] 810 .iter() 811 .any(|marker| source.contains(marker)) 812 { 813 findings.push(format!( 814 "{path}: platform dependency in shared common source" 815 )); 816 } 817 let lowercase = source.to_ascii_lowercase(); 818 for token in &inherited_preferences { 819 if lowercase.contains(token) { 820 findings.push(format!("{path}: inherited non-product preference {token}")); 821 } 822 } 823 let secret_marker = ["nsec", "1"].concat(); 824 let inspected_secret = lowercase.replace(&format!("{secret_marker}…"), ""); 825 if production_kotlin && inspected_secret.contains(&secret_marker) { 826 findings.push(format!("{path}: secret key literal in production Kotlin")); 827 } 828 } 829 } 830 831 fn product_shell_audit(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 832 let required = [ 833 "app/shared/src/commonMain/kotlin/org/harvestcircle/product/SurfaceRegistry.kt", 834 "app/shared/src/commonMain/kotlin/org/harvestcircle/navigation/Navigation.kt", 835 "app/shared/src/commonMain/kotlin/org/harvestcircle/appearance/AppearanceState.kt", 836 "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/theme/HarvestCircleTheme.kt", 837 "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/component/action/HarvestCircleButton.kt", 838 "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/component/feedback/HarvestCircleBadge.kt", 839 "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/layout/HarvestCircleAppFrame.kt", 840 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/HarvestCircleShell.kt", 841 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationTodayScreen.kt", 842 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationNetworkScreen.kt", 843 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationSettingsScreen.kt", 844 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/ShellAccessibility.kt", 845 ]; 846 for path in required { 847 if !inventory.paths.iter().any(|candidate| candidate == path) { 848 findings.push(format!("{path}: required product-shell source is missing")); 849 } 850 } 851 let regression_matrix: &[(&str, &[&str])] = &[ 852 ( 853 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/HarvestCirclePresenterTest.kt", 854 &["hcSc001", "hcSc002"], 855 ), 856 ( 857 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/HarvestCircleShellPresenterTest.kt", 858 &["hcSc003", "HcSc004"], 859 ), 860 ( 861 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/ReferenceInputPolicyTest.kt", 862 &["hcSc005", "hcSc006", "hcSc007"], 863 ), 864 ( 865 "app/design_system/src/commonTest/kotlin/org/harvestcircle/designsystem/theme/HarvestCircleColorContrastTest.kt", 866 &["hcSc008", "hcSc009"], 867 ), 868 ( 869 "app/shared/src/desktopTest/kotlin/org/harvestcircle/ui/shell/OwnedControlsUiTest.kt", 870 &["hcSc010"], 871 ), 872 ( 873 "app/shared/src/desktopTest/kotlin/org/harvestcircle/ui/shell/ShellAccessibilityUiTest.kt", 874 &["hcSc011"], 875 ), 876 ( 877 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/ShellOverlaysTest.kt", 878 &["hcSc012", "hcSl001", "hcSl006"], 879 ), 880 ( 881 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/ReferenceInputPolicyTest.kt", 882 &["hcSl001"], 883 ), 884 ( 885 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/HarvestCirclePresenterTest.kt", 886 &[ 887 "hcSl002", "hcSl003", "hcSl004", "hcSl005", "hcEx001", "hcEx002", "hcEx003", 888 ], 889 ), 890 ( 891 "app/shared/src/desktopTest/kotlin/org/harvestcircle/ui/shell/BootstrapIdentityEntryTest.kt", 892 &["hcEx004"], 893 ), 894 ( 895 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/HarvestCircleShellPresenterTest.kt", 896 &["hcSl001", "hcSl006"], 897 ), 898 ( 899 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/ImportSecretDraftTest.kt", 900 &["hcSl005"], 901 ), 902 ( 903 "app/shared/src/desktopTest/kotlin/org/harvestcircle/ui/shell/FoundationOverlayHostTest.kt", 904 &["hcSl006"], 905 ), 906 ]; 907 for (path, markers) in regression_matrix { 908 let source = read_text(root, path, findings); 909 for marker in *markers { 910 if !source.contains(marker) { 911 findings.push(format!( 912 "{path}: required shell-security regression marker is missing: {marker}" 913 )); 914 } 915 } 916 } 917 let closure_source_contract: &[(&str, &[&str])] = &[ 918 ( 919 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/ReferenceInputPolicy.kt", 920 &["data object AmbiguousHex", "hasAmbiguousHexShape"], 921 ), 922 ( 923 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/ImportSecretDraft.kt", 924 &[ 925 "class ImportSecretDraft private constructor", 926 "private var characters: CharArray?", 927 ], 928 ), 929 ( 930 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/PresentationModels.kt", 931 &[ 932 "val importDraft: ImportSecretDraft", 933 "class EditImportDraft private constructor", 934 ], 935 ), 936 ( 937 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/HarvestCirclePresenter.kt", 938 &[ 939 "PendingRemovalLease", 940 "removalMutex", 941 "expireRemovalLease", 942 "releaseClaimedRemoval", 943 "PresenterClosePhase.TransferredToShutdown", 944 "ImportSecretDraft", 945 ], 946 ), 947 ( 948 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/ShellOverlays.kt", 949 &["ReferenceInputAdmission.AmbiguousHex"], 950 ), 951 ( 952 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationOverlayHost.kt", 953 &["val overlayBusy = (overlay as? FoundationOverlay.ConfirmAction)?.busy == true"], 954 ), 955 ( 956 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/BootstrapIdentityEntry.kt", 957 &[ 958 "The secret is held only for this import.", 959 "It is cleared after it is sent to the local native runtime.", 960 ], 961 ), 962 ]; 963 for (path, markers) in closure_source_contract { 964 let source = read_text(root, path, findings); 965 for marker in *markers { 966 if !source.contains(marker) { 967 findings.push(format!( 968 "{path}: required secret-lifecycle closure source marker is missing: {marker}" 969 )); 970 } 971 } 972 } 973 let presenter_tests = read_text( 974 root, 975 "app/shared/src/commonTest/kotlin/org/harvestcircle/application/HarvestCirclePresenterTest.kt", 976 findings, 977 ); 978 for forbidden in ["Thread.sleep", "kotlinx.coroutines.delay("] { 979 if presenter_tests.contains(forbidden) { 980 findings.push(format!( 981 "automatic-expiry tests must use virtual time, not {forbidden}" 982 )); 983 } 984 } 985 let bootstrap_entry = read_text( 986 root, 987 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/BootstrapIdentityEntry.kt", 988 findings, 989 ); 990 let retired_copy = [ 991 "The secret is sent directly to the local native runtime ", 992 "and is not retained in the interface.", 993 ] 994 .concat(); 995 if bootstrap_entry.contains(&retired_copy) { 996 findings.push("Bootstrap identity entry retains retired secret-custody copy".to_owned()); 997 } 998 let locked_copy = [ 999 ( 1000 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/HarvestCircleShell.kt", 1001 &[ 1002 "Coordinate local food with clear, signed terms.", 1003 "You do not need a HarvestCircle account.", 1004 "Open source · Nostr-based · No managed service required", 1005 ][..], 1006 ), 1007 ( 1008 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationTodayScreen.kt", 1009 &[ 1010 "No active commitments", 1011 "Explore nearby buying circles or open a shared Nostr reference.", 1012 "Not available in this build.", 1013 ][..], 1014 ), 1015 ( 1016 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationNetworkScreen.kt", 1017 &[ 1018 "Overview", 1019 "Identity", 1020 "Public relays", 1021 "Runtime", 1022 "No managed HarvestCircle service is configured.", 1023 ][..], 1024 ), 1025 ( 1026 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationSettingsScreen.kt", 1027 &[ 1028 "Appearance", 1029 "Project", 1030 "Theme", 1031 "Text size", 1032 "Motion", 1033 "FFI contract", 1034 "Storage schema", 1035 ][..], 1036 ), 1037 ]; 1038 for (path, expected) in locked_copy { 1039 let source = read_text(root, path, findings); 1040 for text in expected { 1041 if !source.contains(text) { 1042 findings.push(format!( 1043 "{path}: locked product-shell copy is missing: {text}" 1044 )); 1045 } 1046 } 1047 } 1048 for path in &inventory.paths { 1049 if !is_production_kotlin(path) { 1050 continue; 1051 } 1052 let source = read_text(root, path, findings); 1053 let normalized_path = path.to_ascii_lowercase(); 1054 let compact = source 1055 .chars() 1056 .filter(|character| !character.is_whitespace()) 1057 .collect::<String>(); 1058 for (shape, diagnostic) in [ 1059 ("funShellText(", "superseded shell text adapter"), 1060 ("funShellButton(", "superseded shell button adapter"), 1061 ("funShellTextField(", "superseded shell field adapter"), 1062 ( 1063 "enumclassShellTextRole", 1064 "superseded shell text-role adapter", 1065 ), 1066 ( 1067 "enumclassShellButtonKind", 1068 "superseded shell button-kind adapter", 1069 ), 1070 ] { 1071 if compact.contains(shape) { 1072 findings.push(format!("{path}: {diagnostic}")); 1073 } 1074 } 1075 if source.contains("androidx.compose.material") { 1076 findings.push(format!( 1077 "{path}: Material component dependency is forbidden" 1078 )); 1079 } 1080 for (shape, diagnostic) in [ 1081 ( 1082 "dataobjectConfirmIdentityRemoval", 1083 "retired parameterless confirmation source shape", 1084 ), 1085 ( 1086 "dataobjectCancelIdentityRemoval", 1087 "retired parameterless confirmation source shape", 1088 ), 1089 ( 1090 "isOverlayIntent.EditReference->classifyNostrReference(", 1091 "parser-on-edit source shape", 1092 ), 1093 ( 1094 "OverlayIntent.Open(FoundationOverlay.OpenNostrReference(", 1095 "prefilled reference ingress source shape", 1096 ), 1097 ( 1098 "selected=true,enabled=false", 1099 "selected-as-disabled source shape", 1100 ), 1101 ( 1102 "valimportDraft:String", 1103 "raw String import-draft custody source shape", 1104 ), 1105 ( 1106 "dataclassEditImportDraft", 1107 "copyable import-draft intent source shape", 1108 ), 1109 ] { 1110 if compact.contains(shape) { 1111 findings.push(format!("{path}: {diagnostic}")); 1112 } 1113 } 1114 if path 1115 == "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationOverlayHost.kt" 1116 && compact.contains( 1117 "funFoundationOverlayHost(state:OverlayState,status:ShellStatusModel,busy:Boolean", 1118 ) 1119 { 1120 findings.push(format!( 1121 "{path}: global busy state must not enter the overlay host" 1122 )); 1123 } 1124 if path == "app/shared/src/commonMain/kotlin/org/harvestcircle/application/ShellOverlays.kt" 1125 && compact.contains("state.identity.busy") 1126 { 1127 findings.push(format!( 1128 "{path}: unrelated identity busy state must not gate overlay admission" 1129 )); 1130 } 1131 if normalized_path.ends_with("/harvestcirclescreen.kt") { 1132 findings.push(format!("{path}: superseded product-shell screen path")); 1133 } 1134 for marker in [ 1135 "home-screen", 1136 "inactive-identities", 1137 "WindowBackgroundColor", 1138 "ButtonBackgroundColor", 1139 "InputBackgroundColor", 1140 ] { 1141 if source.contains(marker) { 1142 findings.push(format!("{path}: superseded product-shell marker {marker}")); 1143 } 1144 } 1145 if is_production_compose(path, &source) 1146 && source.contains("focusRing: HarvestCircleFocusRing = HarvestCircleFocusRing.None") 1147 { 1148 findings.push(format!( 1149 "{path}: interactive control defaults to a hidden keyboard focus ring" 1150 )); 1151 } 1152 let approved_color_adapter = path.starts_with( 1153 "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/theme/color/", 1154 ) || path 1155 == "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/shell/HarvestCircleShellVisuals.kt"; 1156 if is_production_compose(path, &source) 1157 && !approved_color_adapter 1158 && contains_direct_call(&compact, "Color(") 1159 { 1160 findings.push(format!( 1161 "{path}: hard-coded Compose color outside the theme adapter" 1162 )); 1163 } 1164 let approved_text_primitive = matches!( 1165 path.as_str(), 1166 "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/primitive/HarvestCircleText.kt" 1167 | "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/shell/HarvestCircleShellText.kt" 1168 ); 1169 let approved_input_primitive = matches!( 1170 path.as_str(), 1171 "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/component/input/HarvestCircleTextField.kt" 1172 | "app/design_system/src/commonMain/kotlin/org/harvestcircle/designsystem/shell/HarvestCircleShellControls.kt" 1173 ); 1174 if is_production_compose(path, &source) { 1175 if !approved_text_primitive && contains_direct_call(&compact, "BasicText(") { 1176 findings.push(format!( 1177 "{path}: BasicText bypasses the shell primitive adapter" 1178 )); 1179 } 1180 if !approved_input_primitive && contains_direct_call(&compact, "BasicTextField(") { 1181 findings.push(format!( 1182 "{path}: BasicTextField bypasses the shell primitive adapter" 1183 )); 1184 } 1185 } 1186 let lowercase = source.to_ascii_lowercase(); 1187 for marker in [ 1188 "sample farm", 1189 "sample commitment", 1190 "sample price", 1191 "sample event", 1192 "fake farm", 1193 "fake commitment", 1194 "pricecents", 1195 "commitmentid", 1196 "allocationid", 1197 "fulfillmentid", 1198 ] { 1199 if lowercase.contains(marker) { 1200 findings.push(format!( 1201 "{path}: fake commercial product data marker {marker}" 1202 )); 1203 } 1204 } 1205 } 1206 for forbidden in [ 1207 "app/shared/src/commonMain/kotlin/org/harvestcircle/design/HarvestCircleDesign.kt", 1208 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/ShellControls.kt", 1209 ] { 1210 if inventory.paths.iter().any(|path| path == forbidden) { 1211 findings.push(format!( 1212 "{forbidden}: superseded product-shell authority returned" 1213 )); 1214 } 1215 } 1216 } 1217 1218 fn is_forbidden_documentation_or_workflow_path(path: &str) -> bool { 1219 path.split('/').any(|part| { 1220 matches!( 1221 part, 1222 "doc" | "docs" | "spec" | "specs" | ".github" | ".act" | "workflow" | "workflows" 1223 ) 1224 }) 1225 } 1226 1227 fn is_production_kotlin(path: &str) -> bool { 1228 path.starts_with("app/") 1229 && path.ends_with(".kt") 1230 && ["/src/main/", "/src/commonMain/", "/src/desktopMain/"] 1231 .iter() 1232 .any(|segment| path.contains(segment)) 1233 } 1234 1235 fn is_production_compose(path: &str, source: &str) -> bool { 1236 is_production_kotlin(path) 1237 && (source.contains("@Composable") || source.contains("androidx.compose.")) 1238 } 1239 1240 fn contains_direct_call(source: &str, call: &str) -> bool { 1241 source.match_indices(call).any(|(index, _)| { 1242 source[..index] 1243 .chars() 1244 .next_back() 1245 .is_none_or(|character| !character.is_ascii_alphanumeric() && character != '_') 1246 }) 1247 } 1248 1249 fn manifest_declares_dependency(source: &str, dependency: &str) -> bool { 1250 source.lines().map(str::trim).any(|line| { 1251 if line.is_empty() || line.starts_with('#') { 1252 return false; 1253 } 1254 if line 1255 .split_once('=') 1256 .is_some_and(|(key, _)| key.trim().trim_matches('"') == dependency) 1257 { 1258 return true; 1259 } 1260 line.strip_prefix('[') 1261 .and_then(|value| value.strip_suffix(']')) 1262 .is_some_and(|table| { 1263 let segments = table.split('.').collect::<Vec<_>>(); 1264 segments.contains(&"dependencies") 1265 && segments 1266 .last() 1267 .is_some_and(|name| name.trim_matches('"') == dependency) 1268 }) 1269 }) 1270 } 1271 1272 fn sqlite_dependency_topology(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 1273 let cargo_lock = read_text(root, "core/Cargo.lock", findings); 1274 let package_count = |name: &str| { 1275 let marker = format!("name = \"{name}\""); 1276 cargo_lock 1277 .lines() 1278 .filter(|line| line.trim() == marker) 1279 .count() 1280 }; 1281 if package_count("libsqlite3-sys") != 1 1282 || ["rusqlite", "refinery", "refinery-core", "refinery-macros"] 1283 .iter() 1284 .any(|name| package_count(name) != 0) 1285 { 1286 findings.push( 1287 "core/Cargo.lock: exact single SQLx-selected native SQLite topology changed".to_owned(), 1288 ); 1289 } 1290 1291 for path in inventory 1292 .paths 1293 .iter() 1294 .filter(|path| path.starts_with("core/") && path.ends_with("Cargo.toml")) 1295 { 1296 let manifest = read_text(root, path, findings); 1297 if ["rusqlite", "refinery", "libsqlite3-sys"] 1298 .iter() 1299 .any(|dependency| manifest_declares_dependency(&manifest, dependency)) 1300 { 1301 findings.push(format!( 1302 "{path}: direct alternate or native SQLite dependency is forbidden" 1303 )); 1304 } 1305 } 1306 } 1307 1308 fn development_integration_policy(root: &Path, findings: &mut Vec<String>) { 1309 let makefile = read_text(root, "Makefile", findings); 1310 for required in [ 1311 "override CARGO := cargo +1.99.0", 1312 "api-check: doctor", 1313 "development-check: development-provenance-check source-check integration-check", 1314 "governed-development-check:", 1315 "governed-linux-x86_64-development-check: governed-doctor", 1316 ] { 1317 if makefile 1318 .lines() 1319 .filter(|line| line.trim() == required) 1320 .count() 1321 != 1 1322 { 1323 findings.push(format!( 1324 "Makefile: development integration boundary is missing {required}" 1325 )); 1326 } 1327 } 1328 1329 let runner = read_text( 1330 root, 1331 "tools/run-linux-x86_64-development-check.sh", 1332 findings, 1333 ); 1334 for required in [ 1335 "rust:1.99.0-slim-trixie@sha256:2752b332db73fdbb7dc576f06c82ed1f312005784ef913d7e04a28f5f55dc581", 1336 "--platform linux/amd64", 1337 "EXT_BUILD_RUN_ACTIVE", 1338 "--env JAVA_TOOL_OPTIONS=-Duser.home=/workspace/home", 1339 "cargo deny --manifest-path core/Cargo.toml check --config core/deny.toml licenses sources", 1340 "cargo test --manifest-path core/Cargo.toml --workspace --locked", 1341 "cargo clippy --manifest-path core/Cargo.toml --workspace --all-targets --locked -- -D warnings", 1342 ":app:desktop:integrationTest", 1343 ":app:desktop:verifyUniFfiBindings", 1344 "harvestcircle.linux_x86_64.development=pass", 1345 ] { 1346 if !runner.contains(required) { 1347 findings.push(format!( 1348 "tools/run-linux-x86_64-development-check.sh: faithful runner is missing {required}" 1349 )); 1350 } 1351 } 1352 for forbidden in [ 1353 "cargo audit", 1354 " advisories", 1355 "dependencyCheck", 1356 "releaseReadiness", 1357 "unsignedReleaseReadiness", 1358 "verifyReleaseSupplyChainEvidence", 1359 "packageDmg", 1360 "packageDeb", 1361 "CycloneDX", 1362 "SLSA", 1363 ] { 1364 if runner.contains(forbidden) { 1365 findings.push(format!( 1366 "tools/run-linux-x86_64-development-check.sh: deferred release integration is active: {forbidden}" 1367 )); 1368 } 1369 } 1370 } 1371 1372 fn provenance_check(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 1373 const LIB_REVISION: &str = "189c49b74b4bafc142b00b76b296477931139e72"; 1374 const PROVENANCE_PATH: &str = "core/provenance/harvestcircle-v1.toml"; 1375 const SOURCE_LOCK_PATH: &str = "radroots.lib.source-lock.v1.toml"; 1376 const MAX_SOURCE_LOCK_BYTES: u64 = 1024 * 1024; 1377 const MAX_CARGO_LOCK_BYTES: u64 = 32 * 1024 * 1024; 1378 let cargo = read_text(root, "core/Cargo.toml", findings); 1379 for authority in [ 1380 "repository = \"https://github.com/radrootslabs/harvestcircle\"".to_owned(), 1381 format!( 1382 "radroots_event = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1383 ), 1384 format!( 1385 "radroots_event_codec = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1386 ), 1387 format!( 1388 "radroots_identity = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1389 ), 1390 format!( 1391 "radroots_runtime_paths = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1392 ), 1393 format!( 1394 "radroots_service_sqlite = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1395 ), 1396 format!( 1397 "radroots_storage = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1398 ), 1399 format!( 1400 "radroots_transport = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1401 ), 1402 format!( 1403 "radroots_transport_nostr = {{ git = \"https://github.com/radrootslabs/lib\", rev = \"{LIB_REVISION}\", version = \"=0.1.0-alpha\", default-features = false }}" 1404 ), 1405 ] { 1406 if cargo 1407 .lines() 1408 .filter(|line| line.trim() == authority) 1409 .count() 1410 != 1 1411 { 1412 findings.push(format!( 1413 "core/Cargo.toml: missing exact authority: {authority}" 1414 )); 1415 } 1416 } 1417 let provenance = read_text(root, PROVENANCE_PATH, findings); 1418 if !provenance.contains("source_product = \"HarvestCircle\"") 1419 || !provenance 1420 .contains("source_repository = \"https://github.com/radrootslabs/harvestcircle\"") 1421 || !provenance.contains(&format!("canonical_radroots_revision = \"{LIB_REVISION}\"")) 1422 || !provenance 1423 .contains("foundation_baseline = \"c08d18ea569351dddeef70d4c1410708daf067b6\"") 1424 { 1425 findings.push(format!( 1426 "{PROVENANCE_PATH}: exact source provenance changed" 1427 )); 1428 } 1429 let expected_source_lock = concat!( 1430 "schema = \"radroots.lib.source-lock.v1\"\n", 1431 "repository = \"https://github.com/radrootslabs/lib\"\n", 1432 "revision = \"189c49b74b4bafc142b00b76b296477931139e72\"\n", 1433 "architecture = \"radroots.crates.release.v2\"\n", 1434 "workspace_catalog_sha256 = \"ee295f2352e2577a4052d980624415aec9871197d4fc9910a4c21c83a9179200\"\n", 1435 "version = \"0.1.0-alpha\"\n", 1436 "source_archive_sha256 = \"c648a3ab993d10253b9073e7e86db7b8970863bdf1d394d9fc30d66825695240\"\n", 1437 "lockfile = \"core/Cargo.lock\"\n", 1438 "lockfile_sha256 = \"b57fae5737cc9401d38f464c019b07d10c48c13ebcc9c9ac8593fe0fa61ffae8\"\n", 1439 ); 1440 let source_lock_bytes = 1441 match bounded_no_follow_bytes(root, Path::new(SOURCE_LOCK_PATH), MAX_SOURCE_LOCK_BYTES) { 1442 Ok(bytes) => bytes, 1443 Err(error) => { 1444 findings.push(format!("{SOURCE_LOCK_PATH}: {error}")); 1445 Vec::new() 1446 } 1447 }; 1448 let source_lock = String::from_utf8(source_lock_bytes).unwrap_or_default(); 1449 if source_lock != expected_source_lock { 1450 findings.push(format!("{SOURCE_LOCK_PATH}: exact Lib source lock changed")); 1451 } 1452 let lockfile = exact_string_assignment(&source_lock, "lockfile"); 1453 let declared_lockfile_sha256 = exact_string_assignment(&source_lock, "lockfile_sha256"); 1454 let cargo_lock_bytes = lockfile 1455 .as_deref() 1456 .ok_or_else(|| "lockfile assignment is missing or duplicated".to_owned()) 1457 .and_then(|path| bounded_no_follow_bytes(root, Path::new(path), MAX_CARGO_LOCK_BYTES)); 1458 if let (Ok(bytes), Some(declared)) = (&cargo_lock_bytes, declared_lockfile_sha256.as_deref()) { 1459 let actual = format!("{:x}", Sha256::digest(bytes)); 1460 if actual != declared { 1461 findings.push(format!( 1462 "{SOURCE_LOCK_PATH}: lockfile_sha256 does not match actual bounded no-follow bytes" 1463 )); 1464 } 1465 } else { 1466 let error = cargo_lock_bytes 1467 .as_ref() 1468 .err() 1469 .map(String::as_str) 1470 .unwrap_or("lockfile_sha256 assignment is missing or duplicated"); 1471 findings.push(format!("{SOURCE_LOCK_PATH}: {error}")); 1472 } 1473 let cargo_lock = match cargo_lock_bytes { 1474 Ok(bytes) => match String::from_utf8(bytes) { 1475 Ok(source) => source, 1476 Err(error) => { 1477 findings.push(format!("core/Cargo.lock: invalid source UTF-8: {error}")); 1478 String::new() 1479 } 1480 }, 1481 Err(_) => String::new(), // The bounded-read failure was recorded above. 1482 }; 1483 if !cargo_lock.contains(&format!( 1484 "source = \"git+https://github.com/radrootslabs/lib?rev={LIB_REVISION}#{LIB_REVISION}\"" 1485 )) { 1486 findings.push("core/Cargo.lock: selected Lib revision is missing".to_owned()); 1487 } 1488 sqlite_dependency_topology(root, inventory, findings); 1489 development_integration_policy(root, findings); 1490 let coordinates = properties(&read_text( 1491 root, 1492 "config/product/harvestcircle-v1.properties", 1493 findings, 1494 )); 1495 for (key, expected) in [ 1496 ("storage.service_id", "harvestcircle"), 1497 ("storage.instance_id", "desktop"), 1498 ("storage.database_filename", "state.sqlite"), 1499 ("storage.lock_filename", "state.lock"), 1500 ("storage.application_id", "1212371505"), 1501 ("storage.application_id_text", "HCR1"), 1502 ("storage.initial_schema_version", "1"), 1503 ("legacy.database.filename", "harvestcircle.sqlite3"), 1504 ("legacy.database.disposition", "untouched_and_unsupported"), 1505 ("platform.macos.architecture", "aarch64"), 1506 ("platform.linux.architecture", "x86_64"), 1507 ("limit.identities", "256"), 1508 ("limit.unfinished_durable_operations", "1024"), 1509 ("limit.preference_value_utf8_bytes", "4096"), 1510 ("limit.relay_endpoints", "16"), 1511 ("limit.relay_url_bytes", "2048"), 1512 ("limit.events_per_relay", "64"), 1513 ("limit.events_total", "1024"), 1514 ("limit.observers", "32"), 1515 ("limit.actor_mailbox", "64"), 1516 ("limit.command_deadline_min_ms", "1"), 1517 ("limit.command_deadline_max_ms", "30000"), 1518 ("backup.member_limit", "caller_supplied_positive"), 1519 ] { 1520 if coordinates.get(key).map(String::as_str) != Some(expected) { 1521 findings.push(format!( 1522 "config/product/harvestcircle-v1.properties: {key} must remain {expected}" 1523 )); 1524 } 1525 } 1526 let uniffi = read_text(root, "core/crates/harvestcircle_ffi/uniffi.toml", findings); 1527 let ffi_package = coordinates 1528 .get("ffi.kotlin_package") 1529 .map(String::as_str) 1530 .unwrap_or_default(); 1531 let cdylib = coordinates 1532 .get("ffi.cdylib_name") 1533 .map(String::as_str) 1534 .unwrap_or_default(); 1535 if !uniffi.contains("[crates.harvestcircle_ffi.bindings.kotlin]") 1536 || !uniffi.contains(&format!("package_name = \"{ffi_package}\"")) 1537 || !uniffi.contains(&format!("cdylib_name = \"{cdylib}\"")) 1538 { 1539 findings.push( 1540 "core/crates/harvestcircle_ffi/uniffi.toml: final FFI identity changed".to_owned(), 1541 ); 1542 } 1543 let baseline = read_text( 1544 root, 1545 "core/compatibility/harvestcircle-ffi-v4.properties", 1546 findings, 1547 ); 1548 if !baseline.contains("contract.id=harvestcircle-desktop-ffi-v4") 1549 || !baseline.contains("contract.major=4") 1550 { 1551 findings.push( 1552 "core/compatibility/harvestcircle-ffi-v4.properties: FFI v4 identity changed" 1553 .to_owned(), 1554 ); 1555 } 1556 let shared_build = read_text(root, "app/shared/build.gradle.kts", findings); 1557 if !shared_build.contains("id(\"org.harvestcircle.build.kmp-shared\")") 1558 || ["androidTarget", "iosArm", "iosX", "js(", "wasm"] 1559 .iter() 1560 .any(|marker| shared_build.contains(marker)) 1561 { 1562 findings.push("app/shared/build.gradle.kts: shared KMP target boundary changed".to_owned()); 1563 } 1564 const STORAGE_API_BASELINE: &str = "core/compatibility/harvestcircle-storage-api-v3.txt"; 1565 let storage_api = read_text(root, STORAGE_API_BASELINE, findings); 1566 for required in [ 1567 "pub struct harvestcircle_storage::HarvestCircleStorageContract", 1568 "pub const harvestcircle_storage::HARVESTCIRCLE_APPLICATION_ID: u32", 1569 "pub fn harvestcircle_storage::harvestcircle_schema_catalog()", 1570 "pub struct harvestcircle_storage::Database", 1571 "pub async fn harvestcircle_storage::Database::open", 1572 "pub async fn harvestcircle_storage::Database::close", 1573 "pub async fn harvestcircle_storage::Database::retain_availability_version", 1574 "pub async fn harvestcircle_storage::Database::load_availability_version", 1575 "pub async fn harvestcircle_storage::Database::capture_online_backup", 1576 "pub async fn harvestcircle_storage::Database::restore_verified_backup", 1577 "pub struct harvestcircle_storage::VerifiedHarvestCircleBackup", 1578 "pub fn harvestcircle_storage::verify_harvestcircle_backup", 1579 "impl harvestcircle_application::ports::DurableOperationRepository for harvestcircle_storage::Database", 1580 "harvestcircle_application::ports::BoxFuture", 1581 "pub fn harvestcircle_storage::OsKeyringSecretStore::verify<'a>(&'a self, &'a harvestcircle_application::ports::DurableRequestId, harvestcircle_domain::key::PublicKey, harvestcircle_domain::key::SecretKeyInput) -> harvestcircle_application::ports::BoxFuture<'a", 1582 ] { 1583 if !storage_api.contains(required) { 1584 findings.push(format!("{STORAGE_API_BASELINE}: missing {required}")); 1585 } 1586 } 1587 for forbidden in [ 1588 "rusqlite::", 1589 "refinery::", 1590 "sqlx::", 1591 "OperationJournal", 1592 "harvestcircle_initial_schema_sql", 1593 "SELECT_AVAILABILITY_VERSION_SQL", 1594 "decode_availability_row", 1595 "retain_availability_version_on", 1596 "ServiceSqliteTransaction", 1597 "VerifiedServiceBackup", 1598 "StagedServiceRestore", 1599 "verify_backup_bundle", 1600 "stage_verified_restore", 1601 "finalize_staged_restore", 1602 "repair", 1603 "preflight", 1604 ] { 1605 if storage_api.contains(forbidden) { 1606 findings.push(format!( 1607 "{STORAGE_API_BASELINE}: dependency-owned API leaked: {forbidden}" 1608 )); 1609 } 1610 } 1611 for required in [ 1612 PROVENANCE_PATH, 1613 SOURCE_LOCK_PATH, 1614 STORAGE_API_BASELINE, 1615 "config/verification/lanes-v3.properties", 1616 "tools/run-linux-x86_64-development-check.sh", 1617 "tools/verify-storage-api.sh", 1618 ] { 1619 if !inventory.paths.iter().any(|path| path == required) { 1620 findings.push(format!("{required}: governed source evidence is missing")); 1621 } 1622 } 1623 } 1624 1625 fn design_source_audit(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 1626 const PATH: &str = "config/design/harvestcircle-v1.toml"; 1627 if !inventory.paths.iter().any(|path| path == PATH) { 1628 findings.push(format!("{PATH}: design contract is missing")); 1629 return; 1630 } 1631 let source = read_text(root, PATH, findings); 1632 let required_scalars = [ 1633 "schema = \"harvestcircle.design.v1\"", 1634 "repository = \"https://github.com/radrootslabs/harvestcircle\"", 1635 "baseline_revision = \"c08d18ea569351dddeef70d4c1410708daf067b6\"", 1636 "license = \"GPL-3.0-only\"", 1637 "golden_host = \"macos-aarch64\"", 1638 "golden_status = \"verified\"", 1639 "design_system_root = \"app/design_system\"", 1640 "design_catalog_root = \"tools/design_catalog\"", 1641 "application_shell_root = \"app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell\"", 1642 "golden_test_path = \"app/shared/src/desktopTest/kotlin/org/harvestcircle/ui/shell/HarvestCircleMacGoldenTest.kt\"", 1643 ]; 1644 for scalar in required_scalars { 1645 if source.lines().filter(|line| line.trim() == scalar).count() != 1 { 1646 findings.push(format!("{PATH}: missing or duplicate authority: {scalar}")); 1647 } 1648 } 1649 for (path, key, sha256) in [ 1650 ( 1651 "app/shared/src/desktopTest/resources/goldens/macos-aarch64/design-surface-light.png", 1652 "golden_light_sha256", 1653 "96e1ef5dd8b5cb14e47471a737a1e57ab0543b7f3aa79b865051e4740a2ee57a", 1654 ), 1655 ( 1656 "app/shared/src/desktopTest/resources/goldens/macos-aarch64/design-surface-dark.png", 1657 "golden_dark_sha256", 1658 "6a85cd890109b11de6f647dca91cb616651e362aa0802c40aa6aee7f678451c9", 1659 ), 1660 ] { 1661 let authority = format!("{key} = \"{sha256}\""); 1662 if source 1663 .lines() 1664 .filter(|line| line.trim() == authority) 1665 .count() 1666 != 1 1667 { 1668 findings.push(format!("{PATH}: {key} must match the governed golden")); 1669 } 1670 if !inventory.paths.iter().any(|candidate| candidate == path) 1671 || sha256_file(root, path, findings).as_deref() != Some(sha256) 1672 { 1673 findings.push(format!("{path}: macOS golden is missing or changed")); 1674 } 1675 } 1676 let golden_test = read_text( 1677 root, 1678 "app/shared/src/desktopTest/kotlin/org/harvestcircle/ui/shell/HarvestCircleMacGoldenTest.kt", 1679 findings, 1680 ); 1681 if !golden_test.contains("HarvestCircleShell(") 1682 || !golden_test.contains("liveTodayState(") 1683 || golden_test.contains("captureReferenceSurface(") 1684 { 1685 findings.push( 1686 "HarvestCircleMacGoldenTest.kt: golden must render a live application shell state" 1687 .to_owned(), 1688 ); 1689 } 1690 let catalog = read_text(root, "gradle/libs.versions.toml", findings); 1691 for required in [ 1692 "compose-animation = { module = \"org.jetbrains.compose.animation:animation\", version.ref = \"compose\" }", 1693 "compose-components-resources = { module = \"org.jetbrains.compose.components:components-resources\", version.ref = \"compose\" }", 1694 ] { 1695 if !catalog.contains(required) { 1696 findings.push(format!( 1697 "gradle/libs.versions.toml: missing approved design dependency: {required}" 1698 )); 1699 } 1700 } 1701 for forbidden in ["compose-material3", "platformtools", "js(", "wasm"] { 1702 if catalog.to_ascii_lowercase().contains(forbidden) { 1703 findings.push(format!( 1704 "gradle/libs.versions.toml: forbidden design dependency or target: {forbidden}" 1705 )); 1706 } 1707 } 1708 for path in &inventory.paths { 1709 if !is_text(path) 1710 || (!path.starts_with("app/design_system/") 1711 && !path.starts_with("tools/design_catalog/")) 1712 { 1713 continue; 1714 } 1715 let lowercase = read_text(root, path, findings).to_ascii_lowercase(); 1716 for forbidden in [ 1717 "androidx.compose.material3".to_owned(), 1718 "io.github.kdroidfilter.platformtools".to_owned(), 1719 "com.radroots.".to_owned() + &["stu", "dio"].concat(), 1720 ] { 1721 if lowercase.contains(&forbidden) { 1722 findings.push(format!( 1723 "{path}: forbidden dependency or legacy namespace: {forbidden}" 1724 )); 1725 } 1726 } 1727 } 1728 for (path, sha256) in [ 1729 ( 1730 "app/design_system/src/commonMain/composeResources/font/inter_bold.ttf", 1731 "288316099b1e0a47a4716d159098005eef7c0066921f34e3200393dbdb01947f", 1732 ), 1733 ( 1734 "app/design_system/src/commonMain/composeResources/font/inter_medium.ttf", 1735 "97ad806f526e41546d46365bb3a393145f75b7b1568913db74549ad8b8dba872", 1736 ), 1737 ( 1738 "app/design_system/src/commonMain/composeResources/font/inter_regular.ttf", 1739 "40d692fce188e4471e2b3cba937be967878f631ad3ebbbdcd587687c7ebe0c82", 1740 ), 1741 ( 1742 "app/design_system/src/commonMain/composeResources/font/inter_semibold.ttf", 1743 "78a843fade9d4612a5567302fb595b56976eb5fcebf4fea5a5912d638bafcde3", 1744 ), 1745 ] { 1746 if sha256_file(root, path, findings).as_deref() != Some(sha256) { 1747 findings.push(format!( 1748 "{path}: Inter font digest differs from the baseline" 1749 )); 1750 } 1751 } 1752 let font_license = read_text(root, "LICENSES/OFL-1.1.txt", findings); 1753 let packaged_font_license = read_text( 1754 root, 1755 "app/design_system/src/commonMain/composeResources/files/licenses/inter-OFL-1.1.txt", 1756 findings, 1757 ); 1758 if font_license.is_empty() || packaged_font_license != font_license { 1759 findings.push("Inter font licence is missing or differs in packaged resources".to_owned()); 1760 } 1761 } 1762 1763 fn git_source_policy(root: &Path, inventory: &Inventory, findings: &mut Vec<String>) { 1764 let deny = read_text(root, "core/deny.toml", findings); 1765 if !deny 1766 .lines() 1767 .any(|line| line.trim() == "required-git-spec = \"rev\"") 1768 { 1769 findings 1770 .push("core/deny.toml: cargo-deny must require revision-pinned Git sources".to_owned()); 1771 } 1772 let allowed_git = quoted_values(section_value(&deny, "allow-git")); 1773 if allowed_git.is_empty() { 1774 findings.push("core/deny.toml: cargo-deny Git allowlist is empty".to_owned()); 1775 } 1776 let mut inspected = false; 1777 for relative_path in inventory.paths.iter().filter(|path| { 1778 path.as_str() == "core/Cargo.toml" 1779 || (path.starts_with("core/crates/") && path.ends_with("/Cargo.toml")) 1780 }) { 1781 let source = read_text(root, relative_path, findings); 1782 for (index, line) in source 1783 .lines() 1784 .enumerate() 1785 .filter(|(_, line)| line.contains("git")) 1786 { 1787 let Some(git) = attribute(line, "git") else { 1788 continue; 1789 }; 1790 inspected = true; 1791 if !allowed_git.contains(&git) { 1792 findings.push(format!( 1793 "{relative_path}:{}: Git dependency source is not allowlisted", 1794 index + 1 1795 )); 1796 } 1797 if line.contains("branch =") || line.contains("tag =") { 1798 findings.push(format!( 1799 "{relative_path}:{}: Git dependency uses a branch or tag", 1800 index + 1 1801 )); 1802 } 1803 let revision = attribute(line, "rev").unwrap_or_default(); 1804 if !is_lower_hex(&revision, 40) { 1805 findings.push(format!( 1806 "{relative_path}:{}: Git dependency must use one full revision pin", 1807 index + 1 1808 )); 1809 } 1810 if git == "https://github.com/rust-nostr/nostr.git" 1811 && revision != "5bba5163eb77107f82c4a8262cf29d7f33a73219" 1812 { 1813 findings.push("core/Cargo.toml: direct rust-nostr revision changed".to_owned()); 1814 } 1815 } 1816 } 1817 if !inspected { 1818 findings.push("core: no revision-pinned Git dependencies were inspected".to_owned()); 1819 } 1820 for line in read_text(root, "core/Cargo.lock", findings) 1821 .lines() 1822 .filter(|line| line.starts_with("source = \"git+")) 1823 { 1824 let immutable = line.rsplit_once("?rev=").is_some_and(|(_, suffix)| { 1825 suffix.len() == 82 1826 && suffix.as_bytes().get(40) == Some(&b'#') 1827 && suffix.ends_with('"') 1828 && is_lower_hex(&suffix[..40], 40) 1829 && is_lower_hex(&suffix[41..81], 40) 1830 }); 1831 if !immutable { 1832 findings.push(format!( 1833 "core/Cargo.lock: Git source is not immutable: {line}" 1834 )); 1835 } 1836 } 1837 } 1838 1839 fn properties(source: &str) -> std::collections::BTreeMap<String, String> { 1840 source 1841 .lines() 1842 .filter_map(|line| { 1843 let line = line.trim(); 1844 if line.is_empty() || line.starts_with('#') { 1845 None 1846 } else { 1847 line.split_once('=') 1848 .map(|(key, value)| (key.trim().to_owned(), value.trim().to_owned())) 1849 } 1850 }) 1851 .collect() 1852 } 1853 1854 fn section_value<'a>(source: &'a str, key: &str) -> &'a str { 1855 source 1856 .split_once(key) 1857 .map(|(_, tail)| tail.split_once(']').map_or(tail, |(value, _)| value)) 1858 .unwrap_or_default() 1859 } 1860 1861 fn quoted_values(source: &str) -> BTreeSet<String> { 1862 source 1863 .split('"') 1864 .enumerate() 1865 .filter(|(index, _)| index % 2 == 1) 1866 .map(|(_, value)| value.to_owned()) 1867 .collect() 1868 } 1869 1870 fn attribute(source: &str, key: &str) -> Option<String> { 1871 let tail = source.split_once(&format!("{key} = \""))?.1; 1872 Some(tail.split_once('"')?.0.to_owned()) 1873 } 1874 1875 fn is_lower_hex(value: &str, length: usize) -> bool { 1876 value.len() == length 1877 && value 1878 .bytes() 1879 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) 1880 } 1881 1882 fn is_source_safety_text(relative: &str) -> bool { 1883 let normalized = relative.to_ascii_lowercase(); 1884 is_text(relative) 1885 || is_text(&normalized) 1886 || Path::new(&normalized) 1887 .extension() 1888 .and_then(|value| value.to_str()) 1889 .is_some_and(|extension| { 1890 ["svelte", "ts", "js", "css", "html", "sh", "py"].contains(&extension) 1891 }) 1892 } 1893 1894 fn is_text(relative: &str) -> bool { 1895 let name = Path::new(relative) 1896 .file_name() 1897 .and_then(|value| value.to_str()) 1898 .unwrap_or_default(); 1899 let extension = Path::new(relative) 1900 .extension() 1901 .and_then(|value| value.to_str()) 1902 .unwrap_or_default(); 1903 [ 1904 "gradle", 1905 "json", 1906 "kt", 1907 "kts", 1908 "lock", 1909 "md", 1910 "properties", 1911 "rs", 1912 "sql", 1913 "toml", 1914 "txt", 1915 "xml", 1916 "yaml", 1917 "yml", 1918 ] 1919 .contains(&extension) 1920 || [ 1921 ".gitattributes", 1922 ".gitignore", 1923 "AGENTS.md", 1924 "LICENSE", 1925 "Makefile", 1926 "NOTICE", 1927 "gradlew", 1928 "gradlew.bat", 1929 ] 1930 .contains(&name) 1931 } 1932 1933 fn read_text(root: &Path, relative: &str, findings: &mut Vec<String>) -> String { 1934 match bounded_no_follow_bytes(root, Path::new(relative), 8 * 1024 * 1024).and_then(|bytes| { 1935 String::from_utf8(bytes).map_err(|error| format!("invalid source UTF-8: {error}")) 1936 }) { 1937 Ok(source) => source, 1938 Err(error) => { 1939 findings.push(format!( 1940 "{relative}: unable to inspect required source text: {error}" 1941 )); 1942 // The finding is retained even when a caller only tests absence of a marker. 1943 String::new() 1944 } 1945 } 1946 } 1947 1948 fn sha256_file(root: &Path, relative: &str, findings: &mut Vec<String>) -> Option<String> { 1949 match bounded_no_follow_bytes(root, Path::new(relative), 8 * 1024 * 1024) { 1950 Ok(bytes) => Some(format!("{:x}", Sha256::digest(bytes))), 1951 Err(error) => { 1952 findings.push(format!( 1953 "{relative}: unable to inspect required digest input: {error}" 1954 )); 1955 None 1956 } 1957 } 1958 } 1959 1960 fn exact_string_assignment(source: &str, key: &str) -> Option<String> { 1961 let prefix = format!("{key} = \""); 1962 let values = source 1963 .lines() 1964 .filter_map(|line| { 1965 let value = line.strip_prefix(&prefix)?.strip_suffix('"')?; 1966 (!value.is_empty()).then(|| value.to_owned()) 1967 }) 1968 .collect::<Vec<_>>(); 1969 (values.len() == 1).then(|| values[0].clone()) 1970 } 1971 1972 fn bounded_no_follow_bytes(root: &Path, relative: &Path, maximum: u64) -> Result<Vec<u8>, String> { 1973 if relative.is_absolute() 1974 || relative.components().next().is_none() 1975 || relative 1976 .components() 1977 .any(|component| !matches!(component, Component::Normal(_))) 1978 { 1979 return Err("path must be normalized and relative".to_owned()); 1980 } 1981 let components = relative.components().collect::<Vec<_>>(); 1982 let mut path = root.to_path_buf(); 1983 let mut admitted = None; 1984 for (index, component) in components.iter().enumerate() { 1985 path.push(component.as_os_str()); 1986 let metadata = fs::symlink_metadata(&path) 1987 .map_err(|error| format!("unable to inspect {}: {error}", relative.display()))?; 1988 if metadata.file_type().is_symlink() { 1989 return Err(format!( 1990 "path traverses a symbolic link: {}", 1991 relative.display() 1992 )); 1993 } 1994 if index + 1 == components.len() { 1995 if !metadata.is_file() { 1996 return Err(format!( 1997 "path is not a regular file: {}", 1998 relative.display() 1999 )); 2000 } 2001 if metadata.len() > maximum { 2002 return Err(format!("file exceeds byte limit: {}", relative.display())); 2003 } 2004 admitted = Some(metadata); 2005 } else if !metadata.is_dir() { 2006 return Err(format!( 2007 "path parent is not a directory: {}", 2008 relative.display() 2009 )); 2010 } 2011 } 2012 2013 let mut options = OpenOptions::new(); 2014 options.read(true); 2015 #[cfg(unix)] 2016 options.custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK); 2017 let mut file = options.open(&path).map_err(|error| { 2018 format!( 2019 "unable to open {} without following links: {error}", 2020 relative.display() 2021 ) 2022 })?; 2023 let opened = file 2024 .metadata() 2025 .map_err(|error| format!("unable to inspect opened {}: {error}", relative.display()))?; 2026 if !opened.is_file() || opened.len() > maximum { 2027 return Err(format!( 2028 "opened path is not a bounded regular file: {}", 2029 relative.display() 2030 )); 2031 } 2032 #[cfg(unix)] 2033 if admitted 2034 .as_ref() 2035 .is_some_and(|metadata| metadata.dev() != opened.dev() || metadata.ino() != opened.ino()) 2036 { 2037 return Err(format!( 2038 "path identity changed before open: {}", 2039 relative.display() 2040 )); 2041 } 2042 2043 let mut bytes = Vec::with_capacity(opened.len() as usize); 2044 file.by_ref() 2045 .take(maximum + 1) 2046 .read_to_end(&mut bytes) 2047 .map_err(|error| format!("unable to read {}: {error}", relative.display()))?; 2048 if bytes.len() as u64 > maximum { 2049 return Err(format!("file exceeds byte limit: {}", relative.display())); 2050 } 2051 let completed = file 2052 .metadata() 2053 .map_err(|error| format!("unable to revalidate {}: {error}", relative.display()))?; 2054 if completed.len() != bytes.len() as u64 { 2055 return Err(format!( 2056 "file changed while it was read: {}", 2057 relative.display() 2058 )); 2059 } 2060 #[cfg(unix)] 2061 if opened.dev() != completed.dev() || opened.ino() != completed.ino() { 2062 return Err(format!( 2063 "file identity changed while it was read: {}", 2064 relative.display() 2065 )); 2066 } 2067 Ok(bytes) 2068 } 2069 2070 fn relative(root: &Path, path: &Path) -> Result<String, String> { 2071 let relative = path 2072 .strip_prefix(root) 2073 .map_err(|error| format!("{} is outside {}: {error}", path.display(), root.display()))?; 2074 relative 2075 .components() 2076 .map(|component| match component { 2077 Component::Normal(value) => value 2078 .to_str() 2079 .map(str::to_owned) 2080 .ok_or_else(|| "archive inventory path is not valid UTF-8".to_owned()), 2081 _ => Err("archive inventory path must be normalized and relative".to_owned()), 2082 }) 2083 .collect::<Result<Vec<_>, _>>() 2084 .map(|parts| parts.join("/")) 2085 } 2086 2087 #[cfg(test)] 2088 mod tests { 2089 use super::*; 2090 use std::time::{SystemTime, UNIX_EPOCH}; 2091 2092 const ROOT_GUIDANCE: &str = include_str!("../../../AGENTS.md"); 2093 const WEB_GUIDANCE: &str = include_str!("../../../web/AGENTS.md"); 2094 2095 #[test] 2096 fn shared_required_readers_report_failures_instead_of_passing_absent_markers() { 2097 let root = fixture("required readers"); 2098 write(&root, "invalid.rs", "temporary"); 2099 fs::write(root.join("invalid.rs"), [0xff]).unwrap(); 2100 fs::create_dir(root.join("directory.rs")).unwrap(); 2101 write(&root, "large.rs", ""); 2102 OpenOptions::new() 2103 .write(true) 2104 .open(root.join("large.rs")) 2105 .unwrap() 2106 .set_len(8 * 1024 * 1024 + 1) 2107 .unwrap(); 2108 for path in [ 2109 "absent.rs", 2110 "invalid.rs", 2111 "directory.rs", 2112 "large.rs", 2113 "../outside.rs", 2114 ] { 2115 let mut findings = Vec::new(); 2116 let source = read_text(&root, path, &mut findings); 2117 assert!(!source.contains("forbidden marker")); 2118 assert!( 2119 !findings.is_empty(), 2120 "absent forbidden marker must not mean PASS: {path}" 2121 ); 2122 } 2123 for path in ["absent.bin", "directory.rs", "large.rs", "../outside.bin"] { 2124 let mut findings = Vec::new(); 2125 assert!(sha256_file(&root, path, &mut findings).is_none()); 2126 assert!( 2127 !findings.is_empty(), 2128 "missing digest must carry a finding: {path}" 2129 ); 2130 } 2131 #[cfg(unix)] 2132 { 2133 std::os::unix::fs::symlink("invalid.rs", root.join("link.rs")).unwrap(); 2134 let mut findings = Vec::new(); 2135 read_text(&root, "link.rs", &mut findings); 2136 sha256_file(&root, "link.rs", &mut findings); 2137 assert_eq!(findings.len(), 2); 2138 assert!( 2139 findings 2140 .iter() 2141 .all(|finding| finding.contains("symbolic link")) 2142 ); 2143 } 2144 fs::remove_dir_all(root).unwrap(); 2145 } 2146 2147 #[test] 2148 fn root_validation_rejects_wrong_cwd_for_every_command() { 2149 let root = fixture("wrong root with spaces"); 2150 for command in [ 2151 Command::DesignSourceAudit, 2152 Command::RepoAudit, 2153 Command::NamespaceAudit, 2154 Command::ProvenanceCheck, 2155 Command::QualificationReport, 2156 ] { 2157 let findings = run(&root, command).expect_err("wrong root must fail"); 2158 assert!( 2159 findings 2160 .iter() 2161 .any(|finding| finding.contains("product root")), 2162 "{findings:?}" 2163 ); 2164 } 2165 fs::remove_dir_all(root).expect("remove fixture"); 2166 } 2167 2168 #[test] 2169 fn archive_inventory_preserves_literal_backslash_identity() { 2170 let root = fixture("archive literal path"); 2171 write(&root, "web\\node_modules\\unsafe.ts", "source"); 2172 let inventory = Inventory::load(&root).expect("literal archive path"); 2173 assert!( 2174 inventory 2175 .paths 2176 .iter() 2177 .any(|path| path == "web\\node_modules\\unsafe.ts") 2178 ); 2179 fs::remove_dir_all(root).expect("remove fixture"); 2180 } 2181 2182 #[cfg(unix)] 2183 #[test] 2184 fn archive_relative_paths_reject_invalid_utf8_and_escape() { 2185 use std::os::unix::ffi::OsStringExt; 2186 let root = fixture("archive path identity"); 2187 let invalid = root.join(std::ffi::OsString::from_vec(vec![0xff])); 2188 assert!( 2189 relative(&root, &invalid) 2190 .expect_err("invalid UTF-8") 2191 .contains("UTF-8") 2192 ); 2193 assert!(relative(&root, &root.join("../escape.rs")).is_err()); 2194 assert!(relative(&root, Path::new("/unrelated/escape.rs")).is_err()); 2195 fs::remove_dir_all(root).expect("remove fixture"); 2196 } 2197 2198 #[cfg(unix)] 2199 #[test] 2200 fn archive_inventory_rejects_symlinks_and_fifo_before_audits() { 2201 let root = fixture("unsafe archive"); 2202 std::os::unix::fs::symlink("/does-not-exist", root.join("unsafe.rs")).expect("symlink"); 2203 assert!( 2204 Inventory::load(&root) 2205 .expect_err("symlink must fail") 2206 .contains("symbolic link") 2207 ); 2208 fs::remove_file(root.join("unsafe.rs")).expect("remove symlink"); 2209 assert!( 2210 ProcessCommand::new("mkfifo") 2211 .arg(root.join("unsafe.rs")) 2212 .status() 2213 .expect("fifo") 2214 .success() 2215 ); 2216 assert!( 2217 Inventory::load(&root) 2218 .expect_err("FIFO must fail") 2219 .contains("regular file") 2220 ); 2221 fs::remove_dir_all(root).expect("remove fixture"); 2222 } 2223 2224 #[test] 2225 fn nested_parent_inventory_is_confined_to_capsule() { 2226 let parent = fixture("parent with spaces"); 2227 initialize_git_fixture(&parent); 2228 write(&parent, "private.rs", "not capsule source"); 2229 write(&parent, "oss/capsule/source.rs", "capsule source"); 2230 let inventory = Inventory::load(&parent.join("oss/capsule")).expect("nested Git inventory"); 2231 assert!(inventory.git_aware); 2232 assert_eq!(inventory.paths, ["source.rs"]); 2233 fs::remove_dir_all(parent).expect("remove fixture"); 2234 } 2235 2236 #[test] 2237 fn malformed_git_metadata_never_falls_back_to_archive() { 2238 let root = fixture("broken git"); 2239 write(&root, ".git", "not a gitdir\n"); 2240 assert!(Inventory::load(&root).is_err()); 2241 fs::remove_dir_all(root).expect("remove fixture"); 2242 } 2243 2244 fn guidance_findings(root_source: &str, web_source: &str) -> Vec<String> { 2245 let root = fixture("runtime-guidance"); 2246 write(&root, "AGENTS.md", root_source); 2247 write(&root, "web/AGENTS.md", web_source); 2248 let inventory = Inventory::load(&root).expect("guidance inventory"); 2249 let mut findings = Vec::new(); 2250 repo_audit(&root, &inventory, &mut findings); 2251 fs::remove_dir_all(root).expect("remove guidance fixture"); 2252 findings 2253 .into_iter() 2254 .filter(|finding| finding.contains("guidance")) 2255 .collect() 2256 } 2257 2258 #[test] 2259 fn current_runtime_guidance_preserves_separate_boundaries() { 2260 let findings = guidance_findings(ROOT_GUIDANCE, WEB_GUIDANCE); 2261 assert!(findings.is_empty(), "{findings:#?}"); 2262 assert!(ROOT_GUIDANCE.contains("## Native runtime boundaries")); 2263 assert!(WEB_GUIDANCE.contains("IndexedDB")); 2264 } 2265 2266 #[test] 2267 fn runtime_guidance_accepts_wrapping_and_rejects_missing_or_invalid_text() { 2268 assert!( 2269 guidance_findings( 2270 &ROOT_GUIDANCE 2271 .split_whitespace() 2272 .collect::<Vec<_>>() 2273 .join("\n"), 2274 &WEB_GUIDANCE 2275 .split_whitespace() 2276 .collect::<Vec<_>>() 2277 .join("\n"), 2278 ) 2279 .is_empty() 2280 ); 2281 let root = fixture("invalid-guidance"); 2282 write(&root, "AGENTS.md", ROOT_GUIDANCE); 2283 let mut findings = Vec::new(); 2284 runtime_guidance_audit(&root, &mut findings); 2285 assert!( 2286 findings.iter().any( 2287 |finding| finding.starts_with("web/AGENTS.md: unable to read runtime guidance") 2288 ) 2289 ); 2290 write(&root, "web/AGENTS.md", WEB_GUIDANCE); 2291 fs::write(root.join("AGENTS.md"), [0xff]).expect("invalid UTF-8 guidance"); 2292 findings.clear(); 2293 runtime_guidance_audit(&root, &mut findings); 2294 assert!( 2295 findings 2296 .iter() 2297 .any(|finding| finding.starts_with("AGENTS.md: unable to read runtime guidance")) 2298 ); 2299 fs::remove_dir_all(root).expect("remove invalid guidance fixture"); 2300 } 2301 2302 #[test] 2303 fn runtime_guidance_rejects_lost_native_boundaries() { 2304 for marker in [ 2305 "SQLx is the only high-level SQLite library.", 2306 "schema v3, storage API v3, FFI v4.5, snapshot v1, custody,", 2307 "exact Radroots source pin", 2308 "platform/ABI", 2309 "Private keys and signing operations remain behind the generated native", 2310 ] { 2311 assert!(ROOT_GUIDANCE.contains(marker), "fixture marker: {marker}"); 2312 let altered = ROOT_GUIDANCE.replace(marker, "native boundary removed"); 2313 assert!( 2314 !guidance_findings(&altered, WEB_GUIDANCE).is_empty(), 2315 "accepted lost native rule: {marker}" 2316 ); 2317 } 2318 } 2319 2320 #[test] 2321 fn runtime_guidance_rejects_lost_browser_boundaries() { 2322 for marker in [ 2323 "IndexedDB", 2324 "explicit\n extension interaction", 2325 "Applesauce", 2326 "operating-system keyring", 2327 "UniFFI implementation", 2328 "do not invent commands or claim an absent web suite passed", 2329 ] { 2330 assert!(WEB_GUIDANCE.contains(marker), "fixture marker: {marker}"); 2331 let altered = WEB_GUIDANCE.replace(marker, "browser boundary removed"); 2332 assert!( 2333 !guidance_findings(ROOT_GUIDANCE, &altered).is_empty(), 2334 "accepted lost browser rule: {marker}" 2335 ); 2336 } 2337 } 2338 2339 #[test] 2340 fn runtime_guidance_rejects_relaxed_source_and_product_scope() { 2341 for marker in [ 2342 "All `docs/**`,", 2343 "`.github/**`", 2344 "`.act/**`", 2345 "must not depend on private parent code", 2346 "HCAV-021", 2347 ] { 2348 assert!(ROOT_GUIDANCE.contains(marker), "fixture marker: {marker}"); 2349 let altered = ROOT_GUIDANCE.replace(marker, "permitted"); 2350 assert!( 2351 !guidance_findings(&altered, WEB_GUIDANCE).is_empty(), 2352 "accepted relaxed root rule: {marker}" 2353 ); 2354 } 2355 for marker in [ 2356 "Do not introduce `docs/**`", 2357 "`.github/**`", 2358 "`.act/**`", 2359 "dependency on parent documentation", 2360 "WASM launch dependency", 2361 ] { 2362 assert!(WEB_GUIDANCE.contains(marker), "fixture marker: {marker}"); 2363 let altered = WEB_GUIDANCE.replace(marker, "permitted"); 2364 assert!( 2365 !guidance_findings(ROOT_GUIDANCE, &altered).is_empty(), 2366 "accepted relaxed subtree rule: {marker}" 2367 ); 2368 } 2369 } 2370 2371 #[test] 2372 fn commands_are_exact_and_unknown_values_fail_closed() { 2373 assert_eq!( 2374 "design-source-audit".parse(), 2375 Ok(Command::DesignSourceAudit) 2376 ); 2377 assert_eq!("repo-audit".parse(), Ok(Command::RepoAudit)); 2378 assert_eq!("namespace-audit".parse(), Ok(Command::NamespaceAudit)); 2379 assert_eq!("provenance-check".parse(), Ok(Command::ProvenanceCheck)); 2380 assert_eq!( 2381 "qualification-report".parse(), 2382 Ok(Command::QualificationReport) 2383 ); 2384 assert!("all".parse::<Command>().is_err()); 2385 } 2386 2387 #[test] 2388 fn current_design_contract_is_exact() { 2389 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) 2390 .parent() 2391 .and_then(Path::parent) 2392 .expect("repository root") 2393 .to_path_buf(); 2394 let inventory = Inventory::load(&root).expect("source inventory"); 2395 let mut findings = Vec::new(); 2396 design_source_audit(&root, &inventory, &mut findings); 2397 assert!(findings.is_empty(), "{findings:#?}"); 2398 } 2399 2400 #[test] 2401 fn current_source_provenance_and_lib_lock_are_exact() { 2402 let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) 2403 .parent() 2404 .and_then(Path::parent) 2405 .expect("repository root") 2406 .to_path_buf(); 2407 let inventory = Inventory::load(&root).expect("source inventory"); 2408 let mut findings = Vec::new(); 2409 provenance_check(&root, &inventory, &mut findings); 2410 assert!(findings.is_empty(), "{findings:#?}"); 2411 } 2412 2413 #[test] 2414 fn sqlite_topology_rejects_alternate_duplicate_and_direct_authority() { 2415 let root = fixture("sqlite-topology"); 2416 write( 2417 &root, 2418 "core/Cargo.lock", 2419 "name = \"libsqlite3-sys\"\nname = \"libsqlite3-sys\"\nname = \"rusqlite\"\n", 2420 ); 2421 write( 2422 &root, 2423 "core/crates/unsafe_storage/Cargo.toml", 2424 "[target.'cfg(unix)'.dependencies.refinery]\nversion = \"0.9\"\n", 2425 ); 2426 let inventory = Inventory::load(&root).expect("archive inventory"); 2427 let mut findings = Vec::new(); 2428 sqlite_dependency_topology(&root, &inventory, &mut findings); 2429 assert!( 2430 findings.iter().any(|finding| finding 2431 .contains("exact single SQLx-selected native SQLite topology changed")), 2432 "{findings:#?}" 2433 ); 2434 assert!( 2435 findings.iter().any(|finding| finding 2436 .contains("direct alternate or native SQLite dependency is forbidden")), 2437 "{findings:#?}" 2438 ); 2439 fs::remove_dir_all(root).expect("remove fixture"); 2440 } 2441 2442 #[test] 2443 fn development_runner_rejects_release_integration_activation() { 2444 let root = fixture("development-runner"); 2445 write( 2446 &root, 2447 "Makefile", 2448 "override CARGO := cargo +1.99.0\napi-check: doctor\ndevelopment-check: development-provenance-check source-check integration-check\ngoverned-development-check:\ngoverned-linux-x86_64-development-check: governed-doctor\n", 2449 ); 2450 write( 2451 &root, 2452 "tools/run-linux-x86_64-development-check.sh", 2453 "dependencyCheckAnalyze\n", 2454 ); 2455 let mut findings = Vec::new(); 2456 development_integration_policy(&root, &mut findings); 2457 assert!( 2458 findings 2459 .iter() 2460 .any(|finding| { finding.contains("deferred release integration is active") }), 2461 "{findings:#?}" 2462 ); 2463 fs::remove_dir_all(root).expect("remove fixture"); 2464 } 2465 2466 #[test] 2467 fn design_contract_rejects_identity_and_root_drift() { 2468 let root = fixture("design-contract"); 2469 write( 2470 &root, 2471 "config/design/harvestcircle-v1.toml", 2472 "schema = \"harvestcircle.design.v1\"\nrepository = \"https://example.invalid/other\"\ndesign_system_root = \"../escape\"\n", 2473 ); 2474 let inventory = Inventory::load(&root).expect("archive inventory"); 2475 let mut findings = Vec::new(); 2476 design_source_audit(&root, &inventory, &mut findings); 2477 assert!( 2478 findings 2479 .iter() 2480 .any(|finding| finding.contains("missing or duplicate authority")) 2481 ); 2482 fs::remove_dir_all(root).expect("remove fixture"); 2483 } 2484 2485 #[test] 2486 fn archive_inventory_excludes_outputs_and_includes_source() { 2487 let root = fixture("archive"); 2488 write(&root, "src/main.rs", "fn main() {}\n"); 2489 write(&root, "target/debug/generated.bin", "output"); 2490 write(&root, "nested/build/generated.txt", "output"); 2491 let inventory = Inventory::load(&root).expect("archive inventory"); 2492 assert!(!inventory.git_aware); 2493 assert!(inventory.paths.contains(&"src/main.rs".to_owned())); 2494 assert!( 2495 !inventory 2496 .paths 2497 .iter() 2498 .any(|path| path.contains("target/") || path.contains("/build/")) 2499 ); 2500 fs::remove_dir_all(root).expect("remove fixture"); 2501 } 2502 2503 #[test] 2504 fn web_policy_git_ignored_outputs_are_not_traversed_but_forced_inputs_fail() { 2505 let root = fixture("web-git-policy"); 2506 initialize_git_fixture(&root); 2507 write(&root, ".gitignore", include_str!("../../../.gitignore")); 2508 let outputs = [ 2509 "node_modules", 2510 ".svelte-kit", 2511 "build", 2512 "coverage", 2513 "test-results", 2514 "playwright-report", 2515 ]; 2516 for output in outputs { 2517 write( 2518 &root, 2519 &format!("web/{output}/nested/dependency.ts"), 2520 "ignored output", 2521 ); 2522 } 2523 #[cfg(unix)] 2524 std::os::unix::fs::symlink("/does-not-exist", root.join("web/node_modules/external")) 2525 .expect("ignored dependency symlink"); 2526 let inventory = Inventory::load(&root).expect("ignored outputs are not inspected"); 2527 assert_eq!(inventory.paths, vec![".gitignore"]); 2528 let forbidden = [ 2529 "node_modules/dependency.ts", 2530 "web/node_modules/dependency.ts", 2531 "web/.svelte-kit/output.js", 2532 "web/build/index.html", 2533 "web/coverage/report.json", 2534 "web/test-results/report.json", 2535 "web/playwright-report/index.html", 2536 "web/src/module.wasm", 2537 "web/src/addon.node", 2538 "web/.env.local", 2539 "web/.env.example", 2540 "config/.env.production", 2541 ]; 2542 for path in forbidden { 2543 write(&root, path, "forced source"); 2544 assert!( 2545 ProcessCommand::new("git") 2546 .arg("-C") 2547 .arg(&root) 2548 .args(["add", "--force", "--", path]) 2549 .status() 2550 .expect("force index") 2551 .success() 2552 ); 2553 } 2554 let inventory = Inventory::load(&root).expect("forced regular sources inventoried"); 2555 let mut findings = Vec::new(); 2556 repo_audit(&root, &inventory, &mut findings); 2557 for path in forbidden { 2558 assert!( 2559 findings 2560 .iter() 2561 .any(|finding| finding.starts_with(&format!("{path}:")) 2562 && (finding.contains("generated build output") 2563 || finding.contains("secret-shaped"))), 2564 "{path}: {findings:#?}" 2565 ); 2566 } 2567 #[cfg(unix)] 2568 { 2569 assert!( 2570 ProcessCommand::new("git") 2571 .arg("-C") 2572 .arg(&root) 2573 .args(["add", "--force", "--", "web/node_modules/external"]) 2574 .status() 2575 .expect("force index dependency symlink") 2576 .success() 2577 ); 2578 assert!( 2579 Inventory::load(&root) 2580 .expect_err("tracked dependency symlink must fail") 2581 .contains("symbolic link") 2582 ); 2583 } 2584 fs::remove_dir_all(root).expect("remove fixture"); 2585 } 2586 2587 #[test] 2588 fn web_policy_archive_outputs_are_excluded_and_global_source_is_inspected() { 2589 let root = fixture("web-archive-policy"); 2590 for output in [ 2591 "node_modules", 2592 ".svelte-kit", 2593 "build", 2594 "coverage", 2595 "test-results", 2596 "playwright-report", 2597 ] { 2598 write( 2599 &root, 2600 &format!("web/{output}/nested/dependency.ts"), 2601 "ignored output", 2602 ); 2603 } 2604 #[cfg(unix)] 2605 std::os::unix::fs::symlink("/does-not-exist", root.join("web/node_modules/external")) 2606 .expect("archive dependency symlink"); 2607 let marker = ["-----BEGIN ", "PRIVATE KEY-----"].concat(); 2608 let mut sources = Vec::new(); 2609 for owner in ["web/src", "tools", "app"] { 2610 for extension in ["svelte", "ts", "js", "css", "html", "sh", "py", "json"] { 2611 let path = format!("{owner}/ordinary.{extension}"); 2612 write(&root, &path, &marker); 2613 sources.push(path); 2614 } 2615 } 2616 for path in [ 2617 "web/src/unsafe.TS", 2618 "web/src/unsafe.Svelte", 2619 "web/src/unsafe.JSON", 2620 "web/src/coverage/handler.ts", 2621 "web/coverage-extra/handler.ts", 2622 ] { 2623 write(&root, path, &marker); 2624 sources.push(path.to_owned()); 2625 } 2626 let inventory = Inventory::load(&root).expect("archive inventory"); 2627 assert!( 2628 inventory 2629 .paths 2630 .iter() 2631 .all(|path| !path.contains("dependency") && !path.contains("external")) 2632 ); 2633 let mut findings = Vec::new(); 2634 repo_audit(&root, &inventory, &mut findings); 2635 for path in sources { 2636 assert!( 2637 findings.iter().any(|finding| finding 2638 == &format!("{path}: credential or private-key material in source text")), 2639 "{findings:#?}" 2640 ); 2641 } 2642 fs::remove_dir_all(root).expect("remove fixture"); 2643 // Use a separate fixture so this assertion also works on case-insensitive hosts. 2644 let root = fixture("web-archive-case"); 2645 write( 2646 &root, 2647 "WEB/coverage/unsafe.ts", 2648 "case-sensitive archive source", 2649 ); 2650 let inventory = Inventory::load(&root).expect("uppercase archive source"); 2651 assert!( 2652 inventory 2653 .paths 2654 .contains(&"WEB/coverage/unsafe.ts".to_owned()) 2655 ); 2656 fs::remove_dir_all(root).expect("remove case fixture"); 2657 } 2658 2659 #[test] 2660 fn web_policy_preserves_ordinary_sources_and_native_binary_inputs() { 2661 let root = fixture("web-policy-preserved-inputs"); 2662 let sources = [ 2663 "web/src/coverage/handler.ts", 2664 "web/coverage-extra/handler.ts", 2665 "web/src/ordinary.svelte", 2666 "web/src/ordinary.ts", 2667 "web/src/ordinary.js", 2668 "web/src/ordinary.css", 2669 "web/src/ordinary.html", 2670 "web/scripts/ordinary.sh", 2671 "tools/ordinary.py", 2672 "web/package.json", 2673 "web/src/coverage_rules.ts", 2674 "web/.svelte-kit.config.ts", 2675 ]; 2676 let assets = [ 2677 "gradle/wrapper/gradle-wrapper.jar", 2678 "app/design_system/src/commonMain/resources/font/font.ttf", 2679 "app/desktop/src/main/resources/icon.png", 2680 ]; 2681 write(&root, ".gitignore", include_str!("../../../.gitignore")); 2682 for path in sources { 2683 write(&root, path, "ordinary source"); 2684 } 2685 for path in assets { 2686 let target = root.join(path); 2687 fs::create_dir_all(target.parent().expect("asset parent")).expect("asset directory"); 2688 fs::write(target, [0xff, 0x00]).expect("binary input"); 2689 } 2690 for git_aware in [false, true] { 2691 if git_aware { 2692 initialize_git_fixture(&root); 2693 } 2694 let inventory = Inventory::load(&root).expect("ordinary inventory"); 2695 assert_eq!(inventory.git_aware, git_aware); 2696 let mut findings = Vec::new(); 2697 repo_audit(&root, &inventory, &mut findings); 2698 for path in sources.into_iter().chain(assets) { 2699 assert!(inventory.paths.iter().any(|value| value == path), "{path}"); 2700 assert!( 2701 !findings 2702 .iter() 2703 .any(|finding| finding.starts_with(&format!("{path}:"))), 2704 "{findings:#?}" 2705 ); 2706 } 2707 } 2708 fs::remove_dir_all(root).expect("remove fixture"); 2709 } 2710 2711 #[test] 2712 fn web_policy_rejects_invalid_text_without_reading_symlinks_or_directories() { 2713 let root = fixture("web-invalid-text"); 2714 fs::write(root.join("invalid.ts"), [0xff]).expect("invalid text"); 2715 fs::create_dir(root.join("directory.js")).expect("source-shaped directory"); 2716 #[cfg(unix)] 2717 std::os::unix::fs::symlink("/does-not-exist", root.join("link.css")) 2718 .expect("source symlink"); 2719 #[cfg(unix)] 2720 { 2721 assert!( 2722 Inventory::load(&root) 2723 .expect_err("archive symlink must fail before audits") 2724 .contains("symbolic link") 2725 ); 2726 fs::remove_file(root.join("link.css")).expect("remove source symlink"); 2727 } 2728 let inventory = Inventory::load(&root).expect("archive inventory"); 2729 let mut findings = Vec::new(); 2730 repo_audit(&root, &inventory, &mut findings); 2731 assert!( 2732 findings 2733 .iter() 2734 .any(|finding| finding.starts_with("invalid.ts:") && finding.contains("UTF-8")), 2735 "{findings:#?}" 2736 ); 2737 assert!( 2738 findings 2739 .iter() 2740 .any(|finding| finding.starts_with("directory.js:") 2741 && finding.contains("regular file")), 2742 "{findings:#?}" 2743 ); 2744 fs::remove_dir_all(root).expect("remove fixture"); 2745 } 2746 2747 #[test] 2748 fn repository_policy_rejects_secret_and_generated_shapes() { 2749 let root = fixture("policy"); 2750 write(&root, "README.md", "safe\n"); 2751 write(&root, "config/credentials/release.key", "fixture\n"); 2752 write(&root, "core/target/generated/native.bin", "fixture\n"); 2753 write( 2754 &root, 2755 "safe.txt", 2756 &["-----BEGIN ", "PRIVATE KEY-----"].concat(), 2757 ); 2758 write(&root, ".github/workflows/remote.yml", "fixture\n"); 2759 let inventory = Inventory { 2760 paths: vec![ 2761 "README.md".to_owned(), 2762 ".github/workflows/remote.yml".to_owned(), 2763 "config/credentials/release.key".to_owned(), 2764 "core/target/generated/native.bin".to_owned(), 2765 "safe.txt".to_owned(), 2766 ], 2767 git_aware: true, 2768 }; 2769 let mut findings = Vec::new(); 2770 repo_audit(&root, &inventory, &mut findings); 2771 assert!( 2772 findings 2773 .iter() 2774 .any(|finding| finding.contains("secret-shaped")) 2775 ); 2776 assert!( 2777 findings 2778 .iter() 2779 .any(|finding| finding.contains("generated build output")) 2780 ); 2781 assert!( 2782 findings 2783 .iter() 2784 .any(|finding| finding.contains("forbidden repository root")) 2785 ); 2786 assert!( 2787 findings 2788 .iter() 2789 .any(|finding| finding.contains("private-key material")) 2790 ); 2791 fs::remove_dir_all(root).expect("remove fixture"); 2792 } 2793 2794 #[test] 2795 fn namespace_policy_rejects_legacy_temporary_and_platform_sources() { 2796 let root = fixture("namespace"); 2797 let legacy = ["stu", "dio"].concat(); 2798 write( 2799 &root, 2800 &format!("app/{legacy}/Leak.kt"), 2801 &format!( 2802 "package {}\n", 2803 ["org", "radroots", "harvestcircle"].join(".") 2804 ), 2805 ); 2806 write( 2807 &root, 2808 "app/shared/src/commonMain/kotlin/org/harvestcircle/Leak.kt", 2809 "import com.sun.jna.Native\n", 2810 ); 2811 let inventory = Inventory::load(&root).expect("archive inventory"); 2812 let mut findings = Vec::new(); 2813 namespace_audit(&root, &inventory, &mut findings); 2814 assert!( 2815 findings 2816 .iter() 2817 .any(|finding| finding.contains("legacy product name")) 2818 ); 2819 assert!( 2820 findings 2821 .iter() 2822 .any(|finding| finding.contains("temporary product namespace")) 2823 ); 2824 assert!( 2825 findings 2826 .iter() 2827 .any(|finding| finding.contains("platform dependency")) 2828 ); 2829 fs::remove_dir_all(root).expect("remove fixture"); 2830 } 2831 2832 #[test] 2833 fn namespace_policy_rejects_transition_identity_without_exceptions() { 2834 let root = fixture("namespace-no-exceptions"); 2835 let legacy = ["stu", "dio"].concat(); 2836 let repository = format!("https://github.com/radrootslabs/{legacy}_app"); 2837 let entry = 2838 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/BootstrapIdentityEntry.kt"; 2839 write( 2840 &root, 2841 "app/shared/src/commonMain/kotlin/org/harvestcircle/product/SurfaceRegistry.kt", 2842 &format!("val key = \"round_{legacy}_screen\"\n"), 2843 ); 2844 write(&root, entry, "val placeholder = \"nsec1…\"\n"); 2845 write( 2846 &root, 2847 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationSettingsScreen.kt", 2848 &format!( 2849 "val source = \"{repository}\"\nval licence = \"{repository}/blob/dev/LICENSE\"\n" 2850 ), 2851 ); 2852 let inventory = Inventory::load(&root).expect("allowlist inventory"); 2853 let mut findings = Vec::new(); 2854 namespace_audit(&root, &inventory, &mut findings); 2855 assert!( 2856 findings 2857 .iter() 2858 .filter(|finding| finding.contains("legacy product name")) 2859 .count() 2860 >= 2, 2861 "{findings:?}" 2862 ); 2863 assert!( 2864 findings 2865 .iter() 2866 .all(|finding| !finding.contains("secret key literal")), 2867 "{findings:?}" 2868 ); 2869 fs::remove_dir_all(root).expect("remove fixture"); 2870 } 2871 2872 #[test] 2873 fn product_shell_audit_requires_the_complete_source_contract() { 2874 let root = fixture("product-shell"); 2875 write(&root, "README.md", "safe\n"); 2876 let inventory = Inventory::load(&root).expect("product shell inventory"); 2877 let mut findings = Vec::new(); 2878 product_shell_audit(&root, &inventory, &mut findings); 2879 assert!( 2880 findings 2881 .iter() 2882 .any(|finding| finding.contains("required product-shell source is missing")) 2883 ); 2884 fs::remove_dir_all(root).expect("remove fixture"); 2885 } 2886 2887 #[test] 2888 fn current_product_shell_sources_pass_the_expanded_policy() { 2889 let root = Path::new(env!("CARGO_MANIFEST_DIR")) 2890 .join("../..") 2891 .canonicalize() 2892 .expect("repository root"); 2893 let inventory = Inventory::load(&root).expect("current source inventory"); 2894 let mut findings = Vec::new(); 2895 product_shell_audit(&root, &inventory, &mut findings); 2896 assert!(findings.is_empty(), "{findings:?}"); 2897 } 2898 2899 #[test] 2900 fn product_shell_audit_rejects_legacy_screen_paths_tags_and_colors() { 2901 let root = fixture("legacy-shell"); 2902 let path = "app/shared/src/commonMain/kotlin/org/harvestcircle/identities/ui/HarvestCircleScreen.kt"; 2903 write( 2904 &root, 2905 path, 2906 "@Composable fun Legacy() { val tag = \"home-screen\"; val color = WindowBackgroundColor }\n", 2907 ); 2908 let inventory = Inventory::load(&root).expect("legacy inventory"); 2909 let mut findings = Vec::new(); 2910 product_shell_audit(&root, &inventory, &mut findings); 2911 assert!( 2912 findings 2913 .iter() 2914 .any(|finding| finding.contains("superseded product-shell screen path")) 2915 ); 2916 assert!( 2917 findings 2918 .iter() 2919 .any(|finding| finding.contains("superseded product-shell marker home-screen")) 2920 ); 2921 assert!(findings.iter().any(|finding| { 2922 finding.contains("superseded product-shell marker WindowBackgroundColor") 2923 })); 2924 fs::remove_dir_all(root).expect("remove fixture"); 2925 } 2926 2927 #[test] 2928 fn product_shell_audit_rejects_color_and_primitive_bypasses_after_a_move() { 2929 let root = fixture("moved-compose"); 2930 let path = "app/desktop/src/main/kotlin/org/harvestcircle/desktop/MovedScreen.kt"; 2931 write( 2932 &root, 2933 path, 2934 "import androidx.compose.runtime.Composable\nimport androidx.compose.material.Button\n@Composable fun ShellButton() { Color(0xFF000000); BasicText(\"bypass\"); BasicTextField(\"\", {}) }\n", 2935 ); 2936 let inventory = Inventory::load(&root).expect("moved UI inventory"); 2937 let mut findings = Vec::new(); 2938 product_shell_audit(&root, &inventory, &mut findings); 2939 assert!( 2940 findings 2941 .iter() 2942 .any(|finding| finding 2943 .contains("hard-coded Compose color outside the theme adapter")) 2944 ); 2945 assert!( 2946 findings 2947 .iter() 2948 .any(|finding| finding.contains("BasicText bypasses the shell primitive adapter")) 2949 ); 2950 assert!(findings.iter().any(|finding| { 2951 finding.contains("BasicTextField bypasses the shell primitive adapter") 2952 })); 2953 assert!( 2954 findings 2955 .iter() 2956 .any(|finding| finding.contains("Material component dependency is forbidden")) 2957 ); 2958 assert!( 2959 findings 2960 .iter() 2961 .any(|finding| finding.contains("superseded shell button adapter")) 2962 ); 2963 fs::remove_dir_all(root).expect("remove fixture"); 2964 } 2965 2966 #[test] 2967 fn product_shell_audit_rejects_fake_commercial_data_outside_the_shell_package() { 2968 let root = fixture("commercial-data"); 2969 write( 2970 &root, 2971 "app/shared/src/commonMain/kotlin/org/harvestcircle/product/FakeData.kt", 2972 "data class FakeData(val commitmentId: String, val priceCents: Long)\n", 2973 ); 2974 let inventory = Inventory::load(&root).expect("commercial inventory"); 2975 let mut findings = Vec::new(); 2976 product_shell_audit(&root, &inventory, &mut findings); 2977 assert!(findings.iter().any(|finding| finding 2978 .contains("fake commercial product data marker commitmentid"))); 2979 assert!( 2980 findings 2981 .iter() 2982 .any(|finding| finding.contains("fake commercial product data marker pricecents")) 2983 ); 2984 fs::remove_dir_all(root).expect("remove fixture"); 2985 } 2986 2987 #[test] 2988 fn product_shell_audit_rejects_retired_security_and_selection_shapes() { 2989 let root = fixture("shell-security-shapes"); 2990 write( 2991 &root, 2992 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/LegacyConfirmation.kt", 2993 "data object ConfirmIdentityRemoval\ndata object CancelIdentityRemoval\n", 2994 ); 2995 write( 2996 &root, 2997 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/UnsafeReference.kt", 2998 "fun reduce(intent: OverlayIntent) = when (intent) { is OverlayIntent.EditReference -> classifyNostrReference(intent.value) }\n", 2999 ); 3000 write( 3001 &root, 3002 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/UnsafeIngress.kt", 3003 "val overlay = OverlayIntent.Open(FoundationOverlay.OpenNostrReference(\"prefilled\"))\n", 3004 ); 3005 write( 3006 &root, 3007 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/UnsafeSelection.kt", 3008 "ShellTab(selected = true, enabled = false)\n", 3009 ); 3010 let inventory = Inventory::load(&root).expect("security shape inventory"); 3011 let mut findings = Vec::new(); 3012 product_shell_audit(&root, &inventory, &mut findings); 3013 for expected in [ 3014 "retired parameterless confirmation source shape", 3015 "parser-on-edit source shape", 3016 "prefilled reference ingress source shape", 3017 "selected-as-disabled source shape", 3018 ] { 3019 assert!( 3020 findings.iter().any(|finding| finding.contains(expected)), 3021 "missing {expected}: {findings:?}" 3022 ); 3023 } 3024 fs::remove_dir_all(root).expect("remove fixture"); 3025 } 3026 3027 #[test] 3028 fn product_shell_audit_rejects_secret_custody_and_global_overlay_busy_shapes() { 3029 let root = fixture("secret-lifecycle-shapes"); 3030 write( 3031 &root, 3032 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/UnsafeDraft.kt", 3033 "data class EditImportDraft(val value: String)\ndata class State(val importDraft: String)\n", 3034 ); 3035 write( 3036 &root, 3037 "app/shared/src/commonMain/kotlin/org/harvestcircle/application/ShellOverlays.kt", 3038 "fun admit(state: State) = state.identity.busy\n", 3039 ); 3040 write( 3041 &root, 3042 "app/shared/src/commonMain/kotlin/org/harvestcircle/ui/shell/FoundationOverlayHost.kt", 3043 "fun FoundationOverlayHost(state: OverlayState, status: ShellStatusModel, busy: Boolean) = Unit\n", 3044 ); 3045 let inventory = Inventory::load(&root).expect("closure shape inventory"); 3046 let mut findings = Vec::new(); 3047 product_shell_audit(&root, &inventory, &mut findings); 3048 for expected in [ 3049 "raw String import-draft custody source shape", 3050 "copyable import-draft intent source shape", 3051 "unrelated identity busy state must not gate overlay admission", 3052 "global busy state must not enter the overlay host", 3053 ] { 3054 assert!( 3055 findings.iter().any(|finding| finding.contains(expected)), 3056 "missing {expected}: {findings:?}" 3057 ); 3058 } 3059 fs::remove_dir_all(root).expect("remove fixture"); 3060 } 3061 3062 #[test] 3063 fn repository_policy_rejects_nested_documentation_and_workflow_roots() { 3064 let root = fixture("nested-docs"); 3065 write(&root, "app/docs/notes.md", "fixture\n"); 3066 write(&root, "app/.github/workflows/remote.yml", "fixture\n"); 3067 let inventory = Inventory::load(&root).expect("nested docs inventory"); 3068 let mut findings = Vec::new(); 3069 repo_audit(&root, &inventory, &mut findings); 3070 assert!( 3071 findings 3072 .iter() 3073 .any(|finding| finding.starts_with("app/docs/")) 3074 ); 3075 assert!( 3076 findings 3077 .iter() 3078 .any(|finding| finding.starts_with("app/.github/workflows/")) 3079 ); 3080 fs::remove_dir_all(root).expect("remove fixture"); 3081 } 3082 3083 #[cfg(unix)] 3084 #[test] 3085 fn repository_policy_rejects_symbolic_links() { 3086 use std::os::unix::fs::symlink; 3087 let root = fixture("symlink"); 3088 write(&root, "outside.txt", "outside\n"); 3089 fs::create_dir_all(root.join("app")).expect("create app"); 3090 symlink(root.join("outside.txt"), root.join("app/escape.txt")).expect("create symlink"); 3091 assert!( 3092 Inventory::load(&root) 3093 .expect_err("symlink fails before audit dispatch") 3094 .contains("symbolic link") 3095 ); 3096 fs::remove_dir_all(root).expect("remove fixture"); 3097 } 3098 3099 #[cfg(unix)] 3100 #[test] 3101 fn git_inventory_rejects_an_intermediate_symbolic_link() { 3102 use std::os::unix::fs::symlink; 3103 3104 let root = fixture("git-inventory-intermediate-symlink"); 3105 initialize_git_fixture(&root); 3106 write(&root, "tracked/file.txt", "tracked\n"); 3107 add_git_fixture_path(&root, Path::new("tracked/file.txt")); 3108 fs::rename(root.join("tracked"), root.join("actual")).expect("move tracked directory"); 3109 symlink(root.join("actual"), root.join("tracked")).expect("create intermediate symlink"); 3110 3111 let error = Inventory::load(&root).expect_err("intermediate symlink must fail closed"); 3112 assert!(error.contains("Git inventory path traverses a symbolic link")); 3113 fs::remove_dir_all(root).expect("remove fixture"); 3114 } 3115 3116 #[cfg(unix)] 3117 #[test] 3118 fn git_inventory_rejects_invalid_utf8_before_filesystem_traversal() { 3119 use std::io::Write as _; 3120 use std::process::Stdio; 3121 3122 let root = fixture("git-inventory-invalid-utf8-symlink"); 3123 initialize_git_fixture(&root); 3124 write(&root, "blob.txt", "tracked\n"); 3125 let object = ProcessCommand::new("git") 3126 .arg("-C") 3127 .arg(&root) 3128 .args(["hash-object", "-w", "blob.txt"]) 3129 .output() 3130 .expect("write fixture blob"); 3131 assert!(object.status.success()); 3132 let object = String::from_utf8(object.stdout).expect("Git object ID is UTF-8"); 3133 let mut index_entry = format!("100644 blob {}\ttracked/", object.trim()).into_bytes(); 3134 index_entry.push(0x80); 3135 index_entry.extend_from_slice(b"/file.txt\0"); 3136 let mut update = ProcessCommand::new("git") 3137 .arg("-C") 3138 .arg(&root) 3139 .args(["update-index", "-z", "--index-info"]) 3140 .stdin(Stdio::piped()) 3141 .spawn() 3142 .expect("start hostile index update"); 3143 update 3144 .stdin 3145 .take() 3146 .expect("hostile index stdin") 3147 .write_all(&index_entry) 3148 .expect("write hostile index entry"); 3149 assert!( 3150 update 3151 .wait() 3152 .expect("finish hostile index update") 3153 .success() 3154 ); 3155 let error = 3156 Inventory::load(&root).expect_err("invalid UTF-8 inventory path must fail closed"); 3157 assert_eq!(error, "Git inventory path is not valid UTF-8"); 3158 fs::remove_dir_all(root).expect("remove fixture"); 3159 } 3160 3161 #[cfg(unix)] 3162 #[test] 3163 fn git_inventory_preserves_a_literal_backslash_without_aliasing_a_separator() { 3164 let root = fixture("git-inventory-backslash"); 3165 initialize_git_fixture(&root); 3166 write(&root, r"tracked\file.txt", "literal backslash\n"); 3167 write(&root, "tracked/file.txt", "path separator\n"); 3168 add_git_fixture_path(&root, Path::new(r"tracked\file.txt")); 3169 add_git_fixture_path(&root, Path::new("tracked/file.txt")); 3170 3171 let inventory = Inventory::load(&root).expect("distinct Git paths must remain distinct"); 3172 assert!(inventory.paths.contains(&r"tracked\file.txt".to_owned())); 3173 assert!(inventory.paths.contains(&"tracked/file.txt".to_owned())); 3174 fs::remove_dir_all(root).expect("remove fixture"); 3175 } 3176 3177 #[test] 3178 fn git_inventory_rejects_a_missing_leaf() { 3179 let root = fixture("git-inventory-missing-leaf"); 3180 initialize_git_fixture(&root); 3181 write(&root, "tracked/file.txt", "tracked\n"); 3182 add_git_fixture_path(&root, Path::new("tracked/file.txt")); 3183 fs::remove_file(root.join("tracked/file.txt")).expect("remove tracked file"); 3184 3185 let error = Inventory::load(&root).expect_err("missing inventory leaf must fail closed"); 3186 assert!(error.contains("Git inventory path is missing")); 3187 fs::remove_dir_all(root).expect("remove fixture"); 3188 } 3189 3190 #[test] 3191 fn git_inventory_rejects_a_directory_leaf() { 3192 let root = fixture("git-inventory-directory-leaf"); 3193 initialize_git_fixture(&root); 3194 write(&root, "tracked/file.txt", "tracked\n"); 3195 add_git_fixture_path(&root, Path::new("tracked/file.txt")); 3196 fs::remove_file(root.join("tracked/file.txt")).expect("remove tracked file"); 3197 fs::create_dir(root.join("tracked/file.txt")).expect("create directory leaf"); 3198 3199 let error = Inventory::load(&root).expect_err("directory inventory leaf must fail closed"); 3200 assert!(error.contains("Git inventory path is not a regular file")); 3201 fs::remove_dir_all(root).expect("remove fixture"); 3202 } 3203 3204 #[cfg(unix)] 3205 #[test] 3206 fn git_inventory_rejects_a_fifo_leaf_without_opening_it() { 3207 let root = fixture("git-inventory-fifo-leaf"); 3208 initialize_git_fixture(&root); 3209 write(&root, "tracked/file.txt", "tracked\n"); 3210 add_git_fixture_path(&root, Path::new("tracked/file.txt")); 3211 fs::remove_file(root.join("tracked/file.txt")).expect("remove tracked file"); 3212 assert!( 3213 ProcessCommand::new("mkfifo") 3214 .arg(root.join("tracked/file.txt")) 3215 .status() 3216 .expect("create FIFO leaf") 3217 .success() 3218 ); 3219 3220 let error = Inventory::load(&root).expect_err("FIFO inventory leaf must fail closed"); 3221 assert!(error.contains("Git inventory path is not a regular file")); 3222 fs::remove_dir_all(root).expect("remove fixture"); 3223 } 3224 3225 #[test] 3226 fn mutable_git_dependency_and_provenance_mutation_fail_closed() { 3227 let root = fixture("provenance"); 3228 write( 3229 &root, 3230 "core/deny.toml", 3231 "required-git-spec = \"rev\"\nallow-git = [\"https://example.invalid/lib\"]\n", 3232 ); 3233 write( 3234 &root, 3235 "core/Cargo.toml", 3236 "[dependencies]\nlib = { git = \"https://example.invalid/lib\", branch = \"main\" }\n", 3237 ); 3238 write(&root, "core/Cargo.lock", ""); 3239 let mut findings = Vec::new(); 3240 git_source_policy(&root, &Inventory::load(&root).unwrap(), &mut findings); 3241 assert!( 3242 findings 3243 .iter() 3244 .any(|finding| finding.contains("branch or tag")) 3245 ); 3246 assert!( 3247 findings 3248 .iter() 3249 .any(|finding| finding.contains("full revision pin")) 3250 ); 3251 3252 findings.clear(); 3253 let inventory = Inventory::load(&root).expect("archive inventory"); 3254 provenance_check(&root, &inventory, &mut findings); 3255 assert!( 3256 findings 3257 .iter() 3258 .any(|finding| finding.contains("exact source provenance changed")) 3259 ); 3260 assert!( 3261 findings 3262 .iter() 3263 .any(|finding| finding.contains("exact Lib source lock changed")) 3264 ); 3265 fs::remove_dir_all(root).expect("remove fixture"); 3266 } 3267 3268 #[test] 3269 fn source_lock_digest_rejects_actual_byte_mismatch() { 3270 let root = fixture("source-lock-digest"); 3271 write( 3272 &root, 3273 "radroots.lib.source-lock.v1.toml", 3274 concat!( 3275 "schema = \"radroots.lib.source-lock.v1\"\n", 3276 "repository = \"https://github.com/radrootslabs/lib\"\n", 3277 "revision = \"189c49b74b4bafc142b00b76b296477931139e72\"\n", 3278 "architecture = \"radroots.crates.release.v2\"\n", 3279 "workspace_catalog_sha256 = \"ee295f2352e2577a4052d980624415aec9871197d4fc9910a4c21c83a9179200\"\n", 3280 "version = \"0.1.0-alpha\"\n", 3281 "source_archive_sha256 = \"c648a3ab993d10253b9073e7e86db7b8970863bdf1d394d9fc30d66825695240\"\n", 3282 "lockfile = \"core/Cargo.lock\"\n", 3283 "lockfile_sha256 = \"b57fae5737cc9401d38f464c019b07d10c48c13ebcc9c9ac8593fe0fa61ffae8\"\n", 3284 ), 3285 ); 3286 write(&root, "core/Cargo.toml", ""); 3287 write(&root, "core/Cargo.lock", "version = 3\n"); 3288 let inventory = Inventory::load(&root).expect("source-lock inventory"); 3289 let mut findings = Vec::new(); 3290 provenance_check(&root, &inventory, &mut findings); 3291 assert!(findings.iter().any(|finding| { 3292 finding.contains("lockfile_sha256 does not match actual bounded no-follow bytes") 3293 })); 3294 fs::remove_dir_all(root).expect("remove fixture"); 3295 } 3296 3297 #[cfg(unix)] 3298 #[test] 3299 fn bounded_source_lock_reads_reject_final_and_intermediate_symlinks() { 3300 use std::os::unix::fs::symlink; 3301 3302 let root = fixture("source-lock-symlinks"); 3303 write(&root, "actual/Cargo.lock", "version = 4\n"); 3304 symlink(root.join("actual/Cargo.lock"), root.join("final.lock")) 3305 .expect("create final symlink"); 3306 assert!( 3307 bounded_no_follow_bytes(&root, Path::new("final.lock"), 1024) 3308 .expect_err("final symlink must fail") 3309 .contains("symbolic link") 3310 ); 3311 3312 symlink(root.join("actual"), root.join("core")).expect("create intermediate symlink"); 3313 assert!( 3314 bounded_no_follow_bytes(&root, Path::new("core/Cargo.lock"), 1024) 3315 .expect_err("intermediate symlink must fail") 3316 .contains("symbolic link") 3317 ); 3318 assert_eq!( 3319 bounded_no_follow_bytes(&root, Path::new("actual/Cargo.lock"), 1024) 3320 .expect("regular bounded file"), 3321 b"version = 4\n" 3322 ); 3323 assert!( 3324 bounded_no_follow_bytes(&root, Path::new("actual/Cargo.lock"), 1) 3325 .expect_err("oversize file must fail") 3326 .contains("byte limit") 3327 ); 3328 fs::remove_dir_all(root).expect("remove fixture"); 3329 } 3330 3331 fn fixture(name: &str) -> PathBuf { 3332 let nonce = SystemTime::now() 3333 .duration_since(UNIX_EPOCH) 3334 .expect("clock") 3335 .as_nanos(); 3336 let root = std::env::temp_dir().join(format!( 3337 "harvestcircle-xtask-{name}-{}-{nonce}", 3338 std::process::id() 3339 )); 3340 fs::create_dir_all(&root).expect("create fixture"); 3341 root 3342 } 3343 3344 fn initialize_git_fixture(root: &Path) { 3345 assert!( 3346 ProcessCommand::new("git") 3347 .arg("-C") 3348 .arg(root) 3349 .args(["init", "--quiet"]) 3350 .status() 3351 .expect("initialize Git fixture") 3352 .success() 3353 ); 3354 } 3355 3356 fn add_git_fixture_path(root: &Path, relative: &Path) { 3357 assert!( 3358 ProcessCommand::new("git") 3359 .arg("-C") 3360 .arg(root) 3361 .args(["add", "--"]) 3362 .arg(relative) 3363 .status() 3364 .expect("index tracked fixture") 3365 .success() 3366 ); 3367 } 3368 3369 fn write(root: &Path, relative: &str, source: &str) { 3370 let path = root.join(relative); 3371 fs::create_dir_all(path.parent().expect("fixture parent")).expect("create fixture parent"); 3372 fs::write(path, source).expect("write fixture"); 3373 } 3374 }