lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

commit b70eb707d9b8fd6efe05bafb6f7960ba89a8b141
parent 9100e33c8f9511f9e6ffa13486a89fbefb13c71d
Author: triesap <tyson@radroots.org>
Date:   Wed, 14 Oct 2026 00:07:58 +0000

xtask: Reject nonregular prototype scanner inputs

- Reuse bounded descriptor admission for Unix text input reads.
- Reject selected fallback objects before they can be silently omitted.
- Retain seven controlled scanner regressions and all existing policy modes.
- Record exact local qualification with producer and platform gaps explicit.

Diffstat:
Mcontracts/architecture/deviations.toml | 29+++++++++++++++++++++++++++++
Mtools/xtask/src/hygiene.rs | 69++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Atools/xtask/src/hygiene/prototype_input_tests.rs | 303+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 390 insertions(+), 11 deletions(-)

diff --git a/contracts/architecture/deviations.toml b/contracts/architecture/deviations.toml @@ -2,6 +2,35 @@ schema_version = 1 architecture_id = "radroots.crates.release.v1" [[deviation]] +id = "RCRV1-DEV-037" +date = "2026-10-13" +status = "closed" +approval = "The user approved the successor refactor, scoped execution/recovery amendments and all remaining local verified checkpoints; publication and supported consumer qualification remain separate." +affected_steps = ["010", "130"] +spec_anchors = ["contracts/crates/release_v1/radroots_crates_release_v1.toml#repository_policy"] +source_evidence = [ + "Complete current hygiene review shows that the Git inventory can select nonregular textual entries before plain File::open; fallback traversal can silently omit those inputs.", + "Fresh public integration source retains the same scanner bodies; the local predecessor correction only changes conformance discovery and does not repair this independent caller.", +] +replacement_action = "Bring forward contained prototype text-input admission after causal retained proving. Reuse existing private Unix descriptor-bound one-link, no-follow and nonblocking bounded reads; preserve bounded regular-file behavior on other tooling hosts. Reject selected nonregular fallback inputs rather than silently omit them. Preserve prototype patterns, report-only/strict modes, allowances, public APIs, dependencies, generated outputs and historical qualification." +verification = [ + "Validate this prospective deviation before production edits. Seven retained cases use disposable roots with at most four input directories, 32 total directories and 64 total files including a fixed Git scaffold, one authority of at most 1 KiB, two regular text files and one FIFO, socket or link; tests assert total object counts.", + "Run byte-identical tests against unchanged and corrected production. Only one owned child may attempt a FIFO scan; bound it to two seconds, 8 KiB streams, closed stdin and a fixture-only replacement environment with process-group termination/reaping. Fixture Git and mkfifo setup have five-second and 1 KiB limits.", + "Retain prompt nonregular admission, exact regular UTF-8/byte ceilings, link-target bytes and object types, and actual report-only/strict outcomes. No network, signer, account, application state or recursive cycle is involved.", + "Run exact Rust 1.99.0 formatting, locked all-feature/all-target xtask checks and all cases, warning-denied Clippy, actual architecture/contract, forbidden/prototype hygiene and generated-root freshness; review exact owner paths before a local commit.", +] +unresolved_risk = "The contained scanner input correction is locally qualified on macOS arm64. Other tooling hosts and actual Linux execution, Git process deadlines, whole traversal/aggregate complexity, legacy forbidden-identifier helpers, complete producer/platform/resource qualification and supported consumer adoption remain separate. Report-only success retains 94 findings and four allowances and cannot claim strict or zero-finding acceptance; two existing canonical native/WASM producer cases remain explicitly ignored in the default xtask suite." +normative_architecture_change = false +adr_required = false +closure_evidence = [ + "Prospective standalone architecture validation passed before production edits. The initial seven compiled cases have four causal failures and three passing controls: a tracked FIFO reaches blocking open and the bounded owned child hits its deadline; fallback FIFO/socket inputs are omitted with success; the Git socket reaches file open. Fixture setup, byte bounds and symlink-target controls pass.", + "Pre-production warning-denied Clippy found one test-only collapsible-if style issue. After that correction, the complete unchanged-production repeat has the same four causal failures and three passing controls. The corrected seven-test source remains byte-identical through green and full qualification; there are no ignored regression cases or application effects.", + "Unix scanner reads now reuse existing private descriptor-bound, one-link, no-follow and nonblocking bounded file admission with revalidation and exact byte/UTF-8 errors. Selected nonregular fallback text entries now fail admission instead of being silently omitted. Non-Unix code preserves bounded regular-file reading with explicit path and opened-object type checks; that execution remains unqualified here.", + "All seven retained cases pass after correction. Final exact Rust 1.99.0 formatting, locked all-feature/all-target xtask check and warning-denied Clippy pass. The complete all-target xtask suite passes 592 cases with zero failures or filtered cases; the same two existing canonical native/WASM producer cases remain explicitly ignored. Existing shared file/process admission and all original xtask controls remain green.", + "Actual standalone contract validation, forbidden-identifier hygiene and generated DTO-root freshness pass without changing source or generated bytes. The actual prototype command passes its existing report-only contract with 94 findings and four allowances; no strict cleanup or zero-finding claim is made. Patterns, modes, allowances, dependencies, locks, public APIs and historical evidence remain unchanged. Final closed-deviation architecture validation and exact source/status review are required before the local owner checkpoint; broader source, process, resource, platform, producer and consumer obligations stay open.", +] + +[[deviation]] id = "RCRV1-DEV-036" date = "2026-10-13" status = "closed" diff --git a/tools/xtask/src/hygiene.rs b/tools/xtask/src/hygiene.rs @@ -1049,17 +1049,55 @@ fn read_bounded_prototype_input( display_path: &str, max_file_bytes: u64, ) -> Result<String, String> { - let file = fs::File::open(path) - .map_err(|error| format!("open prototype guard input {display_path}: {error}"))?; - let mut bytes = Vec::new(); - file.take(max_file_bytes + 1) - .read_to_end(&mut bytes) - .map_err(|error| format!("read prototype guard input {display_path}: {error}"))?; - if bytes.len() as u64 > max_file_bytes { - return Err(format!( - "prototype guard input exceeds {max_file_bytes} bytes: {display_path}" - )); - } + #[cfg(unix)] + let bytes = { + use crate::safe_artifact_io::{ArtifactIoFailureKind, LimitKind}; + + crate::safe_artifact_io::read_regular_path(path, max_file_bytes).map_err(|error| { + match error.kind() { + ArtifactIoFailureKind::LimitExceeded(LimitKind::FileBytes) => format!( + "prototype guard input exceeds {max_file_bytes} bytes: {display_path}" + ), + ArtifactIoFailureKind::InvalidObject => format!( + "prototype guard input must be a regular single-link file without linked path components: {display_path}" + ), + _ => format!("admit prototype guard input {display_path}: {error}"), + } + })? + }; + #[cfg(not(unix))] + let bytes = { + let metadata = fs::symlink_metadata(path) + .map_err(|error| format!("inspect prototype guard input {display_path}: {error}"))?; + if metadata.file_type().is_symlink() || !metadata.is_file() { + return Err(format!( + "prototype guard input must be a regular non-symlink file: {display_path}" + )); + } + let file = fs::File::open(path) + .map_err(|error| format!("open prototype guard input {display_path}: {error}"))?; + if !file + .metadata() + .map_err(|error| { + format!("inspect opened prototype guard input {display_path}: {error}") + })? + .is_file() + { + return Err(format!( + "prototype guard input must be a regular file: {display_path}" + )); + } + let mut bytes = Vec::new(); + file.take(max_file_bytes + 1) + .read_to_end(&mut bytes) + .map_err(|error| format!("read prototype guard input {display_path}: {error}"))?; + if bytes.len() as u64 > max_file_bytes { + return Err(format!( + "prototype guard input exceeds {max_file_bytes} bytes: {display_path}" + )); + } + bytes + }; String::from_utf8(bytes) .map_err(|error| format!("prototype guard input is not UTF-8 {display_path}: {error}")) } @@ -1108,6 +1146,11 @@ fn collect_prototype_inputs( return Ok(()); } if !metadata.is_dir() { + if is_prototype_text_input(path, extensions, extensionless_names) { + return Err(format!( + "prototype guard input must be a regular file: {relative}" + )); + } return Ok(()); } let entries = fs::read_dir(path) @@ -2564,3 +2607,7 @@ description = "bounded pattern" let _ = fs::remove_dir_all(root); } } + +#[cfg(all(test, unix))] +#[path = "hygiene/prototype_input_tests.rs"] +mod prototype_input_tests; diff --git a/tools/xtask/src/hygiene/prototype_input_tests.rs b/tools/xtask/src/hygiene/prototype_input_tests.rs @@ -0,0 +1,303 @@ +use super::*; +use crate::bounded_process::{ProcessRequest, ReplacementEnvironment}; +use std::os::unix::fs::{FileTypeExt, symlink}; +use std::os::unix::net::UnixListener; +use std::time::Duration; +use tempfile::TempDir; + +const CHILD_ROOT: &str = "RADROOTS_HYGIENE_FIXTURE_ROOT"; +const FIFO_CASE: &str = + "hygiene::prototype_input_tests::git_inventory_fifo_is_rejected_without_blocking"; +const CONFIG: &str = r#"schema = "radroots.prototype-contract-source-guard.v1" +mode = "report_only" +[scan] +roots = ["src"] +path_roots = ["src"] +path_excludes = [] +extensions = ["rs"] +extensionless_names = [] +[limits] +max_scan_entries = 16 +max_inventory_bytes = 4096 +max_file_bytes = 1024 +max_matches = 16 +max_reported_findings = 4 +max_reported_allowlisted = 4 +[[pattern]] +id = "fixture-marker" +needle = "fixture-marker" +match_kind = "substring" +description = "Disposable scanner admission fixture" +"#; + +struct Fixture { + _directory: TempDir, + root: PathBuf, +} + +impl Fixture { + fn new(git_inventory: bool) -> Self { + let directory = TempDir::new().expect("disposable scanner root"); + let root = directory + .path() + .canonicalize() + .expect("physical fixture root"); + fs::create_dir(root.join("src")).expect("source directory"); + fs::create_dir(root.join("contracts")).expect("authority directory"); + assert!(CONFIG.len() <= 1024); + fs::write(root.join("contracts/guard.toml"), CONFIG).expect("fixture authority"); + fs::write(root.join("src/input.rs"), "fn current_contract() {}\n").expect("source"); + if git_inventory { + for args in [vec!["init", "-q"], vec!["add", "--", "src/input.rs"]] { + let mut request = ProcessRequest::new("/usr/bin/git") + .arg("-C") + .arg(root.as_os_str()) + .deadline(Duration::from_secs(5)) + .output_limits(1024, 1024); + for argument in args { + request = request.arg(argument); + } + let result = crate::bounded_process::run(&request).expect("bounded fixture Git"); + assert!(result.status().success(), "fixture Git: {result:?}"); + } + } + let fixture = Self { + _directory: directory, + root, + }; + fixture.assert_bounds(); + fixture + } + + fn path(&self) -> PathBuf { + self.root.join("src/input.rs") + } + + fn scan(&self, strict: bool) -> Result<(), String> { + scan_fixture(&self.root, strict) + } + + fn replace_with_fifo(&self) { + fs::remove_file(self.path()).expect("replace regular fixture"); + let request = ProcessRequest::new("/usr/bin/mkfifo") + .arg(self.path().as_os_str()) + .deadline(Duration::from_secs(5)) + .output_limits(1024, 1024); + let output = crate::bounded_process::run(&request).expect("bounded fixture FIFO creation"); + assert!(output.status().success()); + assert!( + fs::symlink_metadata(self.path()) + .expect("FIFO type") + .file_type() + .is_fifo() + ); + self.assert_bounds(); + } + + fn replace_with_socket(&self) -> UnixListener { + fs::remove_file(self.path()).expect("replace regular fixture"); + let short_path = self.root.join("s"); + let socket = UnixListener::bind(&short_path).expect("short owned fixture socket"); + fs::rename(short_path, self.path()).expect("move owned socket into source"); + assert!( + fs::symlink_metadata(self.path()) + .expect("socket type") + .file_type() + .is_socket() + ); + self.assert_bounds(); + socket + } + + fn assert_bounds(&self) { + let mut directories = 0; + let mut files = 0; + for entry in walkdir::WalkDir::new(&self.root).follow_links(false) { + let entry = entry.expect("fixture inventory"); + if entry.file_type().is_dir() { + directories += 1; + } else { + files += 1; + } + assert!(directories <= 32 && files <= 64, "fixture scaffold bounds"); + } + } +} + +fn scan_fixture(root: &Path, strict: bool) -> Result<(), String> { + let mut args = vec![ + "prototype-contracts".to_owned(), + "--config".to_owned(), + "contracts/guard.toml".to_owned(), + ]; + if strict { + args.push("--strict".to_owned()); + } + run(&args, root) +} + +fn assert_regular_admission_error(result: Result<(), String>) { + let error = result.expect_err("selected nonregular text input must not pass or be omitted"); + assert!( + error.contains("regular"), + "must reject object before reading: {error}" + ); +} + +#[test] +fn regular_report_and_strict_findings_are_preserved() { + for git_inventory in [false, true] { + let fixture = Fixture::new(git_inventory); + fs::write(fixture.path(), "const MARKER: &str = \"fixture-marker\";\n") + .expect("fixture source"); + fixture + .scan(false) + .expect("report-only mode retains finding"); + let strict = fixture.scan(true).expect_err("strict mode retains failure"); + assert!(strict.contains("1 non-allowlisted match(es)")); + assert_eq!( + fs::read_to_string(fixture.path()).expect("unchanged source"), + "const MARKER: &str = \"fixture-marker\";\n" + ); + fixture.assert_bounds(); + } +} + +#[test] +fn regular_byte_ceiling_and_utf8_are_preserved() { + let fixture = Fixture::new(false); + fs::write(fixture.path(), "x".repeat(1024)).expect("exact byte ceiling"); + assert_eq!( + read_bounded_prototype_input(&fixture.path(), "src/input.rs", 1024) + .expect("exact bounded bytes"), + "x".repeat(1024) + ); + fs::write(fixture.path(), "x".repeat(1025)).expect("one excess byte"); + assert!( + read_bounded_prototype_input(&fixture.path(), "src/input.rs", 1024) + .expect_err("reject excess byte") + .contains("exceeds 1024 bytes") + ); + fs::write(fixture.path(), [0xff]).expect("invalid UTF-8 fixture"); + assert!( + read_bounded_prototype_input(&fixture.path(), "src/input.rs", 1024) + .expect_err("reject invalid UTF-8") + .contains("not UTF-8") + ); +} + +#[test] +fn git_inventory_fifo_is_rejected_without_blocking() { + if std::env::args().any(|argument| argument == "--exact") + && let Some(root) = std::env::var_os(CHILD_ROOT) + { + let root = PathBuf::from(root); + assert!( + fs::symlink_metadata(root.join("src/input.rs")) + .expect("child FIFO type") + .file_type() + .is_fifo() + ); + assert_regular_admission_error(scan_fixture(&root, false)); + println!("owned_fifo_admission_probe_completed"); + return; + } + let fixture = Fixture::new(true); + fixture.replace_with_fifo(); + let mut environment = ReplacementEnvironment::default(); + environment + .insert(CHILD_ROOT, fixture.root.as_os_str()) + .expect("fixture-only child environment"); + let request = + ProcessRequest::new(std::env::current_exe().expect("compiled scanner test binary")) + .arg("--exact") + .arg(FIFO_CASE) + .arg("--nocapture") + .arg("--test-threads=1") + .environment(environment) + .deadline(Duration::from_secs(2)) + .output_limits(8192, 8192); + let output = crate::bounded_process::run(&request) + .expect("nonregular source must be rejected within the child bound"); + assert!( + output.status().success(), + "child failed: {}{}", + String::from_utf8_lossy(output.stdout()), + String::from_utf8_lossy(output.stderr()) + ); + assert!( + String::from_utf8_lossy(output.stdout()).contains("owned_fifo_admission_probe_completed") + ); + assert!( + fs::symlink_metadata(fixture.path()) + .expect("retained FIFO type") + .file_type() + .is_fifo() + ); + fixture.assert_bounds(); +} + +#[test] +fn fallback_fifo_is_rejected_instead_of_omitted() { + let fixture = Fixture::new(false); + fixture.replace_with_fifo(); + assert_regular_admission_error(fixture.scan(false)); + assert!( + fs::symlink_metadata(fixture.path()) + .expect("retained FIFO type") + .file_type() + .is_fifo() + ); +} + +#[test] +fn git_socket_is_rejected_before_text_read() { + let fixture = Fixture::new(true); + let _socket = fixture.replace_with_socket(); + assert_regular_admission_error(fixture.scan(false)); + assert!( + fs::symlink_metadata(fixture.path()) + .expect("retained socket type") + .file_type() + .is_socket() + ); +} + +#[test] +fn fallback_socket_is_rejected_instead_of_omitted() { + let fixture = Fixture::new(false); + let _socket = fixture.replace_with_socket(); + assert_regular_admission_error(fixture.scan(false)); + assert!( + fs::symlink_metadata(fixture.path()) + .expect("retained socket type") + .file_type() + .is_socket() + ); +} + +#[test] +fn linked_source_rejection_preserves_target_bytes() { + let fixture = Fixture::new(false); + let target = fixture.root.join("src/target.txt"); + fs::write(&target, b"unchanged target\n").expect("owned link target"); + fs::remove_file(fixture.path()).expect("replace fixture source"); + symlink(&target, fixture.path()).expect("fixture link"); + assert!( + fixture + .scan(false) + .expect_err("linked source remains rejected") + .contains("symlink") + ); + assert_eq!( + fs::read(&target).expect("retained target"), + b"unchanged target\n" + ); + assert!( + fs::symlink_metadata(fixture.path()) + .expect("retained link type") + .file_type() + .is_symlink() + ); + fixture.assert_bounds(); +}