app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

root_inventory.rs (15954B)


      1 //! Exercise the public CLI against complete source copies, never the private parent.
      2 use std::fs;
      3 use std::path::{Path, PathBuf};
      4 use std::process::{Command, Output};
      5 use std::sync::atomic::{AtomicU64, Ordering};
      6 use std::time::{SystemTime, UNIX_EPOCH};
      7 
      8 struct Fixture(PathBuf);
      9 static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);
     10 impl Fixture {
     11     fn new() -> Self {
     12         let nonce = SystemTime::now()
     13             .duration_since(UNIX_EPOCH)
     14             .unwrap()
     15             .as_nanos();
     16         Self::with_nonce(nonce)
     17     }
     18 
     19     fn with_nonce(nonce: u128) -> Self {
     20         Self::in_directory(&std::env::temp_dir(), nonce)
     21     }
     22 
     23     fn in_directory(directory: &Path, nonce: u128) -> Self {
     24         loop {
     25             let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed);
     26             let root = directory.join(format!(
     27                 "harvestcircle root fixture {} {nonce} {sequence}",
     28                 std::process::id()
     29             ));
     30             match fs::create_dir(&root) {
     31                 Ok(()) => return Self(root),
     32                 Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
     33                 Err(error) => panic!(
     34                     "unable to create exclusive fixture {root:?}; fixture filesystem must exist and have sufficient writable capacity: {error}"
     35                 ),
     36             }
     37         }
     38     }
     39 }
     40 impl Drop for Fixture {
     41     fn drop(&mut self) {
     42         if let Err(error) = fs::remove_dir_all(&self.0) {
     43             if std::thread::panicking() {
     44                 eprintln!("fixture cleanup failed for {:?}: {error}", self.0);
     45             } else {
     46                 panic!("fixture cleanup failed for {:?}: {error}", self.0);
     47             }
     48         }
     49     }
     50 }
     51 
     52 #[test]
     53 fn simultaneous_identical_timestamps_create_distinct_owned_fixtures() {
     54     let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
     55     let workers = (0..8)
     56         .map(|index| {
     57             let barrier = barrier.clone();
     58             std::thread::spawn(move || {
     59                 barrier.wait();
     60                 let fixture = Fixture::with_nonce(0);
     61                 fs::write(fixture.0.join("owner"), index.to_string()).unwrap();
     62                 (index, fixture)
     63             })
     64         })
     65         .collect::<Vec<_>>();
     66     let fixtures = workers
     67         .into_iter()
     68         .map(|worker| worker.join().unwrap())
     69         .collect::<Vec<_>>();
     70     let paths = fixtures
     71         .iter()
     72         .map(|(_, fixture)| &fixture.0)
     73         .collect::<std::collections::BTreeSet<_>>();
     74     assert_eq!(paths.len(), 8);
     75     for (index, fixture) in &fixtures {
     76         assert_eq!(
     77             fs::read_to_string(fixture.0.join("owner")).unwrap(),
     78             index.to_string()
     79         );
     80     }
     81 }
     82 
     83 fn git(root: &Path, arguments: &[&str]) -> Output {
     84     let output = Command::new("git")
     85         .arg("-C")
     86         .arg(root)
     87         .args(arguments)
     88         .env_remove("GIT_DIR")
     89         .env_remove("GIT_WORK_TREE")
     90         .env_remove("GIT_INDEX_FILE")
     91         .env("GIT_CONFIG_NOSYSTEM", "1")
     92         .env("GIT_CONFIG_GLOBAL", "/dev/null")
     93         .output()
     94         .unwrap();
     95     assert!(
     96         output.status.success(),
     97         "Git fixture failed: {}",
     98         String::from_utf8_lossy(&output.stderr)
     99     );
    100     output
    101 }
    102 
    103 fn copy_source(root: &Path) {
    104     fs::create_dir_all(root).unwrap();
    105     let source = Path::new(env!("CARGO_MANIFEST_DIR"))
    106         .parent()
    107         .unwrap()
    108         .parent()
    109         .unwrap();
    110     copy_archive_source(source, source, root);
    111 }
    112 
    113 // No Git prerequisite: these CLI tests also run from a clean source archive.
    114 fn copy_archive_source(source: &Path, directory: &Path, destination: &Path) {
    115     for entry in fs::read_dir(directory).unwrap() {
    116         let entry = entry.unwrap();
    117         let path = entry.path();
    118         let relative = path.strip_prefix(source).unwrap();
    119         let parts = relative
    120             .components()
    121             .map(|part| part.as_os_str().to_str().unwrap())
    122             .collect::<Vec<_>>();
    123         if matches!(
    124             parts[0],
    125             ".git" | ".gradle" | ".kotlin" | ".idea" | "build" | "target" | "out"
    126         ) || parts
    127             .iter()
    128             .any(|part| matches!(*part, "build" | "target" | "out"))
    129             || (matches!(parts[0], "build-logic" | "buildSrc")
    130                 && parts
    131                     .get(1)
    132                     .is_some_and(|part| matches!(*part, ".gradle" | ".kotlin")))
    133             || (parts[0] == "web"
    134                 && (parts.contains(&"node_modules")
    135                     || parts.get(1).is_some_and(|part| {
    136                         matches!(
    137                             *part,
    138                             ".svelte-kit" | "coverage" | "test-results" | "playwright-report"
    139                         )
    140                     })))
    141         {
    142             continue;
    143         }
    144         let file_type = entry.file_type().unwrap();
    145         assert!(
    146             !file_type.is_symlink(),
    147             "fixture source symlink: {relative:?}"
    148         );
    149         if file_type.is_dir() {
    150             fs::create_dir_all(destination.join(relative)).unwrap();
    151             copy_archive_source(source, &path, destination);
    152         } else {
    153             assert!(
    154                 file_type.is_file(),
    155                 "fixture source is not regular: {relative:?}"
    156             );
    157             fs::create_dir_all(destination.join(relative).parent().unwrap()).unwrap();
    158             fs::copy(&path, destination.join(relative)).unwrap();
    159         }
    160     }
    161 }
    162 
    163 fn cli(root: &Path, command: &str) -> Output {
    164     Command::new(env!("CARGO_BIN_EXE_harvestcircle_xtask"))
    165         .current_dir(root)
    166         .arg(command)
    167         .env("HARVESTCIRCLE_BUILD_MODE", "standalone")
    168         .output()
    169         .unwrap()
    170 }
    171 
    172 fn assert_pass(root: &Path, kind: &str) {
    173     let output = cli(root, "qualification-report");
    174     assert!(
    175         output.status.success(),
    176         "CLI failed: {}",
    177         String::from_utf8_lossy(&output.stderr)
    178     );
    179     assert!(
    180         String::from_utf8(output.stdout)
    181             .unwrap()
    182             .contains(&format!("inventory={kind}"))
    183     );
    184 }
    185 
    186 #[test]
    187 fn ownership_dispatch_keeps_global_safety_and_native_guards_active() {
    188     let fixture = Fixture::new();
    189     let capsule = fixture.0.join("capsule");
    190     copy_source(&capsule);
    191     fs::create_dir_all(capsule.join("web/src")).unwrap();
    192     // These are native implementation rules, not browser product policy.
    193     fs::write(
    194         capsule.join("web/src/ordinary.json"),
    195         [
    196             "{\"example\":\"",
    197             "stu",
    198             "dio",
    199             " org.",
    200             "radroots.",
    201             "harvestcircle use_",
    202             "radroots_dns\"}",
    203         ]
    204         .concat(),
    205     )
    206     .unwrap();
    207     assert_pass(&capsule, "archive");
    208     for command in [
    209         "design-source-audit",
    210         "repo-audit",
    211         "namespace-audit",
    212         "provenance-check",
    213         "qualification-report",
    214     ] {
    215         fs::write(
    216             capsule.join("web/src/unsafe.ts"),
    217             ["-----BEGIN ", "PRIVATE KEY-----"].concat(),
    218         )
    219         .unwrap();
    220         let output = cli(&capsule, command);
    221         assert!(!output.status.success(), "{command} skipped global safety");
    222         assert!(
    223             String::from_utf8(output.stderr)
    224                 .unwrap()
    225                 .contains("unsafe.ts")
    226         );
    227         fs::remove_file(capsule.join("web/src/unsafe.ts")).unwrap();
    228     }
    229     fs::write(
    230         capsule.join("core/crates/harvestcircle_domain/src/relay.rs"),
    231         "// forbidden second policy",
    232     )
    233     .unwrap();
    234     let output = cli(&capsule, "qualification-report");
    235     assert!(!output.status.success());
    236     assert!(
    237         String::from_utf8(output.stderr)
    238             .unwrap()
    239             .contains("duplicate relay")
    240     );
    241 }
    242 
    243 #[test]
    244 fn invalid_native_source_and_required_license_cannot_pass() {
    245     let fixture = Fixture::new();
    246     let capsule = fixture.0.join("capsule");
    247     copy_source(&capsule);
    248     for path in [
    249         "core/crates/harvestcircle_domain/src/lib.rs",
    250         "LICENSES/GPL-3.0-only.txt",
    251     ] {
    252         let saved = fs::read(capsule.join(path)).unwrap();
    253         fs::write(capsule.join(path), [0xff]).unwrap();
    254         let output = cli(&capsule, "qualification-report");
    255         assert!(!output.status.success(), "accepted invalid {path}");
    256         assert!(String::from_utf8(output.stderr).unwrap().contains(path));
    257         fs::write(capsule.join(path), saved).unwrap();
    258     }
    259 }
    260 
    261 #[test]
    262 fn git_global_artifacts_fail_each_command_and_unknown_inputs_retain_native_rules() {
    263     let fixture = Fixture::new();
    264     let capsule = fixture.0.join("capsule");
    265     copy_source(&capsule);
    266     git(&capsule, &["init", "--quiet"]);
    267     git(&capsule, &["add", "--", "."]);
    268     fs::create_dir_all(capsule.join("web/build")).unwrap();
    269     fs::write(capsule.join("web/build/index.html"), "generated").unwrap();
    270     git(&capsule, &["add", "--force", "--", "web/build/index.html"]);
    271     for command in [
    272         "design-source-audit",
    273         "repo-audit",
    274         "namespace-audit",
    275         "provenance-check",
    276         "qualification-report",
    277     ] {
    278         let output = cli(&capsule, command);
    279         assert!(!output.status.success());
    280         assert!(
    281             String::from_utf8(output.stderr)
    282                 .unwrap()
    283                 .contains("generated build output")
    284         );
    285     }
    286     git(&capsule, &["rm", "--force", "--", "web/build/index.html"]);
    287     fs::write(
    288         capsule.join("unknown.json"),
    289         ["org.", "radroots.", "harvestcircle"].concat(),
    290     )
    291     .unwrap();
    292     let output = cli(&capsule, "namespace-audit");
    293     assert!(
    294         !output.status.success(),
    295         "unknown input bypassed native rules"
    296     );
    297     assert!(
    298         String::from_utf8(output.stderr)
    299             .unwrap()
    300             .contains("unknown.json: temporary product namespace")
    301     );
    302     fs::write(capsule.join("unknown.json"), "{}").unwrap();
    303     let output = cli(&capsule, "qualification-report");
    304     assert!(
    305         output.status.success(),
    306         "{}",
    307         String::from_utf8_lossy(&output.stderr)
    308     );
    309     let report = String::from_utf8(output.stdout).unwrap();
    310     assert!(report.contains("ownership_reason=unclassified input unknown.json"));
    311     assert!(report.contains("web_qualification=unclaimed"));
    312 }
    313 
    314 #[test]
    315 fn complete_archive_checkout_nested_parent_and_linked_worktree_pass() {
    316     let fixture = Fixture::new();
    317     let capsule = fixture.0.join("public capsule");
    318     copy_source(&capsule);
    319     assert_pass(&capsule, "archive");
    320     let second_archive = fixture.0.join("copied clean archive");
    321     fs::create_dir_all(&second_archive).unwrap();
    322     copy_archive_source(&capsule, &capsule, &second_archive);
    323     assert_pass(&second_archive, "archive");
    324     fs::remove_dir_all(second_archive).unwrap();
    325     // An intentionally unsafe private source must never enter capsule inventory.
    326     fs::write(
    327         fixture.0.join("private.rs"),
    328         ["-----BEGIN ", "PRIVATE KEY-----"].concat(),
    329     )
    330     .unwrap();
    331     git(&fixture.0, &["init", "--quiet"]);
    332     git(&fixture.0, &["add", "--", "private.rs", "public capsule"]);
    333     assert_pass(&capsule, "git");
    334     // A standalone capsule repository remains independently usable.
    335     git(&capsule, &["init", "--quiet"]);
    336     git(&capsule, &["add", "--", "."]);
    337     git(
    338         &capsule,
    339         &[
    340             "-c",
    341             "user.name=Fixture",
    342             "-c",
    343             "user.email=fixture@example.invalid",
    344             "-c",
    345             "commit.gpgsign=false",
    346             "commit",
    347             "--quiet",
    348             "-m",
    349             "fixture",
    350         ],
    351     );
    352     assert_pass(&capsule, "git");
    353     let linked = fixture.0.join("linked capsule with spaces");
    354     git(
    355         &capsule,
    356         &[
    357             "worktree",
    358             "add",
    359             "--quiet",
    360             "--detach",
    361             linked.to_str().unwrap(),
    362         ],
    363     );
    364     assert!(linked.join(".git").is_file());
    365     assert_pass(&linked, "git");
    366 }
    367 
    368 #[test]
    369 fn cli_rejects_wrong_cwd_missing_native_markers_and_corrupt_git() {
    370     let fixture = Fixture::new();
    371     let capsule = fixture.0.join("capsule");
    372     copy_source(&capsule);
    373     for command in [
    374         "design-source-audit",
    375         "repo-audit",
    376         "namespace-audit",
    377         "provenance-check",
    378         "qualification-report",
    379     ] {
    380         for root in [&fixture.0, &capsule.join("core"), &capsule.join("web")] {
    381             let output = cli(root, command);
    382             assert!(!output.status.success());
    383             assert!(
    384                 String::from_utf8(output.stderr)
    385                     .unwrap()
    386                     .contains("product root")
    387             );
    388         }
    389     }
    390     for marker in [
    391         "core/crates/harvestcircle_domain/src/lib.rs",
    392         "core/Cargo.lock",
    393         "core/rust-toolchain.toml",
    394         "tools/xtask/Cargo.lock",
    395         "contracts/rshr-201-step-gates.v1.json",
    396     ] {
    397         let path = capsule.join(marker);
    398         let saved = fs::read(&path).unwrap();
    399         fs::remove_file(&path).unwrap();
    400         for command in [
    401             "design-source-audit",
    402             "repo-audit",
    403             "namespace-audit",
    404             "provenance-check",
    405             "qualification-report",
    406         ] {
    407             let output = cli(&capsule, command);
    408             assert!(!output.status.success(), "accepted missing {marker}");
    409             assert!(String::from_utf8(output.stderr).unwrap().contains(marker));
    410         }
    411         fs::write(path, saved).unwrap();
    412     }
    413     fs::write(capsule.join(".git"), "gitdir: /does-not-exist\n").unwrap();
    414     let output = cli(&capsule, "qualification-report");
    415     assert!(!output.status.success());
    416     assert!(
    417         String::from_utf8(output.stderr)
    418             .unwrap()
    419             .contains("Git metadata")
    420     );
    421 }
    422 
    423 #[cfg(unix)]
    424 #[test]
    425 fn full_archive_rejects_native_symlink_parent_and_invalid_path_bytes() {
    426     use std::os::unix::fs::symlink;
    427     let fixture = Fixture::new();
    428     let capsule = fixture.0.join("capsule");
    429     copy_source(&capsule);
    430     let real_core = fixture.0.join("outside core");
    431     fs::rename(capsule.join("core"), &real_core).unwrap();
    432     symlink(&real_core, capsule.join("core")).unwrap();
    433     let output = cli(&capsule, "qualification-report");
    434     assert!(!output.status.success());
    435     assert!(
    436         String::from_utf8(output.stderr)
    437             .unwrap()
    438             .contains("symbolic link")
    439     );
    440     fs::remove_file(capsule.join("core")).unwrap();
    441     fs::rename(real_core, capsule.join("core")).unwrap();
    442     let alias = fixture.0.join("aliased capsule");
    443     symlink(&capsule, &alias).unwrap();
    444     assert!(
    445         harvestcircle_xtask::run(&alias, harvestcircle_xtask::Command::QualificationReport)
    446             .is_err()
    447     );
    448     // Linux supports non-UTF-8 filenames; macOS rejects their creation with EILSEQ.
    449     #[cfg(target_os = "linux")]
    450     {
    451         use std::os::unix::ffi::{OsStrExt, OsStringExt};
    452         // Container bind-mounted temporary directories may normalize invalid
    453         // filename bytes; native Linux tmpfs is required for this case.
    454         let native_fixture = Fixture::in_directory(Path::new("/dev/shm"), 0);
    455         let native_capsule = native_fixture.0.join("capsule");
    456         copy_source(&native_capsule);
    457         let invalid_name = std::ffi::OsString::from_vec(vec![b'x', 0xff]);
    458         fs::write(native_capsule.join(&invalid_name), "source")
    459             .expect("native Linux tmpfs must admit invalid filename bytes and have capacity");
    460         assert!(
    461             fs::read_dir(&native_capsule)
    462                 .unwrap()
    463                 .any(|entry| { entry.unwrap().file_name().as_bytes() == invalid_name.as_bytes() }),
    464             "native Linux fixture filesystem must preserve exact invalid filename bytes"
    465         );
    466         let output = cli(&native_capsule, "qualification-report");
    467         assert!(!output.status.success());
    468         assert!(String::from_utf8(output.stderr).unwrap().contains("UTF-8"));
    469     }
    470 }