commit 1ccfd56b13576da00f1a679a072540e89f8a7e65
parent 827ee8ada5758af60006dea1a4eca3697a590799
Author: triesap <tyson@radroots.org>
Date: Sat, 3 Oct 2026 22:41:33 +0000
repo: harden repository-root and inventory validation (HCR-005)
- Validate HarvestCircle native root markers before every audit dispatch
- Confine Git inventory to standalone, linked, and nested capsule contexts
- Reject unsafe archive entries while preserving literal UTF-8 identities
- Exercise complete contexts and exclusive parallel fixtures in 54 tests
Diffstat:
2 files changed, 562 insertions(+), 25 deletions(-)
diff --git a/tools/xtask/src/lib.rs b/tools/xtask/src/lib.rs
@@ -36,6 +36,8 @@ impl FromStr for Command {
}
pub fn run(root: &Path, command: Command) -> Result<String, Vec<String>> {
+ let root = validate_product_root(root).map_err(|finding| vec![finding])?;
+ let root = root.as_path();
let build_mode =
std::env::var("HARVESTCIRCLE_BUILD_MODE").unwrap_or_else(|_| "standalone".to_owned());
if command == Command::QualificationReport
@@ -88,6 +90,99 @@ pub fn run(root: &Path, command: Command) -> Result<String, Vec<String>> {
}
}
+fn validate_product_root(root: &Path) -> Result<PathBuf, String> {
+ let metadata = fs::symlink_metadata(root)
+ .map_err(|error| format!("HarvestCircle product root cannot be inspected: {error}"))?;
+ if metadata.file_type().is_symlink() || !metadata.is_dir() {
+ return Err(
+ "HarvestCircle product root must be a directory, not a symbolic link".to_owned(),
+ );
+ }
+ let root = root
+ .canonicalize()
+ .map_err(|error| format!("HarvestCircle product root cannot be resolved: {error}"))?;
+ for marker in [
+ "Makefile",
+ "settings.gradle.kts",
+ "build.gradle.kts",
+ "gradlew",
+ "config/product/harvestcircle-v1.properties",
+ "radroots.lib.source-lock.v1.toml",
+ "core/Cargo.toml",
+ "core/Cargo.lock",
+ "core/rust-toolchain.toml",
+ "tools/xtask/Cargo.toml",
+ "tools/xtask/Cargo.lock",
+ "core/crates/harvestcircle_domain/Cargo.toml",
+ "core/crates/harvestcircle_domain/src/lib.rs",
+ "contracts/rshr-201-step-gates.v1.json",
+ "contracts/release/harvestcircle-artifact-contract.v3.json",
+ ] {
+ validate_git_inventory_path(&root, Path::new(marker))
+ .map_err(|finding| format!("invalid HarvestCircle product root: {finding}"))?;
+ }
+ for (manifest, identity) in [
+ (
+ "core/crates/harvestcircle_domain/Cargo.toml",
+ "harvestcircle_domain",
+ ),
+ ("tools/xtask/Cargo.toml", "harvestcircle_xtask"),
+ ] {
+ let source = bounded_no_follow_bytes(&root, Path::new(manifest), 1024 * 1024)
+ .map_err(|finding| format!("invalid HarvestCircle product root: {finding}"))?;
+ let source = std::str::from_utf8(&source)
+ .map_err(|_| format!("invalid HarvestCircle product root: {manifest} is not UTF-8"))?;
+ if !source
+ .lines()
+ .any(|line| line.trim() == format!("name = \"{identity}\""))
+ {
+ return Err(format!(
+ "invalid HarvestCircle product root: {manifest} has the wrong product identity"
+ ));
+ }
+ }
+ Ok(root)
+}
+
+fn git_command(root: &Path) -> ProcessCommand {
+ let mut command = ProcessCommand::new("git");
+ command.arg("-C").arg(root);
+ for variable in [
+ "GIT_DIR",
+ "GIT_WORK_TREE",
+ "GIT_INDEX_FILE",
+ "GIT_COMMON_DIR",
+ "GIT_OBJECT_DIRECTORY",
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
+ ] {
+ command.env_remove(variable);
+ }
+ command
+}
+
+fn has_git_context(root: &Path) -> Result<bool, String> {
+ for directory in root.ancestors() {
+ match fs::symlink_metadata(directory.join(".git")) {
+ Ok(metadata) => {
+ if metadata.file_type().is_symlink() || !(metadata.is_file() || metadata.is_dir()) {
+ return Err("Git metadata is not a regular file or directory".to_owned());
+ }
+ let output = git_command(root)
+ .args(["rev-parse", "--is-inside-work-tree"])
+ .output()
+ .map_err(|error| format!("unable to inspect Git context: {error}"))?;
+ if !output.status.success() || output.stdout != b"true\n" {
+ return Err("invalid Git metadata for HarvestCircle inventory".to_owned());
+ }
+ return Ok(true);
+ }
+ Err(error) if error.kind() == ErrorKind::NotFound => {}
+ Err(error) => return Err(format!("unable to inspect Git metadata: {error}")),
+ }
+ }
+ Ok(false)
+}
+
#[derive(Debug)]
struct Inventory {
paths: Vec<String>,
@@ -96,16 +191,16 @@ struct Inventory {
impl Inventory {
fn load(root: &Path) -> Result<Self, String> {
- if root.join(".git").exists() {
- let output = ProcessCommand::new("git")
+ if has_git_context(root)? {
+ let output = git_command(root)
.args([
- "-C",
- &root.to_string_lossy(),
"ls-files",
"--cached",
"--others",
"--exclude-standard",
"-z",
+ "--",
+ ".",
])
.output()
.map_err(|error| {
@@ -220,13 +315,24 @@ fn archive_paths(root: &Path, directory: &Path, paths: &mut Vec<String>) -> Resu
{
continue;
}
- paths.push(relative);
- if entry
+ let file_type = entry
.file_type()
- .map_err(|error| format!("unable to classify archive entry: {error}"))?
- .is_dir()
- {
+ .map_err(|error| format!("unable to classify archive entry: {error}"))?;
+ if file_type.is_symlink() {
+ return Err(format!(
+ "{relative}: archive inventory traverses a symbolic link"
+ ));
+ }
+ if !file_type.is_dir() && !file_type.is_file() {
+ return Err(format!(
+ "{relative}: archive inventory path is not a regular file"
+ ));
+ }
+ paths.push(relative.clone());
+ if file_type.is_dir() {
archive_paths(root, &path, paths)?;
+ } else {
+ validate_git_inventory_path(root, Path::new(&relative))?;
}
}
Ok(())
@@ -1874,9 +1980,20 @@ fn bounded_no_follow_bytes(root: &Path, relative: &Path, maximum: u64) -> Result
}
fn relative(root: &Path, path: &Path) -> Result<String, String> {
- path.strip_prefix(root)
- .map(|relative| relative.to_string_lossy().replace('\\', "/"))
- .map_err(|error| format!("{} is outside {}: {error}", path.display(), root.display()))
+ let relative = path
+ .strip_prefix(root)
+ .map_err(|error| format!("{} is outside {}: {error}", path.display(), root.display()))?;
+ relative
+ .components()
+ .map(|component| match component {
+ Component::Normal(value) => value
+ .to_str()
+ .map(str::to_owned)
+ .ok_or_else(|| "archive inventory path is not valid UTF-8".to_owned()),
+ _ => Err("archive inventory path must be normalized and relative".to_owned()),
+ })
+ .collect::<Result<Vec<_>, _>>()
+ .map(|parts| parts.join("/"))
}
#[cfg(test)]
@@ -1887,6 +2004,103 @@ mod tests {
const ROOT_GUIDANCE: &str = include_str!("../../../AGENTS.md");
const WEB_GUIDANCE: &str = include_str!("../../../web/AGENTS.md");
+ #[test]
+ fn root_validation_rejects_wrong_cwd_for_every_command() {
+ let root = fixture("wrong root with spaces");
+ for command in [
+ Command::DesignSourceAudit,
+ Command::RepoAudit,
+ Command::NamespaceAudit,
+ Command::ProvenanceCheck,
+ Command::QualificationReport,
+ ] {
+ let findings = run(&root, command).expect_err("wrong root must fail");
+ assert!(
+ findings
+ .iter()
+ .any(|finding| finding.contains("product root")),
+ "{findings:?}"
+ );
+ }
+ fs::remove_dir_all(root).expect("remove fixture");
+ }
+
+ #[test]
+ fn archive_inventory_preserves_literal_backslash_identity() {
+ let root = fixture("archive literal path");
+ write(&root, "web\\node_modules\\unsafe.ts", "source");
+ let inventory = Inventory::load(&root).expect("literal archive path");
+ assert!(
+ inventory
+ .paths
+ .iter()
+ .any(|path| path == "web\\node_modules\\unsafe.ts")
+ );
+ fs::remove_dir_all(root).expect("remove fixture");
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn archive_relative_paths_reject_invalid_utf8_and_escape() {
+ use std::os::unix::ffi::OsStringExt;
+ let root = fixture("archive path identity");
+ let invalid = root.join(std::ffi::OsString::from_vec(vec![0xff]));
+ assert!(
+ relative(&root, &invalid)
+ .expect_err("invalid UTF-8")
+ .contains("UTF-8")
+ );
+ assert!(relative(&root, &root.join("../escape.rs")).is_err());
+ assert!(relative(&root, Path::new("/unrelated/escape.rs")).is_err());
+ fs::remove_dir_all(root).expect("remove fixture");
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn archive_inventory_rejects_symlinks_and_fifo_before_audits() {
+ let root = fixture("unsafe archive");
+ std::os::unix::fs::symlink("/does-not-exist", root.join("unsafe.rs")).expect("symlink");
+ assert!(
+ Inventory::load(&root)
+ .expect_err("symlink must fail")
+ .contains("symbolic link")
+ );
+ fs::remove_file(root.join("unsafe.rs")).expect("remove symlink");
+ assert!(
+ ProcessCommand::new("mkfifo")
+ .arg(root.join("unsafe.rs"))
+ .status()
+ .expect("fifo")
+ .success()
+ );
+ assert!(
+ Inventory::load(&root)
+ .expect_err("FIFO must fail")
+ .contains("regular file")
+ );
+ fs::remove_dir_all(root).expect("remove fixture");
+ }
+
+ #[test]
+ fn nested_parent_inventory_is_confined_to_capsule() {
+ let parent = fixture("parent with spaces");
+ initialize_git_fixture(&parent);
+ write(&parent, "private.rs", "not capsule source");
+ write(&parent, "oss/capsule/source.rs", "capsule source");
+ let inventory = Inventory::load(&parent.join("oss/capsule")).expect("nested Git inventory");
+ assert!(inventory.git_aware);
+ assert_eq!(inventory.paths, ["source.rs"]);
+ fs::remove_dir_all(parent).expect("remove fixture");
+ }
+
+ #[test]
+ fn malformed_git_metadata_never_falls_back_to_archive() {
+ let root = fixture("broken git");
+ write(&root, ".git", "not a gitdir\n");
+ assert!(Inventory::load(&root).is_err());
+ fs::remove_dir_all(root).expect("remove fixture");
+ }
+
fn guidance_findings(root_source: &str, web_source: &str) -> Vec<String> {
let root = fixture("runtime-guidance");
write(&root, "AGENTS.md", root_source);
@@ -2362,6 +2576,15 @@ mod tests {
#[cfg(unix)]
std::os::unix::fs::symlink("/does-not-exist", root.join("link.css"))
.expect("source symlink");
+ #[cfg(unix)]
+ {
+ assert!(
+ Inventory::load(&root)
+ .expect_err("archive symlink must fail before audits")
+ .contains("symbolic link")
+ );
+ fs::remove_file(root.join("link.css")).expect("remove source symlink");
+ }
let inventory = Inventory::load(&root).expect("archive inventory");
let mut findings = Vec::new();
repo_audit(&root, &inventory, &mut findings);
@@ -2378,13 +2601,6 @@ mod tests {
&& finding.contains("regular file")),
"{findings:#?}"
);
- #[cfg(unix)]
- assert!(
- findings.iter().any(
- |finding| finding.starts_with("link.css:") && finding.contains("symbolic link")
- ),
- "{findings:#?}"
- );
fs::remove_dir_all(root).expect("remove fixture");
}
@@ -2732,13 +2948,10 @@ mod tests {
write(&root, "outside.txt", "outside\n");
fs::create_dir_all(root.join("app")).expect("create app");
symlink(root.join("outside.txt"), root.join("app/escape.txt")).expect("create symlink");
- let inventory = Inventory::load(&root).expect("archive inventory");
- let mut findings = Vec::new();
- repo_audit(&root, &inventory, &mut findings);
assert!(
- findings
- .iter()
- .any(|finding| finding.contains("symbolic links"))
+ Inventory::load(&root)
+ .expect_err("symlink fails before audit dispatch")
+ .contains("symbolic link")
);
fs::remove_dir_all(root).expect("remove fixture");
}
diff --git a/tools/xtask/tests/root_inventory.rs b/tools/xtask/tests/root_inventory.rs
@@ -0,0 +1,324 @@
+//! Exercise the public CLI against complete source copies, never the private parent.
+use std::fs;
+use std::path::{Path, PathBuf};
+use std::process::{Command, Output};
+use std::sync::atomic::{AtomicU64, Ordering};
+use std::time::{SystemTime, UNIX_EPOCH};
+
+struct Fixture(PathBuf);
+static NEXT_FIXTURE: AtomicU64 = AtomicU64::new(0);
+impl Fixture {
+ fn new() -> Self {
+ let nonce = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ Self::with_nonce(nonce)
+ }
+
+ fn with_nonce(nonce: u128) -> Self {
+ loop {
+ let sequence = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed);
+ let root = std::env::temp_dir().join(format!(
+ "harvestcircle root fixture {} {nonce} {sequence}",
+ std::process::id()
+ ));
+ match fs::create_dir(&root) {
+ Ok(()) => return Self(root),
+ Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
+ Err(error) => panic!("unable to create exclusive fixture {root:?}: {error}"),
+ }
+ }
+ }
+}
+impl Drop for Fixture {
+ fn drop(&mut self) {
+ if let Err(error) = fs::remove_dir_all(&self.0) {
+ if std::thread::panicking() {
+ eprintln!("fixture cleanup failed for {:?}: {error}", self.0);
+ } else {
+ panic!("fixture cleanup failed for {:?}: {error}", self.0);
+ }
+ }
+ }
+}
+
+#[test]
+fn simultaneous_identical_timestamps_create_distinct_owned_fixtures() {
+ let barrier = std::sync::Arc::new(std::sync::Barrier::new(8));
+ let workers = (0..8)
+ .map(|index| {
+ let barrier = barrier.clone();
+ std::thread::spawn(move || {
+ barrier.wait();
+ let fixture = Fixture::with_nonce(0);
+ fs::write(fixture.0.join("owner"), index.to_string()).unwrap();
+ (index, fixture)
+ })
+ })
+ .collect::<Vec<_>>();
+ let fixtures = workers
+ .into_iter()
+ .map(|worker| worker.join().unwrap())
+ .collect::<Vec<_>>();
+ let paths = fixtures
+ .iter()
+ .map(|(_, fixture)| &fixture.0)
+ .collect::<std::collections::BTreeSet<_>>();
+ assert_eq!(paths.len(), 8);
+ for (index, fixture) in &fixtures {
+ assert_eq!(
+ fs::read_to_string(fixture.0.join("owner")).unwrap(),
+ index.to_string()
+ );
+ }
+}
+
+fn git(root: &Path, arguments: &[&str]) -> Output {
+ let output = Command::new("git")
+ .arg("-C")
+ .arg(root)
+ .args(arguments)
+ .env_remove("GIT_DIR")
+ .env_remove("GIT_WORK_TREE")
+ .env_remove("GIT_INDEX_FILE")
+ .env("GIT_CONFIG_NOSYSTEM", "1")
+ .env("GIT_CONFIG_GLOBAL", "/dev/null")
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "Git fixture failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ output
+}
+
+fn copy_source(root: &Path) {
+ fs::create_dir_all(root).unwrap();
+ let source = Path::new(env!("CARGO_MANIFEST_DIR"))
+ .parent()
+ .unwrap()
+ .parent()
+ .unwrap();
+ copy_archive_source(source, source, root);
+}
+
+// No Git prerequisite: these CLI tests also run from a clean source archive.
+fn copy_archive_source(source: &Path, directory: &Path, destination: &Path) {
+ for entry in fs::read_dir(directory).unwrap() {
+ let entry = entry.unwrap();
+ let path = entry.path();
+ let relative = path.strip_prefix(source).unwrap();
+ let parts = relative
+ .components()
+ .map(|part| part.as_os_str().to_str().unwrap())
+ .collect::<Vec<_>>();
+ if matches!(
+ parts[0],
+ ".git" | ".gradle" | ".kotlin" | ".idea" | "build" | "target" | "out"
+ ) || parts
+ .iter()
+ .any(|part| matches!(*part, "build" | "target" | "out"))
+ || (matches!(parts[0], "build-logic" | "buildSrc")
+ && parts
+ .get(1)
+ .is_some_and(|part| matches!(*part, ".gradle" | ".kotlin")))
+ || (parts[0] == "web"
+ && (parts.contains(&"node_modules")
+ || parts.get(1).is_some_and(|part| {
+ matches!(
+ *part,
+ ".svelte-kit" | "coverage" | "test-results" | "playwright-report"
+ )
+ })))
+ {
+ continue;
+ }
+ let file_type = entry.file_type().unwrap();
+ assert!(
+ !file_type.is_symlink(),
+ "fixture source symlink: {relative:?}"
+ );
+ if file_type.is_dir() {
+ fs::create_dir_all(destination.join(relative)).unwrap();
+ copy_archive_source(source, &path, destination);
+ } else {
+ assert!(
+ file_type.is_file(),
+ "fixture source is not regular: {relative:?}"
+ );
+ fs::create_dir_all(destination.join(relative).parent().unwrap()).unwrap();
+ fs::copy(&path, destination.join(relative)).unwrap();
+ }
+ }
+}
+
+fn cli(root: &Path, command: &str) -> Output {
+ Command::new(env!("CARGO_BIN_EXE_harvestcircle_xtask"))
+ .current_dir(root)
+ .arg(command)
+ .env("HARVESTCIRCLE_BUILD_MODE", "standalone")
+ .output()
+ .unwrap()
+}
+
+fn assert_pass(root: &Path, kind: &str) {
+ let output = cli(root, "qualification-report");
+ assert!(
+ output.status.success(),
+ "CLI failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ String::from_utf8(output.stdout)
+ .unwrap()
+ .contains(&format!("inventory={kind}"))
+ );
+}
+
+#[test]
+fn complete_archive_checkout_nested_parent_and_linked_worktree_pass() {
+ let fixture = Fixture::new();
+ let capsule = fixture.0.join("public capsule");
+ copy_source(&capsule);
+ assert_pass(&capsule, "archive");
+ let second_archive = fixture.0.join("copied clean archive");
+ fs::create_dir_all(&second_archive).unwrap();
+ copy_archive_source(&capsule, &capsule, &second_archive);
+ assert_pass(&second_archive, "archive");
+ fs::remove_dir_all(second_archive).unwrap();
+ // An intentionally unsafe private source must never enter capsule inventory.
+ fs::write(
+ fixture.0.join("private.rs"),
+ ["-----BEGIN ", "PRIVATE KEY-----"].concat(),
+ )
+ .unwrap();
+ git(&fixture.0, &["init", "--quiet"]);
+ git(&fixture.0, &["add", "--", "private.rs", "public capsule"]);
+ assert_pass(&capsule, "git");
+ // A standalone capsule repository remains independently usable.
+ git(&capsule, &["init", "--quiet"]);
+ git(&capsule, &["add", "--", "."]);
+ git(
+ &capsule,
+ &[
+ "-c",
+ "user.name=Fixture",
+ "-c",
+ "user.email=fixture@example.invalid",
+ "-c",
+ "commit.gpgsign=false",
+ "commit",
+ "--quiet",
+ "-m",
+ "fixture",
+ ],
+ );
+ assert_pass(&capsule, "git");
+ let linked = fixture.0.join("linked capsule with spaces");
+ git(
+ &capsule,
+ &[
+ "worktree",
+ "add",
+ "--quiet",
+ "--detach",
+ linked.to_str().unwrap(),
+ ],
+ );
+ assert!(linked.join(".git").is_file());
+ assert_pass(&linked, "git");
+}
+
+#[test]
+fn cli_rejects_wrong_cwd_missing_native_markers_and_corrupt_git() {
+ let fixture = Fixture::new();
+ let capsule = fixture.0.join("capsule");
+ copy_source(&capsule);
+ for command in [
+ "design-source-audit",
+ "repo-audit",
+ "namespace-audit",
+ "provenance-check",
+ "qualification-report",
+ ] {
+ for root in [&fixture.0, &capsule.join("core"), &capsule.join("web")] {
+ let output = cli(root, command);
+ assert!(!output.status.success());
+ assert!(
+ String::from_utf8(output.stderr)
+ .unwrap()
+ .contains("product root")
+ );
+ }
+ }
+ for marker in [
+ "core/crates/harvestcircle_domain/src/lib.rs",
+ "core/Cargo.lock",
+ "core/rust-toolchain.toml",
+ "tools/xtask/Cargo.lock",
+ "contracts/rshr-201-step-gates.v1.json",
+ ] {
+ let path = capsule.join(marker);
+ let saved = fs::read(&path).unwrap();
+ fs::remove_file(&path).unwrap();
+ for command in [
+ "design-source-audit",
+ "repo-audit",
+ "namespace-audit",
+ "provenance-check",
+ "qualification-report",
+ ] {
+ let output = cli(&capsule, command);
+ assert!(!output.status.success(), "accepted missing {marker}");
+ assert!(String::from_utf8(output.stderr).unwrap().contains(marker));
+ }
+ fs::write(path, saved).unwrap();
+ }
+ fs::write(capsule.join(".git"), "gitdir: /does-not-exist\n").unwrap();
+ let output = cli(&capsule, "qualification-report");
+ assert!(!output.status.success());
+ assert!(
+ String::from_utf8(output.stderr)
+ .unwrap()
+ .contains("Git metadata")
+ );
+}
+
+#[cfg(unix)]
+#[test]
+fn full_archive_rejects_native_symlink_parent_and_invalid_path_bytes() {
+ use std::os::unix::fs::symlink;
+ let fixture = Fixture::new();
+ let capsule = fixture.0.join("capsule");
+ copy_source(&capsule);
+ let real_core = fixture.0.join("outside core");
+ fs::rename(capsule.join("core"), &real_core).unwrap();
+ symlink(&real_core, capsule.join("core")).unwrap();
+ let output = cli(&capsule, "qualification-report");
+ assert!(!output.status.success());
+ assert!(
+ String::from_utf8(output.stderr)
+ .unwrap()
+ .contains("symbolic link")
+ );
+ fs::remove_file(capsule.join("core")).unwrap();
+ fs::rename(real_core, capsule.join("core")).unwrap();
+ let alias = fixture.0.join("aliased capsule");
+ symlink(&capsule, &alias).unwrap();
+ assert!(
+ harvestcircle_xtask::run(&alias, harvestcircle_xtask::Command::QualificationReport)
+ .is_err()
+ );
+ // Linux supports non-UTF-8 filenames; macOS rejects their creation with EILSEQ.
+ #[cfg(target_os = "linux")]
+ {
+ use std::os::unix::ffi::OsStringExt;
+ let invalid = capsule.join(std::ffi::OsString::from_vec(vec![b'x', 0xff]));
+ fs::write(&invalid, "source").unwrap();
+ let output = cli(&capsule, "qualification-report");
+ assert!(!output.status.success());
+ assert!(String::from_utf8(output.stderr).unwrap().contains("UTF-8"));
+ }
+}