From a221d6081b113fc30a5ea50732880f55c130593c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:32:46 -0800 Subject: [PATCH 1/8] craft-testkit: parse pinned-corpus manifests and check a corpus folder against them Add craft_testkit::corpus behind the corpus feature (native only, sha2). - Manifest::parse reads one tab-separated row per file: the SHA-256 as 64 hexadecimal digits in either case, a relative path with / between its parts, and optional license and URL columns. It skips blank lines and lines whose first character other than a space or tab is #, and reads LF and CRLF. A row with fewer than 2 or more than 4 columns, a bad digest, a path that is empty, absolute, has an empty, . or .. part or holds \, : or NUL, or a repeated path returns a ManifestError naming the line instead of panicking. - verify checks that each listed file resolves inside the folder after symbolic links are followed, is a regular file (checked before it is opened, so a directory or a named pipe is refused), is within the size limit, and has the listed SHA-256. An empty manifest is an error. - pinned(var, manifest) returns the folder the variable names (default CRAFT_CORPUS) after verify. With the variable unset it prints one "SKIPPED: corpus not given: set to its folder" line and returns None, or fails the test when _REQUIRED is exactly 1. A set but empty variable, a manifest that does not parse or a folder that does not match fails the test. - Limits: a manifest of at most 1 MiB and 10,000 rows, files of at most 8 GiB, hashed 64 KiB at a time. The parser follows the loader in crates/affinity/tests/support/corpus.rs, which has no tests of its own; that crate switches in its own pull request. The README gains the module's description and its Origin and Migration tables. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 5 + crates/testkit/README.md | 30 ++ crates/testkit/src/corpus.rs | 890 +++++++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 6 + 5 files changed, 934 insertions(+) create mode 100644 crates/testkit/src/corpus.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..edc19d31a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "sha2 0.10.9", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..33bf1c9d9d 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,7 +8,12 @@ repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" publish = false +[features] +# Pinned-corpus manifests and the `corpus::pinned` test gate (native only). +corpus = ["dep:sha2"] + [dependencies] +sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..ab948e4f2e 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,36 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## Pinned corpora: `corpus` + +`craft_testkit::corpus` is behind the `corpus` feature and is native only. It parses a corpus manifest and checks a folder of files against it. + +A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. + +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a NUL character, and a path listed twice. An empty optional column is `None`. +- `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. +- `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. +- `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. The corpus is required when the variable of the same name plus `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`) is exactly `1`. With the folder variable unset and the corpus optional, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`. With the folder variable unset and the corpus required, or set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. + +`Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `corpus` | storytold/craft-libs | `crates/affinity/tests/support/corpus.rs:18-35` | `75a654f4` | + +### Migration + +| Consumer | Today | State | +|---|---|---| +| craft-libs `affinity` | `tests/support/corpus.rs` reads `corpus.tsv` (already tab-separated) from `AFFINITY_CORPUS` | Pending: a separate pull request switches it | +| craft-libs `raw` | `docs/raf-corpus.sha256` separates digest and path with two spaces | Pending: the list is converted to tabs in a separate pull request | +| LightCraft | `crates/raw/tests/it/corpus.rs` checks the RAF list | Pending: a separate pull request switches it | +| PhotoCraft | `crates/io/tests/it/corpus.rs` and `xtask/*-corpus.sha256` (two-space lists) | Pending: the lists are converted to tabs in a separate pull request | +| CADCraft | `crates/io/src/roundtrip/tests.rs` scans `CADCRAFT_CORPUS_DIR` without a checksum list | Pending: needs a pinned list first | +| VectorCraft | `crates/affinity/tests/support/corpus.rs` reads a two-space list | Pending: the list is converted to tabs in a separate pull request | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs new file mode 100644 index 0000000000..fb0a4e4d91 --- /dev/null +++ b/crates/testkit/src/corpus.rs @@ -0,0 +1,890 @@ +//! Pinned test corpora: a folder of files listed in a manifest, each checked against its SHA-256. +//! +//! A manifest has one tab-separated row per file: the SHA-256 as 64 hexadecimal digits, the +//! file's path relative to the corpus folder, and optional license and URL columns. In this +//! example each `\t` stands for one tab character: +//! +//! ```text +//! # Public Affinity documents +//! cc8ca0db0d8fc545eb29153be900f153fa6b7b7eac068d05e54a502aba1264fe\tafdesignload-color.afdesign\tMIT\thttps://example.org/color.afdesign +//! 9a17f500d09fb3b1a70d24aabdc2882955ec3eac3700a474549e6100be3a8484\tmore/layer_mode.afdesign +//! ``` +//! +//! [`Manifest::parse`] skips blank lines and lines whose first character other than a space or a +//! tab is `#`. A `#` later in a row is part of that row. It returns a [`ManifestError`] naming the +//! line of a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal +//! digits, a path that is empty, absolute or leaves the folder, or a path listed twice. Paths use +//! `/` between their parts. +//! +//! [`pinned`] is the gate a test calls: it returns the corpus folder named by a variable after +//! checking every listed file, prints one `SKIPPED:` line and returns `None` when the variable is +//! unset and the corpus is optional, and fails the test otherwise. [`verify`] runs the same check +//! and returns a [`VerifyError`] instead of failing. No function here downloads a file or changes +//! the process environment. +//! +//! Every input has a size limit, set by [`Limits`]: a manifest of at most 1 MiB and 10,000 rows, +//! and files of at most 8 GiB each, read 64 KiB at a time. + +use std::collections::HashSet; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +/// The variable [`pinned`] reads when the caller names none. +pub const DEFAULT_VAR: &str = "CRAFT_CORPUS"; + +/// The suffix [`pinned`] adds to the folder variable's name to form the name of the variable that +/// makes the corpus required. +pub const REQUIRED_SUFFIX: &str = "_REQUIRED"; + +/// The size of each read while a file is hashed. +const CHUNK: usize = 64 * 1024; + +/// Size limits for a manifest and for the files it lists. An input over a limit is an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest manifest in bytes. Default 1 MiB. + pub max_manifest_bytes: usize, + /// The most rows a manifest may list. Default 10,000. + pub max_entries: usize, + /// The largest listed file in bytes. Default 8 GiB. + pub max_file_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: 1024 * 1024, max_entries: 10_000, max_file_bytes: 8 * 1024 * 1024 * 1024 } + } +} + +/// One row of a manifest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + digest: [u8; 32], + path: String, + license: Option, + url: Option, + line: usize, +} + +impl Entry { + /// The file's SHA-256. + pub fn digest(&self) -> &[u8; 32] { + &self.digest + } + + /// The file's path relative to the corpus folder, with `/` between its parts. + pub fn path(&self) -> &str { + &self.path + } + + /// The license column, when the row has one that is not empty. + pub fn license(&self) -> Option<&str> { + self.license.as_deref() + } + + /// The URL column, when the row has one that is not empty. + pub fn url(&self) -> Option<&str> { + self.url.as_deref() + } + + /// The 1-based line of the manifest that holds the row. + pub fn line(&self) -> usize { + self.line + } + + /// The file's path under `dir`. + fn path_in(&self, dir: &Path) -> PathBuf { + let mut path = dir.to_path_buf(); + path.extend(self.path.split('/')); + path + } +} + +/// A parsed manifest: the rows in the order the manifest lists them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Manifest { + entries: Vec, +} + +impl Manifest { + /// Parses `text` under the default [`Limits`]. + pub fn parse(text: &str) -> Result { + Self::parse_with_limits(text, &Limits::default()) + } + + /// Parses `text`. A manifest longer than `limits.max_manifest_bytes` or with more than + /// `limits.max_entries` rows is an error. + pub fn parse_with_limits(text: &str, limits: &Limits) -> Result { + if text.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let mut entries: Vec = Vec::new(); + let mut seen: HashSet<&str> = HashSet::new(); + for (index, raw) in text.lines().enumerate() { + let line = index + 1; + let content = raw.trim_start_matches([' ', '\t']); + if content.trim().is_empty() || content.starts_with('#') { + continue; + } + if entries.len() == limits.max_entries { + return Err(ManifestError::TooManyEntries { limit: limits.max_entries }); + } + let columns: Vec<&str> = raw.split('\t').collect(); + if !(2..=4).contains(&columns.len()) { + return Err(ManifestError::Columns { line, found: columns.len() }); + } + let digest = parse_digest(columns[0]).ok_or(ManifestError::Digest { line })?; + let path = columns[1]; + check_path(path).map_err(|reason| ManifestError::Path { line, reason })?; + if !seen.insert(path) { + let first = entries.iter().find(|e| e.path == path).map_or(0, |e| e.line); + return Err(ManifestError::Duplicate { line, first }); + } + let optional = |i: usize| columns.get(i).filter(|c| !c.is_empty()).map(|c| (*c).to_owned()); + entries.push(Entry { digest, path: path.to_owned(), license: optional(2), url: optional(3), line }); + } + Ok(Self { entries }) + } + + /// Reads and parses the manifest file at `path`. A path that is not a regular file is refused + /// before it is opened. Reading stops after `limits.max_manifest_bytes` bytes plus one, so an + /// oversized file is not read whole. + pub fn read(path: &Path, limits: &Limits) -> Result { + if !std::fs::metadata(path).map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let file = File::open(path).map_err(ManifestError::Io)?; + if !file.metadata().map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let cap = u64::try_from(limits.max_manifest_bytes).unwrap_or(u64::MAX).saturating_add(1); + let mut bytes = Vec::new(); + file.take(cap).read_to_end(&mut bytes).map_err(ManifestError::Io)?; + if bytes.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let text = String::from_utf8(bytes).map_err(|_| ManifestError::NotUtf8)?; + Self::parse_with_limits(&text, limits) + } + + /// The rows, in manifest order. + pub fn entries(&self) -> &[Entry] { + &self.entries + } + + /// The paths of the rows, in manifest order. + pub fn names(&self) -> impl Iterator { + self.entries.iter().map(Entry::path) + } +} + +/// Decodes 64 ASCII hexadecimal digits, in either case. +fn parse_digest(text: &str) -> Option<[u8; 32]> { + let bytes = text.as_bytes(); + if bytes.len() != 64 { + return None; + } + let mut digest = [0u8; 32]; + let (pairs, _) = bytes.as_chunks::<2>(); + for (out, &[high, low]) in digest.iter_mut().zip(pairs) { + let high = char::from(high).to_digit(16)?; + let low = char::from(low).to_digit(16)?; + *out = u8::try_from(high * 16 + low).ok()?; + } + Some(digest) +} + +/// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none +/// empty, `.` or `..`, and no `\`, `:` or NUL anywhere, so the same row means the same file on +/// every platform. +fn check_path(path: &str) -> Result<(), PathError> { + if path.is_empty() { + return Err(PathError::Empty); + } + if path.contains(['\\', ':', '\0']) { + return Err(PathError::Character); + } + for part in path.split('/') { + match part { + "" => return Err(if path.starts_with('/') { PathError::Absolute } else { PathError::EmptyPart }), + "." | ".." => return Err(PathError::DotPart), + _ => {} + } + } + Ok(()) +} + +/// Why a manifest path was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathError { + /// The path is empty. + Empty, + /// The path starts with `/`. + Absolute, + /// The path has an empty part (`a//b`, or a trailing `/`). + EmptyPart, + /// The path has a `.` or `..` part. + DotPart, + /// The path holds a `\`, a `:` or a NUL character. + Character, +} + +impl fmt::Display for PathError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Empty => "the path is empty", + Self::Absolute => "the path is absolute", + Self::EmptyPart => "the path has an empty part", + Self::DotPart => "the path has a . or .. part", + Self::Character => "the path holds a \\, a : or a NUL character", + }) + } +} + +/// Why a manifest could not be read or parsed. +#[derive(Debug)] +pub enum ManifestError { + /// The manifest is longer than the limit in bytes. + TooLarge { + /// The limit in bytes. + limit: usize, + }, + /// The manifest lists more rows than the limit. + TooManyEntries { + /// The limit in rows. + limit: usize, + }, + /// A row does not have 2, 3 or 4 tab-separated columns. + Columns { + /// The 1-based line of the row. + line: usize, + /// The number of columns found. + found: usize, + }, + /// A row's digest is not 64 hexadecimal digits. + Digest { + /// The 1-based line of the row. + line: usize, + }, + /// A row's path is refused. + Path { + /// The 1-based line of the row. + line: usize, + /// Why the path is refused. + reason: PathError, + }, + /// A row repeats the path of an earlier row. + Duplicate { + /// The 1-based line of the repeated row. + line: usize, + /// The 1-based line of the earlier row. + first: usize, + }, + /// The manifest path does not name a regular file. + NotAFile, + /// The manifest file is not UTF-8. + NotUtf8, + /// The manifest file could not be read. + Io(io::Error), +} + +impl fmt::Display for ManifestError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooLarge { limit } => write!(f, "the manifest is longer than {limit} bytes"), + Self::TooManyEntries { limit } => write!(f, "the manifest lists more than {limit} files"), + Self::Columns { line, found } => write!(f, "line {line}: {found} tab-separated columns, expected 2 to 4"), + Self::Digest { line } => write!(f, "line {line}: the SHA-256 is not 64 hexadecimal digits"), + Self::Path { line, reason } => write!(f, "line {line}: {reason}"), + Self::Duplicate { line, first } => write!(f, "line {line}: the path is already listed on line {first}"), + Self::NotAFile => f.write_str("the manifest is not a regular file"), + Self::NotUtf8 => f.write_str("the manifest is not UTF-8"), + Self::Io(error) => write!(f, "the manifest could not be read: {error}"), + } + } +} + +impl std::error::Error for ManifestError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } + } +} + +/// Why a corpus folder does not match its manifest. +#[derive(Debug)] +pub enum VerifyError { + /// The manifest lists no files, so the folder would be accepted without a check. + EmptyManifest, + /// The corpus folder could not be resolved. + Folder { + /// The folder. + dir: PathBuf, + /// The error resolving it. + error: io::Error, + }, + /// A listed file is missing or could not be resolved. + Missing { + /// The path the manifest lists. + path: String, + /// The error resolving it. + error: io::Error, + }, + /// A listed path resolves outside the corpus folder, through a symbolic link. + Escapes { + /// The path the manifest lists. + path: String, + }, + /// A listed path is not a regular file. + NotAFile { + /// The path the manifest lists. + path: String, + }, + /// A listed file is larger than the limit. + TooLarge { + /// The path the manifest lists. + path: String, + /// The limit in bytes. + limit: u64, + }, + /// A listed file could not be read. + Read { + /// The path the manifest lists. + path: String, + /// The read error. + error: io::Error, + }, + /// A listed file's SHA-256 differs from the manifest's. + Modified { + /// The path the manifest lists. + path: String, + }, +} + +impl fmt::Display for VerifyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyManifest => f.write_str("the manifest lists no files"), + Self::Folder { dir, error } => write!(f, "corpus folder {}: {error}", dir.display()), + Self::Missing { path, error } => write!(f, "{path}: missing: {error}"), + Self::Escapes { path } => write!(f, "{path}: resolves outside the corpus folder"), + Self::NotAFile { path } => write!(f, "{path}: not a regular file"), + Self::TooLarge { path, limit } => write!(f, "{path}: larger than {limit} bytes"), + Self::Read { path, error } => write!(f, "{path}: {error}"), + Self::Modified { path } => write!(f, "{path}: SHA-256 differs from the manifest"), + } + } +} + +impl std::error::Error for VerifyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Folder { error, .. } | Self::Missing { error, .. } | Self::Read { error, .. } => Some(error), + _ => None, + } + } +} + +/// Checks every file `manifest` lists in `dir` under the default [`Limits`]. +pub fn verify(dir: &Path, manifest: &Manifest) -> Result<(), VerifyError> { + verify_with_limits(dir, manifest, &Limits::default()) +} + +/// Checks every file `manifest` lists in `dir`: each must resolve inside `dir` after symbolic +/// links are followed, be a regular file of at most `limits.max_file_bytes` bytes, and have the +/// listed SHA-256. Returns the first failure in manifest order. An empty manifest is an error. +pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> Result<(), VerifyError> { + if manifest.entries.is_empty() { + return Err(VerifyError::EmptyManifest); + } + let root = dir.canonicalize().map_err(|error| VerifyError::Folder { dir: dir.to_path_buf(), error })?; + let mut buf = vec![0u8; CHUNK]; + for entry in &manifest.entries { + verify_entry(&root, entry, limits, &mut buf)?; + } + Ok(()) +} + +fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Result<(), VerifyError> { + let path = || entry.path.clone(); + let target = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + if !target.starts_with(root) { + return Err(VerifyError::Escapes { path: path() }); + } + let kind = std::fs::metadata(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + if !kind.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + let file = File::open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; + if !meta.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + if meta.len() > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + let mut reader = file.take(limits.max_file_bytes.saturating_add(1)); + let mut hasher = Sha256::new(); + let mut total: u64 = 0; + loop { + let n = match reader.read(buf) { + Ok(0) => break, + Ok(n) => n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(VerifyError::Read { path: path(), error }), + }; + total = total.saturating_add(n as u64); + if total > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + hasher.update(&buf[..n]); + } + if hasher.finalize().as_slice() != entry.digest.as_slice() { + return Err(VerifyError::Modified { path: path() }); + } + Ok(()) +} + +/// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file +/// `manifest` lists has been checked with [`verify`]. +/// +/// The corpus is required when the variable named `var` plus [`REQUIRED_SUFFIX`] (by default +/// `CRAFT_CORPUS_REQUIRED`) is exactly `1`; unset, empty, `0`, `true` and any other value leave it +/// optional. +/// +/// - Folder variable unset and the corpus optional: prints one line, +/// `SKIPPED: corpus not given: set to its folder`, to stderr and returns `None`. +/// - Folder variable unset and the corpus required: fails the test. +/// - Folder variable set, even to an empty value: fails the test unless the manifest parses and +/// every listed file matches. +/// +/// It fails the test with a panic whose message names the variable and the failure. +#[allow(clippy::panic)] +pub fn pinned(var: Option<&str>, manifest: &str) -> Option { + let var = var.unwrap_or(DEFAULT_VAR); + let required_var = format!("{var}{REQUIRED_SUFFIX}"); + let required = std::env::var_os(&required_var).as_deref() == Some(OsStr::new("1")); + match gate(std::env::var_os(var), required, var, &required_var, manifest) { + Ok(Some(dir)) => Some(dir), + Ok(None) => { + eprintln!("SKIPPED: corpus not given: set {var} to its folder"); + None + } + Err(message) => panic!("{message}"), + } +} + +/// The decision of [`pinned`], without reading the environment or printing: `Ok(None)` skips and +/// `Err` holds the message the test fails with. +fn gate(folder: Option, required: bool, var: &str, required_var: &str, manifest: &str) -> Result, String> { + let Some(folder) = folder else { + return if required { Err(format!("corpus not given: {var} is unset and {required_var}=1 forbids skipping")) } else { Ok(None) }; + }; + if folder.is_empty() { + return Err(format!("{var} is set but empty")); + } + let dir = PathBuf::from(folder); + let manifest = Manifest::parse(manifest).map_err(|e| format!("corpus manifest for {var}: {e}"))?; + verify(&dir, &manifest).map_err(|e| format!("pinned corpus in {} ({var}): {e}", dir.display()))?; + Ok(Some(dir)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Output}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_CORPUS_CHILD"; + /// The folder variable the child's `pinned` reads. + const VAR: &str = "CRAFT_TESTKIT_CORPUS_DIR"; + /// The required variable that goes with [`VAR`]. + const REQUIRED: &str = "CRAFT_TESTKIT_CORPUS_DIR_REQUIRED"; + + const HELLO: &[u8] = b"hello world"; + /// SHA-256 of `hello world`. + const HELLO_SHA: &str = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; + const EMPTY_SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + /// A folder under the system temporary folder, removed on drop. + struct Scratch(PathBuf); + + impl Scratch { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("craft_testkit_corpus_{}_{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch folder"); + Self(dir) + } + + fn write(&self, rel: &str, bytes: &[u8]) -> PathBuf { + let path = self.0.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(&path, bytes).expect("write file"); + path + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn parse_err(text: &str) -> ManifestError { + Manifest::parse(text).expect_err("the manifest is refused") + } + + #[test] + fn comments_are_skipped() { + let text = format!("# pinned corpus\n # indented comment\n\t# tab-indented comment\n{HELLO_SHA}\thello.txt\n#{EMPTY_SHA}\tempty.txt\n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.names().collect::>(), ["hello.txt"]); + assert_eq!(manifest.entries()[0].line(), 4); + } + + #[test] + fn a_hash_inside_a_row_is_not_a_comment() { + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tdir/#1.txt\tMIT\thttps://example.org/a#b\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.path(), "dir/#1.txt"); + assert_eq!(entry.url(), Some("https://example.org/a#b")); + } + + #[test] + fn blank_lines_are_skipped() { + let text = format!("\n \n\t\n{HELLO_SHA}\thello.txt\n\n{EMPTY_SHA}\tempty.txt\n \t \n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.entries().len(), 2); + assert_eq!(manifest.entries()[0].line(), 4); + assert_eq!(manifest.entries()[1].line(), 6); + assert_eq!(Manifest::parse("").expect("parse").entries().len(), 0); + } + + #[test] + fn malformed_row_is_error() { + assert!(matches!(parse_err(HELLO_SHA), ManifestError::Columns { line: 1, found: 1 })); + assert!(matches!(parse_err(&format!("# c\n{HELLO_SHA} hello.txt\n")), ManifestError::Columns { line: 2, found: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\ta\tMIT\turl\textra\n")), ManifestError::Columns { line: 1, found: 5 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\t\n")), ManifestError::Path { line: 1, reason: PathError::Empty })); + assert!(matches!(parse_err("\thello.txt\n"), ManifestError::Digest { line: 1 })); + } + + #[test] + fn wrong_digest_length_is_error() { + assert!(matches!(parse_err(&format!("{}\ta\n", &HELLO_SHA[..63])), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}0\ta\n")), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!(" {HELLO_SHA}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn non_hex_digest_is_error() { + let bad = format!("{}g", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{bad}\ta\n")), ManifestError::Digest { line: 1 })); + let sign = format!("+{}", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{sign}\ta\n")), ManifestError::Digest { line: 1 })); + let wide = format!("{}é", &HELLO_SHA[..62]); + assert!(matches!(parse_err(&format!("{wide}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn rows_take_two_to_four_columns_and_empty_optional_columns_are_none() { + let text = format!( + "{HELLO_SHA}\ta.txt\n{HELLO_SHA}\tb.txt\tMIT\n{HELLO_SHA}\tc.txt\tMIT\thttps://example.org/c\n{HELLO_SHA}\td.txt\t\n{HELLO_SHA}\te.txt\t\thttps://example.org/e\n" + ); + let manifest = Manifest::parse(&text).expect("parse"); + let cols: Vec<_> = manifest.entries().iter().map(|e| (e.path(), e.license(), e.url())).collect(); + assert_eq!( + cols, + [ + ("a.txt", None, None), + ("b.txt", Some("MIT"), None), + ("c.txt", Some("MIT"), Some("https://example.org/c")), + ("d.txt", None, None), + ("e.txt", None, Some("https://example.org/e")), + ] + ); + } + + #[test] + fn crlf_lines_and_uppercase_digests_parse() { + let upper = HELLO_SHA.to_ascii_uppercase(); + let manifest = Manifest::parse(&format!("# c\r\n{upper}\thello.txt\tMIT\r\n\r\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.license(), Some("MIT")); + assert_eq!(entry.digest()[..4], [0xb9, 0x4d, 0x27, 0xb9]); + assert_eq!(entry.digest(), Manifest::parse(&format!("{HELLO_SHA}\thello.txt")).expect("parse").entries()[0].digest()); + } + + #[test] + fn duplicate_path_is_error() { + let text = format!("{HELLO_SHA}\ta/b.txt\n# c\n{HELLO_SHA}\ta/b.txt\n"); + assert!(matches!(parse_err(&text), ManifestError::Duplicate { line: 3, first: 1 })); + } + + #[test] + fn paths_that_leave_the_folder_are_errors() { + let cases = [ + ("/etc/passwd", PathError::Absolute), + ("../outside", PathError::DotPart), + ("a/../../outside", PathError::DotPart), + ("./a", PathError::DotPart), + ("a//b", PathError::EmptyPart), + ("a/", PathError::EmptyPart), + ("C:/Windows/win.ini", PathError::Character), + ("C:a", PathError::Character), + ("\\\\server\\share\\a", PathError::Character), + ("a\\..\\..\\b", PathError::Character), + ]; + for (path, expected) in cases { + match parse_err(&format!("{HELLO_SHA}\t{path}\n")) { + ManifestError::Path { line: 1, reason } => assert_eq!(reason, expected, "{path}"), + other => panic!("{path}: {other}"), + } + } + } + + #[test] + fn manifest_limits_are_errors() { + let text = format!("{HELLO_SHA}\ta\n{HELLO_SHA}\tb\n"); + let limits = Limits { max_entries: 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooManyEntries { limit: 1 }))); + let limits = Limits { max_entries: 2, ..Limits::default() }; + assert_eq!(Manifest::parse_with_limits(&text, &limits).expect("parse").entries().len(), 2); + + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooLarge { .. }))); + let limits = Limits { max_manifest_bytes: text.len(), ..Limits::default() }; + assert!(Manifest::parse_with_limits(&text, &limits).is_ok()); + + let scratch = Scratch::new(); + let path = scratch.write("corpus.tsv", text.as_bytes()); + assert_eq!(Manifest::read(&path, &Limits::default()).expect("read").entries().len(), 2); + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::read(&path, &limits), Err(ManifestError::TooLarge { .. }))); + let bad = scratch.write("bad.tsv", b"\xff\xfe"); + assert!(matches!(Manifest::read(&bad, &Limits::default()), Err(ManifestError::NotUtf8))); + assert!(matches!(Manifest::read(&scratch.0.join("absent.tsv"), &Limits::default()), Err(ManifestError::Io(_)))); + } + + fn hello_corpus() -> (Scratch, Manifest) { + let scratch = Scratch::new(); + scratch.write("hello.txt", HELLO); + scratch.write("sub/empty.bin", b""); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\tMIT\n{EMPTY_SHA}\tsub/empty.bin\n")).expect("parse"); + (scratch, manifest) + } + + #[test] + fn a_matching_folder_verifies() { + let (scratch, manifest) = hello_corpus(); + verify(&scratch.0, &manifest).expect("the corpus matches"); + } + + #[test] + fn missing_file_fails() { + let (scratch, manifest) = hello_corpus(); + std::fs::remove_file(scratch.0.join("sub").join("empty.bin")).expect("remove"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Missing { path, .. }) => assert_eq!(path, "sub/empty.bin"), + other => panic!("{other:?}"), + } + assert!(matches!(verify(&scratch.0.join("absent"), &manifest), Err(VerifyError::Folder { .. }))); + } + + #[test] + fn modified_file_fails() { + let (scratch, manifest) = hello_corpus(); + scratch.write("hello.txt", b"hello world!"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Modified { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + + #[test] + fn an_empty_manifest_or_a_folder_entry_fails() { + let (scratch, _) = hello_corpus(); + assert!(matches!(verify(&scratch.0, &Manifest::default()), Err(VerifyError::EmptyManifest))); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tsub\n")).expect("parse"); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::NotAFile { .. }))); + } + + /// A named pipe is refused before it is opened; opening one for reading waits for a writer. + #[cfg(unix)] + #[test] + fn a_named_pipe_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("pipe"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tpipe\n")).expect("parse"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::NotAFile { path }) => assert_eq!(path, "pipe"), + other => panic!("{other:?}"), + } + } + + /// A manifest path that names a named pipe or a folder is refused before it is opened. + #[cfg(unix)] + #[test] + fn a_manifest_that_is_not_a_file_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("corpus.tsv"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + assert!(matches!(Manifest::read(&scratch.0, &Limits::default()), Err(ManifestError::NotAFile))); + assert!(matches!(Manifest::read(&fifo, &Limits::default()), Err(ManifestError::NotAFile))); + } + + #[test] + fn file_size_limit_is_error() { + let (scratch, manifest) = hello_corpus(); + let limits = Limits { max_file_bytes: HELLO.len() as u64, ..Limits::default() }; + verify_with_limits(&scratch.0, &manifest, &limits).expect("a file at the limit passes"); + let limits = Limits { max_file_bytes: HELLO.len() as u64 - 1, ..Limits::default() }; + match verify_with_limits(&scratch.0, &manifest, &limits) { + Err(VerifyError::TooLarge { path, limit }) => assert_eq!((path.as_str(), limit), ("hello.txt", 10)), + other => panic!("{other:?}"), + } + } + + #[test] + fn a_file_larger_than_one_read_hashes_whole() { + let scratch = Scratch::new(); + let bytes: Vec = (0..CHUNK * 2 + 7).map(|i| (i % 251) as u8).collect(); + scratch.write("big.bin", &bytes); + let hex: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); + let manifest = Manifest::parse(&format!("{hex}\tbig.bin\n")).expect("parse"); + verify(&scratch.0, &manifest).expect("the whole file is hashed"); + scratch.write("big.bin", &bytes[..CHUNK]); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::Modified { .. }))); + } + + #[cfg(unix)] + #[test] + fn a_symbolic_link_out_of_the_folder_fails() { + let outside = Scratch::new(); + let target = outside.write("hello.txt", HELLO); + let corpus = Scratch::new(); + std::os::unix::fs::symlink(&target, corpus.0.join("hello.txt")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\n")).expect("parse"); + match verify(&corpus.0, &manifest) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + std::os::unix::fs::symlink(&outside.0, corpus.0.join("out")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tout/hello.txt\n")).expect("parse"); + assert!(matches!(verify(&corpus.0, &manifest), Err(VerifyError::Escapes { .. }))); + } + + #[test] + fn the_gate_skips_only_an_optional_unset_corpus() { + let (scratch, _) = hello_corpus(); + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + assert_eq!(gate(None, false, VAR, REQUIRED, &manifest), Ok(None)); + let required = gate(None, true, VAR, REQUIRED, &manifest).expect_err("required"); + assert!(required.contains(&format!("{REQUIRED}=1")), "{required}"); + let dir = scratch.0.clone().into_os_string(); + assert_eq!(gate(Some(dir.clone()), false, VAR, REQUIRED, &manifest), Ok(Some(scratch.0.clone()))); + let empty = gate(Some(OsString::new()), false, VAR, REQUIRED, &manifest).expect_err("empty"); + assert!(empty.contains("empty"), "{empty}"); + let bad = gate(Some(dir.clone()), false, VAR, REQUIRED, "# c\nnot a row\n").expect_err("bad manifest"); + assert!(bad.contains("line 2"), "{bad}"); + let missing = gate(Some(dir), false, VAR, REQUIRED, &format!("{EMPTY_SHA}\tabsent.bin\n")).expect_err("missing"); + assert!(missing.contains("absent.bin"), "{missing}"); + } + + /// Runs `child` below in a new process of this test binary with the given variables set and + /// every other corpus variable removed, so no test changes this process's environment. + fn run_child(case: &str, vars: &[(&str, &str)]) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["corpus::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + for name in [VAR, REQUIRED, DEFAULT_VAR, "CRAFT_CORPUS_REQUIRED"] { + cmd.env_remove(name); + } + for (name, value) in vars { + cmd.env(name, value); + } + cmd.output().expect("run the test binary") + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + let found = match case.to_str() { + Some("named") => pinned(Some(VAR), &manifest), + Some("default") => pinned(None, &manifest), + other => panic!("unknown child case {other:?}"), + }; + eprintln!("pinned returned {}", found.map_or_else(|| "none".to_owned(), |d| d.display().to_string())); + } + + #[test] + fn required_variable_unset_fails() { + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1"), Some("1\n")] { + let vars: Vec<(&str, &str)> = value.map(|v| (REQUIRED, v)).into_iter().collect(); + let out = run_child("named", &vars); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches(&format!("SKIPPED: corpus not given: set {VAR} to its folder\n")).count(), 1, "{value:?}: {err}"); + assert!(err.contains("pinned returned none"), "{value:?}: {err}"); + } + let out = run_child("named", &[(REQUIRED, "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{REQUIRED}=1 forbids skipping")), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("pinned returned"), "{err}"); + } + + #[test] + fn pinned_reads_the_named_folder_and_fails_on_a_bad_one() { + let (scratch, _) = hello_corpus(); + let dir = scratch.0.to_str().expect("a UTF-8 temporary path"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains(&format!("pinned returned {dir}")), "{err}"); + + scratch.write("hello.txt", b"changed"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("hello.txt: SHA-256 differs from the manifest"), "{err}"); + + let out = run_child("named", &[(VAR, "")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{VAR} is set but empty")), "{err}"); + } + + #[test] + fn pinned_defaults_to_craft_corpus() { + let out = run_child("default", &[]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: corpus not given: set CRAFT_CORPUS to its folder\n"), "{err}"); + + let out = run_child("default", &[("CRAFT_CORPUS_REQUIRED", "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_CORPUS_REQUIRED=1 forbids skipping"), "{err}"); + } +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..bb41162311 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! With the `corpus` feature, `corpus` (native only) parses pinned-corpus manifests and checks a +//! corpus folder against them: `corpus::Manifest`, `corpus::verify` and the test gate +//! `corpus::pinned`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -25,6 +29,8 @@ //! under foreign host environments. They are lightweight syntactic regression gates designed to complement, //! rather than replace, platform integration tests and CI execution. +#[cfg(all(feature = "corpus", not(target_arch = "wasm32")))] +pub mod corpus; pub mod guards; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; From c0845ba8d32436d6eed4ae8d41ac43ae56397214 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:38:39 -0800 Subject: [PATCH 2/8] craft-testkit: open corpus files without waiting on a named pipe Manifest::read and verify checked a path's type and then opened it. A path replaced by a named pipe between the two blocked the open until a writer appeared. On Unix both now open with O_NONBLOCK and check the opened file's type again. --- Cargo.lock | 1 + crates/testkit/Cargo.toml | 5 ++++- crates/testkit/README.md | 1 + crates/testkit/src/corpus.rs | 33 +++++++++++++++++++++++++++++++-- 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 22e6ee881e..2b49aeac33 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3124,6 +3124,7 @@ dependencies = [ name = "craft-testkit" version = "0.1.0" dependencies = [ + "libc", "sha2 0.10.9", ] diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 33bf1c9d9d..275e178e29 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -10,10 +10,13 @@ publish = false [features] # Pinned-corpus manifests and the `corpus::pinned` test gate (native only). -corpus = ["dep:sha2"] +corpus = ["dep:sha2", "dep:libc"] [dependencies] sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } +[target.'cfg(unix)'.dependencies] +libc = { version = "0.2", optional = true } + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 107ed212d4..5aa907a7c0 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -215,6 +215,7 @@ A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 h - `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a NUL character, and a path listed twice. An empty optional column is `None`. - `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. - `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. +- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. - `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. The corpus is required when the variable of the same name plus `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`) is exactly `1`. With the folder variable unset and the corpus optional, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`. With the folder variable unset and the corpus required, or set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. `Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs index fb0a4e4d91..85929938a2 100644 --- a/crates/testkit/src/corpus.rs +++ b/crates/testkit/src/corpus.rs @@ -158,7 +158,7 @@ impl Manifest { if !std::fs::metadata(path).map_err(ManifestError::Io)?.is_file() { return Err(ManifestError::NotAFile); } - let file = File::open(path).map_err(ManifestError::Io)?; + let file = open_for_reading(path).map_err(ManifestError::Io)?; if !file.metadata().map_err(ManifestError::Io)?.is_file() { return Err(ManifestError::NotAFile); } @@ -422,7 +422,7 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> if !kind.is_file() { return Err(VerifyError::NotAFile { path: path() }); } - let file = File::open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let file = open_for_reading(&target).map_err(|error| VerifyError::Read { path: path(), error })?; let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; if !meta.is_file() { return Err(VerifyError::NotAFile { path: path() }); @@ -452,6 +452,20 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Ok(()) } +/// Opens `path` for reading. On Unix the file is opened with `O_NONBLOCK`, so a path that was +/// replaced by a named pipe after its type was checked opens at once instead of waiting for a +/// writer; the caller checks the opened file's type. Reads from a regular file are not affected. +fn open_for_reading(path: &Path) -> io::Result { + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.custom_flags(libc::O_NONBLOCK); + } + options.open(path) +} + /// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file /// `manifest` lists has been checked with [`verify`]. /// @@ -749,6 +763,21 @@ mod tests { assert!(matches!(Manifest::read(&fifo, &Limits::default()), Err(ManifestError::NotAFile))); } + /// Files are opened with `O_NONBLOCK`, read back from the open file's status flags in + /// `/proc/self/fdinfo`, so a path replaced by a named pipe after its type was checked opens at + /// once instead of waiting for a writer. + #[cfg(target_os = "linux")] + #[test] + fn files_are_opened_with_o_nonblock() { + use std::os::fd::AsRawFd; + let (scratch, _) = hello_corpus(); + let file = open_for_reading(&scratch.0.join("hello.txt")).expect("open"); + let info = std::fs::read_to_string(format!("/proc/self/fdinfo/{}", file.as_raw_fd())).expect("read fdinfo"); + let flags = info.lines().find_map(|line| line.strip_prefix("flags:")).map(str::trim).expect("flags line"); + let flags = i32::from_str_radix(flags, 8).expect("octal flags"); + assert_ne!(flags & libc::O_NONBLOCK, 0, "flags {flags:o}"); + } + #[test] fn file_size_limit_is_error() { let (scratch, manifest) = hello_corpus(); From aea1ee6860149b23f1b3adb81d7d8e04c6a88921 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 21:50:31 -0800 Subject: [PATCH 3/8] craft-testkit: refuse corpus files opened outside the folder and control characters in paths On Unix, verify checks after the open that the opened file is inside the corpus folder: by the path the kernel reports for the open file on Linux, Android and Apple platforms, otherwise by resolving the path again and comparing device and inode. Manifest paths that hold a control character are refused. --- Cargo.lock | 1 + crates/testkit/Cargo.toml | 5 +- crates/testkit/README.md | 4 +- crates/testkit/src/corpus.rs | 113 +++++++++++++++++++++++++++++++++-- 4 files changed, 114 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2b49aeac33..a6e198f5ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3125,6 +3125,7 @@ name = "craft-testkit" version = "0.1.0" dependencies = [ "libc", + "rustix 1.1.5", "sha2 0.10.9", ] diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index 275e178e29..32085ff235 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -10,7 +10,7 @@ publish = false [features] # Pinned-corpus manifests and the `corpus::pinned` test gate (native only). -corpus = ["dep:sha2", "dep:libc"] +corpus = ["dep:sha2", "dep:libc", "dep:rustix"] [dependencies] sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } @@ -18,5 +18,8 @@ sha2 = { version = "0.10", default-features = false, features = ["std"], optiona [target.'cfg(unix)'.dependencies] libc = { version = "0.2", optional = true } +[target.'cfg(target_vendor = "apple")'.dependencies] +rustix = { version = "1.1", default-features = false, features = ["std", "fs"], optional = true } + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 5aa907a7c0..aa72b1daec 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -212,10 +212,10 @@ Changes from `craft-media-testkit`'s `hammer`: A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. -- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a NUL character, and a path listed twice. An empty optional column is `None`. +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a control character (NUL included), and a path listed twice. An empty optional column is `None`. - `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. - `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. -- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. +- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. After the open, `verify` also checks that the opened file is inside `dir`: on Linux, Android and Apple platforms by the path the kernel reports for the open file, and on other Unix systems, or when that path cannot be read, by resolving the listed path again and comparing its device and inode with the opened file's. That second lookup goes through the path again, so a folder changed during it is not detected. On Windows the location of the opened file is not checked again. - `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. The corpus is required when the variable of the same name plus `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`) is exactly `1`. With the folder variable unset and the corpus optional, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`. With the folder variable unset and the corpus required, or set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. `Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs index 85929938a2..f40c6dc4f7 100644 --- a/crates/testkit/src/corpus.rs +++ b/crates/testkit/src/corpus.rs @@ -200,13 +200,13 @@ fn parse_digest(text: &str) -> Option<[u8; 32]> { } /// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none -/// empty, `.` or `..`, and no `\`, `:` or NUL anywhere, so the same row means the same file on -/// every platform. +/// empty, `.` or `..`, and no `\`, `:` or control character (NUL included) anywhere, so the same +/// row means the same file on every platform. fn check_path(path: &str) -> Result<(), PathError> { if path.is_empty() { return Err(PathError::Empty); } - if path.contains(['\\', ':', '\0']) { + if path.contains(['\\', ':']) || path.chars().any(char::is_control) { return Err(PathError::Character); } for part in path.split('/') { @@ -230,7 +230,7 @@ pub enum PathError { EmptyPart, /// The path has a `.` or `..` part. DotPart, - /// The path holds a `\`, a `:` or a NUL character. + /// The path holds a `\`, a `:` or a control character. Character, } @@ -241,7 +241,7 @@ impl fmt::Display for PathError { Self::Absolute => "the path is absolute", Self::EmptyPart => "the path has an empty part", Self::DotPart => "the path has a . or .. part", - Self::Character => "the path holds a \\, a : or a NUL character", + Self::Character => "the path holds a \\, a : or a control character", }) } } @@ -413,6 +413,17 @@ pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> R } fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Result<(), VerifyError> { + verify_entry_with(root, entry, limits, buf, open_for_reading) +} + +/// [`verify_entry`] with the function that opens the resolved path; tests change the path in it. +fn verify_entry_with( + root: &Path, + entry: &Entry, + limits: &Limits, + buf: &mut [u8], + open: impl FnOnce(&Path) -> io::Result, +) -> Result<(), VerifyError> { let path = || entry.path.clone(); let target = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; if !target.starts_with(root) { @@ -422,11 +433,13 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> if !kind.is_file() { return Err(VerifyError::NotAFile { path: path() }); } - let file = open_for_reading(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let file = open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; if !meta.is_file() { return Err(VerifyError::NotAFile { path: path() }); } + #[cfg(unix)] + opened_file_is_inside(root, entry, &file, &meta)?; if meta.len() > limits.max_file_bytes { return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); } @@ -452,6 +465,49 @@ fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Ok(()) } +/// Checks, after the open, that the opened file is inside `root`, so a path changed into a link out +/// of the folder between the first check and the open is refused. On Linux, Android and Apple +/// platforms the kernel reports the open file's path, which must start with `root`. On other Unix +/// systems, and where that path cannot be read, the entry's path is resolved again and must lead, without a link in its last part, to the +/// opened file (the same device and inode). +#[cfg(unix)] +fn opened_file_is_inside(root: &Path, entry: &Entry, file: &File, opened: &std::fs::Metadata) -> Result<(), VerifyError> { + use std::os::unix::fs::MetadataExt; + let path = || entry.path.clone(); + if let Some(actual) = opened_path(file).map_err(|error| VerifyError::Read { path: path(), error })? { + return if actual.starts_with(root) { Ok(()) } else { Err(VerifyError::Escapes { path: path() }) }; + } + let again = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + let now = std::fs::symlink_metadata(&again).map_err(|error| VerifyError::Read { path: path(), error })?; + if !again.starts_with(root) || (now.dev(), now.ino()) != (opened.dev(), opened.ino()) { + return Err(VerifyError::Escapes { path: path() }); + } + Ok(()) +} + +/// The path of the file `file` has open, as the kernel reports it in `/proc/self/fd`, or `None` +/// when that cannot be read (for example without a mounted `/proc`). +#[cfg(any(target_os = "linux", target_os = "android"))] +#[allow(clippy::unnecessary_wraps)] +fn opened_path(file: &File) -> io::Result> { + use std::os::fd::AsRawFd; + Ok(std::fs::read_link(format!("/proc/self/fd/{}", file.as_raw_fd())).ok()) +} + +/// The path of the file `file` has open, as the kernel reports it. +#[cfg(target_vendor = "apple")] +fn opened_path(file: &File) -> io::Result> { + use std::os::unix::ffi::OsStringExt; + let path = rustix::fs::getpath(file)?; + Ok(Some(PathBuf::from(OsString::from_vec(path.into_bytes())))) +} + +/// `None`: the platform does not report the path of an open file. +#[cfg(all(unix, not(any(target_os = "linux", target_os = "android", target_vendor = "apple"))))] +fn opened_path(_file: &File) -> io::Result> { + Ok(None) +} + /// Opens `path` for reading. On Unix the file is opened with `O_NONBLOCK`, so a path that was /// replaced by a named pipe after its type was checked opens at once instead of waiting for a /// writer; the caller checks the opened file's type. Reads from a regular file are not affected. @@ -661,6 +717,9 @@ mod tests { ("C:a", PathError::Character), ("\\\\server\\share\\a", PathError::Character), ("a\\..\\..\\b", PathError::Character), + ("a\u{1}b", PathError::Character), + ("a\u{7f}b", PathError::Character), + ("a\u{85}b", PathError::Character), ]; for (path, expected) in cases { match parse_err(&format!("{HELLO_SHA}\t{path}\n")) { @@ -819,6 +878,48 @@ mod tests { assert!(matches!(verify(&corpus.0, &manifest), Err(VerifyError::Escapes { .. }))); } + /// A file opened outside the folder, as after the listed path was changed into a link between + /// the first check and the open, is refused even when its contents match. + #[cfg(unix)] + #[test] + fn a_file_opened_outside_the_folder_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let entry = &manifest.entries[0]; + let opened = File::open(&other).expect("open the outside file"); + let meta = opened.metadata().expect("metadata"); + match opened_file_is_inside(&root, entry, &opened, &meta) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + let listed = File::open(root.join("hello.txt")).expect("open the listed file"); + let meta = listed.metadata().expect("metadata"); + opened_file_is_inside(&root, entry, &listed, &meta).expect("the listed file passes"); + } + + /// `verify` refuses a listed file that is changed into a link out of the folder after it was + /// resolved and before it is opened, even when the outside file's contents match. + #[cfg(unix)] + #[test] + fn a_file_changed_into_an_outside_link_before_the_open_fails() { + let (scratch, manifest) = hello_corpus(); + let outside = Scratch::new(); + let other = outside.write("hello.txt", HELLO); + let root = scratch.0.canonicalize().expect("canonical folder"); + let mut buf = vec![0u8; CHUNK]; + let swap = |path: &Path| { + std::fs::remove_file(path)?; + std::os::unix::fs::symlink(&other, path)?; + open_for_reading(path) + }; + match verify_entry_with(&root, &manifest.entries[0], &Limits::default(), &mut buf, swap) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + #[test] fn the_gate_skips_only_an_optional_unset_corpus() { let (scratch, _) = hello_corpus(); From b3476c5455ae4f615624c39a32daadf186f95e33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:30:36 -0800 Subject: [PATCH 4/8] craft-testkit: skip an unset corpus with skip::skip `corpus::pinned` no longer reads `_REQUIRED` itself or prints its own SKIPPED line. With the folder variable unset it calls `skip::skip`, so the required variable follows the same rule as every other skip: unset or empty skips, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. --- crates/testkit/src/corpus.rs | 67 +++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs index f40c6dc4f7..408039ee44 100644 --- a/crates/testkit/src/corpus.rs +++ b/crates/testkit/src/corpus.rs @@ -17,16 +17,16 @@ //! `/` between their parts. //! //! [`pinned`] is the gate a test calls: it returns the corpus folder named by a variable after -//! checking every listed file, prints one `SKIPPED:` line and returns `None` when the variable is -//! unset and the corpus is optional, and fails the test otherwise. [`verify`] runs the same check -//! and returns a [`VerifyError`] instead of failing. No function here downloads a file or changes -//! the process environment. +//! checking every listed file. When the variable is unset it skips or fails the test under the +//! rule of [`skip`](crate::skip::skip), and it fails the test on any other failure. [`verify`] +//! runs the same check and returns a [`VerifyError`] instead of failing. No function here +//! downloads a file or changes the process environment. //! //! Every input has a size limit, set by [`Limits`]: a manifest of at most 1 MiB and 10,000 rows, //! and files of at most 8 GiB each, read 64 KiB at a time. use std::collections::HashSet; -use std::ffi::{OsStr, OsString}; +use std::ffi::OsString; use std::fmt; use std::fs::File; use std::io::{self, Read}; @@ -525,13 +525,12 @@ fn open_for_reading(path: &Path) -> io::Result { /// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file /// `manifest` lists has been checked with [`verify`]. /// -/// The corpus is required when the variable named `var` plus [`REQUIRED_SUFFIX`] (by default -/// `CRAFT_CORPUS_REQUIRED`) is exactly `1`; unset, empty, `0`, `true` and any other value leave it -/// optional. -/// -/// - Folder variable unset and the corpus optional: prints one line, -/// `SKIPPED: corpus not given: set to its folder`, to stderr and returns `None`. -/// - Folder variable unset and the corpus required: fails the test. +/// - Folder variable unset: calls [`skip`](crate::skip::skip) with the reason +/// `corpus not given: set to its folder` and the variable named `var` plus +/// [`REQUIRED_SUFFIX`] (by default `CRAFT_CORPUS_REQUIRED`). When that variable is unset or +/// empty, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns +/// `None`. When it is `1`, it fails the test. Any other value, `0` included, fails the test as a +/// configuration error. /// - Folder variable set, even to an empty value: fails the test unless the manifest parses and /// every listed file matches. /// @@ -539,23 +538,23 @@ fn open_for_reading(path: &Path) -> io::Result { #[allow(clippy::panic)] pub fn pinned(var: Option<&str>, manifest: &str) -> Option { let var = var.unwrap_or(DEFAULT_VAR); - let required_var = format!("{var}{REQUIRED_SUFFIX}"); - let required = std::env::var_os(&required_var).as_deref() == Some(OsStr::new("1")); - match gate(std::env::var_os(var), required, var, &required_var, manifest) { + match gate(std::env::var_os(var), var, manifest) { Ok(Some(dir)) => Some(dir), Ok(None) => { - eprintln!("SKIPPED: corpus not given: set {var} to its folder"); + let required_var = format!("{var}{REQUIRED_SUFFIX}"); + let _ = crate::skip::skip(&format!("corpus not given: set {var} to its folder"), &required_var); None } Err(message) => panic!("{message}"), } } -/// The decision of [`pinned`], without reading the environment or printing: `Ok(None)` skips and -/// `Err` holds the message the test fails with. -fn gate(folder: Option, required: bool, var: &str, required_var: &str, manifest: &str) -> Result, String> { +/// The decision of [`pinned`] on the folder variable's value, without reading the environment or +/// printing: `Ok(None)` when the variable is unset, which [`pinned`] passes to +/// [`skip`](crate::skip::skip), and `Err` holds the message the test fails with. +fn gate(folder: Option, var: &str, manifest: &str) -> Result, String> { let Some(folder) = folder else { - return if required { Err(format!("corpus not given: {var} is unset and {required_var}=1 forbids skipping")) } else { Ok(None) }; + return Ok(None); }; if folder.is_empty() { return Err(format!("{var} is set but empty")); @@ -921,19 +920,17 @@ mod tests { } #[test] - fn the_gate_skips_only_an_optional_unset_corpus() { + fn the_gate_leaves_only_an_unset_folder_to_skip() { let (scratch, _) = hello_corpus(); let manifest = format!("{HELLO_SHA}\thello.txt\n"); - assert_eq!(gate(None, false, VAR, REQUIRED, &manifest), Ok(None)); - let required = gate(None, true, VAR, REQUIRED, &manifest).expect_err("required"); - assert!(required.contains(&format!("{REQUIRED}=1")), "{required}"); + assert_eq!(gate(None, VAR, &manifest), Ok(None)); let dir = scratch.0.clone().into_os_string(); - assert_eq!(gate(Some(dir.clone()), false, VAR, REQUIRED, &manifest), Ok(Some(scratch.0.clone()))); - let empty = gate(Some(OsString::new()), false, VAR, REQUIRED, &manifest).expect_err("empty"); + assert_eq!(gate(Some(dir.clone()), VAR, &manifest), Ok(Some(scratch.0.clone()))); + let empty = gate(Some(OsString::new()), VAR, &manifest).expect_err("empty"); assert!(empty.contains("empty"), "{empty}"); - let bad = gate(Some(dir.clone()), false, VAR, REQUIRED, "# c\nnot a row\n").expect_err("bad manifest"); + let bad = gate(Some(dir.clone()), VAR, "# c\nnot a row\n").expect_err("bad manifest"); assert!(bad.contains("line 2"), "{bad}"); - let missing = gate(Some(dir), false, VAR, REQUIRED, &format!("{EMPTY_SHA}\tabsent.bin\n")).expect_err("missing"); + let missing = gate(Some(dir), VAR, &format!("{EMPTY_SHA}\tabsent.bin\n")).expect_err("missing"); assert!(missing.contains("absent.bin"), "{missing}"); } @@ -967,8 +964,8 @@ mod tests { } #[test] - fn required_variable_unset_fails() { - for value in [None, Some(""), Some("0"), Some("true"), Some(" 1"), Some("1\n")] { + fn an_unset_folder_follows_the_skip_rule() { + for value in [None, Some("")] { let vars: Vec<(&str, &str)> = value.map(|v| (REQUIRED, v)).into_iter().collect(); let out = run_child("named", &vars); let err = String::from_utf8_lossy(&out.stderr); @@ -979,9 +976,17 @@ mod tests { let out = run_child("named", &[(REQUIRED, "1")]); let err = String::from_utf8_lossy(&out.stderr); assert!(!out.status.success(), "{err}"); - assert!(err.contains(&format!("{REQUIRED}=1 forbids skipping")), "{err}"); + assert!(err.contains(&format!("corpus not given: set {VAR} to its folder, and {REQUIRED}=1 forbids skipping")), "{err}"); assert!(!err.contains("SKIPPED:"), "{err}"); assert!(!err.contains("pinned returned"), "{err}"); + for value in ["0", "true", " 1", "1\n"] { + let out = run_child("named", &[(REQUIRED, value)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{value:?}: {err}"); + assert!(err.contains(&format!("{REQUIRED}={value:?} is not empty or 1")), "{value:?}: {err}"); + assert!(!err.contains("SKIPPED:"), "{value:?}: {err}"); + assert!(!err.contains("pinned returned"), "{value:?}: {err}"); + } } #[test] From 4bdac469e1835d0706a1bf45cc1c57b35908f7b0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:14:02 -0800 Subject: [PATCH 5/8] craft-testkit: fail pinned on a folder variable name that cannot be read pinned now fails the test when the folder variable name is empty or holds `=` or a NUL character, before the environment is read, instead of reading it as unset and skipping. The docs of verify and the README also state what the containment check after the open covers on each platform, that an Apple path query error fails verification, and that the manifest parser does not check names against a file system's rules. --- crates/testkit/README.md | 6 ++--- crates/testkit/src/corpus.rs | 50 +++++++++++++++++++++++++++++++----- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 4a77a4d1a2..863715fb87 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -243,11 +243,11 @@ Changes from `craft-media-testkit`'s `hammer`: A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. -- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a control character (NUL included), and a path listed twice. An empty optional column is `None`. +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a control character (NUL included), and a path listed twice. An empty optional column is `None`. The parser does not check that a name is valid on a given file system: a name Windows reserves (`<`, `>`, `"`, `|`, `?`, `*`, a trailing `.` or space, a device name such as `NUL`) or two names that differ only in case are accepted, so a manifest must use names that every file system it is verified on supports. - `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. - `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. -- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. After the open, `verify` also checks that the opened file is inside `dir`: on Linux, Android and Apple platforms by the path the kernel reports for the open file, and on other Unix systems, or when that path cannot be read, by resolving the listed path again and comparing its device and inode with the opened file's. That second lookup goes through the path again, so a folder changed during it is not detected. On Windows the location of the opened file is not checked again. -- `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. With the folder variable unset, it calls `skip::skip` with the reason `corpus not given: set to its folder` and the required variable `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`), so the [skip](#skip) rule applies: unset or empty prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. With the folder variable set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. +- On Unix, `Manifest::read` and `verify` open each file with `O_NONBLOCK` and check the opened file's type again, so a path replaced by a named pipe after the first check fails at once. After the open, `verify` also checks that the opened file is inside `dir`: on Linux, Android and Apple platforms by the path the kernel reports for the open file, and on other Unix systems, or on Linux and Android when `/proc/self/fd` cannot be read, by resolving the listed path again and comparing its device and inode with the opened file's. On Apple platforms an error from the path query fails verification with `VerifyError::Read` instead of falling back to the second lookup. That second lookup goes through the path again, so a folder changed during it is not detected. On Windows the location of the opened file is not checked again, so a part of the path changed into a link out of `dir` between the check and the open is not detected. In every case the opened file must still have the listed SHA-256. +- `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. With the folder variable unset, it calls `skip::skip` with the reason `corpus not given: set to its folder` and the required variable `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`), so the [skip](#skip) rule applies: unset or empty prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`, `1` fails the test, and any other value, `0` included, fails the test as a configuration error. With the folder variable set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. A `var` that is empty or holds `=` or a NUL character fails the test before the environment is read. Otherwise it returns the folder. `Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs index 408039ee44..96d6460074 100644 --- a/crates/testkit/src/corpus.rs +++ b/crates/testkit/src/corpus.rs @@ -200,8 +200,11 @@ fn parse_digest(text: &str) -> Option<[u8; 32]> { } /// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none -/// empty, `.` or `..`, and no `\`, `:` or control character (NUL included) anywhere, so the same -/// row means the same file on every platform. +/// empty, `.` or `..`, and no `\`, `:` or control character (NUL included) anywhere, so no +/// platform reads a row as an absolute path or a path outside the folder. It does not check that +/// each name is valid on a given file system: a name Windows reserves (`<>"|?*`, a trailing `.` or +/// space, a device name such as `NUL`) or one that differs from another only in case is accepted, +/// and the manifest must use names the file systems it is verified on support. fn check_path(path: &str) -> Result<(), PathError> { if path.is_empty() { return Err(PathError::Empty); @@ -400,6 +403,14 @@ pub fn verify(dir: &Path, manifest: &Manifest) -> Result<(), VerifyError> { /// Checks every file `manifest` lists in `dir`: each must resolve inside `dir` after symbolic /// links are followed, be a regular file of at most `limits.max_file_bytes` bytes, and have the /// listed SHA-256. Returns the first failure in manifest order. An empty manifest is an error. +/// +/// The resolved path is checked before the file is opened. On Unix the opened file is checked +/// again: on Linux, Android and Apple platforms by the path the kernel reports for it, and +/// elsewhere, or on Linux and Android without that path, by resolving the listed path a second time +/// and comparing device and inode. That second lookup does not detect a folder inside `dir` that is +/// changed while it runs. On Windows the opened file's location is not checked again, so a part of +/// the path changed into a link out of `dir` between the check and the open is not detected. In +/// each case the file must still have the listed SHA-256. pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> Result<(), VerifyError> { if manifest.entries.is_empty() { return Err(VerifyError::EmptyManifest); @@ -467,9 +478,11 @@ fn verify_entry_with( /// Checks, after the open, that the opened file is inside `root`, so a path changed into a link out /// of the folder between the first check and the open is refused. On Linux, Android and Apple -/// platforms the kernel reports the open file's path, which must start with `root`. On other Unix -/// systems, and where that path cannot be read, the entry's path is resolved again and must lead, without a link in its last part, to the -/// opened file (the same device and inode). +/// platforms the kernel reports the open file's path, which must start with `root`; on Apple +/// platforms an error from that query fails the check with [`VerifyError::Read`]. On other Unix +/// systems, and on Linux and Android when `/proc/self/fd` cannot be read, the entry's path is +/// resolved again and must lead, without a link in its last part, to the opened file (the same +/// device and inode). #[cfg(unix)] fn opened_file_is_inside(root: &Path, entry: &Entry, file: &File, opened: &std::fs::Metadata) -> Result<(), VerifyError> { use std::os::unix::fs::MetadataExt; @@ -534,10 +547,14 @@ fn open_for_reading(path: &Path) -> io::Result { /// - Folder variable set, even to an empty value: fails the test unless the manifest parses and /// every listed file matches. /// -/// It fails the test with a panic whose message names the variable and the failure. +/// A `var` that is empty or holds `=` or a NUL character fails the test before the environment is +/// read. It fails the test with a panic whose message names the variable and the failure. #[allow(clippy::panic)] pub fn pinned(var: Option<&str>, manifest: &str) -> Option { let var = var.unwrap_or(DEFAULT_VAR); + if let Err(message) = check_var(var) { + panic!("{message}"); + } match gate(std::env::var_os(var), var, manifest) { Ok(Some(dir)) => Some(dir), Ok(None) => { @@ -549,6 +566,15 @@ pub fn pinned(var: Option<&str>, manifest: &str) -> Option { } } +/// Refuses a folder variable name that is empty or holds `=` or a NUL character, the names +/// [`skip::required`](crate::skip::required) refuses. +fn check_var(var: &str) -> Result<(), String> { + if var.is_empty() || var.contains(['=', '\0']) { + return Err(format!("{var:?} cannot name the corpus folder variable: it is empty or holds `=` or a NUL character")); + } + Ok(()) +} + /// The decision of [`pinned`] on the folder variable's value, without reading the environment or /// printing: `Ok(None)` when the variable is unset, which [`pinned`] passes to /// [`skip`](crate::skip::skip), and `Err` holds the message the test fails with. @@ -1010,6 +1036,18 @@ mod tests { assert!(err.contains(&format!("{VAR} is set but empty")), "{err}"); } + #[test] + fn a_bad_folder_variable_name_fails_before_the_environment_is_read() { + for name in ["", "A=B", "A\0B"] { + assert!(check_var(name).is_err(), "{name:?}"); + let result = std::panic::catch_unwind(|| pinned(Some(name), "not a manifest")); + let payload = result.expect_err(&format!("{name:?} should fail the test")); + let message = payload.downcast_ref::().map(String::as_str).unwrap_or_default(); + assert!(message.contains("cannot name the corpus folder variable"), "{name:?}: {message}"); + } + assert_eq!(check_var(VAR), Ok(())); + } + #[test] fn pinned_defaults_to_craft_corpus() { let out = run_child("default", &[]); From 30fc207650d6770a690e9101da6a8f1783bd9e3b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:14:54 -0800 Subject: [PATCH 6/8] craft-testkit: write the skip line past the test output capture --- crates/testkit/src/skip.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs index 934c7df6e2..e9dbb58527 100644 --- a/crates/testkit/src/skip.rs +++ b/crates/testkit/src/skip.rs @@ -115,7 +115,9 @@ fn skip_with(required: bool, reason: &str, required_var: &str) -> bool { if required { panic!("{reason}, and {required_var}=1 forbids skipping this test"); } - eprint!("{}", skip_line(reason)); + // Written to the process's stderr directly: `eprint!` is captured by the test harness and + // would hide the line from a default run. + let _ = std::io::Write::write_all(&mut std::io::stderr().lock(), skip_line(reason).as_bytes()); false } @@ -385,6 +387,20 @@ mod tests { assert!(!err.contains("ran on"), "{err}"); } + #[test] + fn the_skip_line_shows_in_a_run_that_captures_test_output() { + let exe = std::env::current_exe().expect("the test binary's path"); + let out = Command::new(exe) + .args(["skip::tests::child", "--exact", "--test-threads=1"]) + .env(CHILD_CASE, "skip") + .env_remove(REQUIRED_VAR) + .output() + .expect("run the test binary"); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: probe absent\n"), "{err}"); + } + #[test] fn skip_lines_from_parallel_threads_stay_whole() { let out = run_child("threads", None); From d54781d859ab7dc66cea99a046a0f6b01df9058a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 16:06:12 -0800 Subject: [PATCH 7/8] audio-dsp: test startup vowels at 16 kHz --- crates/audio-dsp/src/effects/suppress.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/crates/audio-dsp/src/effects/suppress.rs b/crates/audio-dsp/src/effects/suppress.rs index 21083846b7..acebd93e37 100644 --- a/crates/audio-dsp/src/effects/suppress.rs +++ b/crates/audio-dsp/src/effects/suppress.rs @@ -875,6 +875,28 @@ mod tests { } } + #[test] + fn a_hop_periodic_startup_vowel_keeps_its_level_at_16_khz() { + let sr = 16_000.0; + let held = sr as usize * 3; + let mut speech = vec![0.0f32; held + sr as usize / 2]; + for (i, v) in speech[..held].iter_mut().enumerate() { + let t = std::f64::consts::TAU * 250.0 * i as f64 / sr as f64; + *v = (1..8).map(|h| (0.15 * (h as f64 * t).sin() / h as f64) as f32).sum(); + } + let mut s = NoiseSuppression::new(sr, 1); + assert!(s.set_param("reduction", 24.0)); + s.reset(); + assert_eq!(s.hop, sr as usize / 250); + let lat = s.latency(); + let mut y = speech.clone(); + s.process(&mut [&mut y]); + for range in [0..sr as usize * 2, sr as usize * 3 / 2..sr as usize * 2] { + let kept = db((energy(&y[range.start + lat..range.end + lat]) / energy(&speech[range.clone()])).sqrt()); + assert!(kept.abs() < 3.0, "the 250 Hz startup vowel at 16 kHz changed by {kept:.2} dB over {range:?}"); + } + } + /// Steady noise whose spectrum falls with frequency (white noise through a one-pole low-pass /// at 500 Hz) is suppressed by at least 20 dB from 4 s on. #[test] From 4c14eb978db259201a4be58791c90a4878e6c79e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:06:53 -0800 Subject: [PATCH 8/8] Save for Web: Optimize to File Size's OK waits while the size text does not parse Clicking the Optimize rows' OK while Desired File Size held text that does not parse filed a search with the size the rows held before. Clearing the field had the same effect for both OK and Enter, since the field took empty text as a blank value and the rows kept their old size. The size field now holds an f32, which has no blank value, so empty text does not parse either, and OK is disabled while the field's text does not parse, as the parameter dialogs hold their OK. Enter in the field already filed nothing for text that is not a number. --- .../form_dialogs/save_for_web/options.rs | 20 ++++++++--- .../tests/it/form_dialogs/save_for_web.rs | 34 +++++++++++++++++++ 2 files changed, 49 insertions(+), 5 deletions(-) diff --git a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs index 96b3ebc464..cdc32a2d7a 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/save_for_web/options.rs @@ -203,7 +203,8 @@ fn preset_row(ui: &mut Ui, kit: &Kit<'_>, options: &mut SaveForWebOptions, live: } /// "Optimize to File Size…" and, once opened, its rows; OK, or Enter in the Desired File Size field, files the search. -/// While the rows are closed, the host's last answer shows as a line while the settings are the ones it found. +/// OK waits while the Desired File Size holds text that does not parse. While the rows are closed, the host's last +/// answer shows as a line while the settings are the ones it found. fn optimize_rows(ui: &mut Ui, kit: &Kit<'_>, options: &SaveForWebOptions, live: &mut Live, asked: &mut Asked) { let Kit { words, units, .. } = *kit; if !live.optimize.open { @@ -218,10 +219,19 @@ fn optimize_rows(ui: &mut Ui, kit: &Kit<'_>, options: &SaveForWebOptions, live: } return; } + let mut unparsed = false; row(ui, &words.optimize_size, "optimize-size", |ui| { - let edit = whole(units, words.optimize_size.clone(), live.optimize.desired_k(), DESIRED_K).submits().show(ui).edit; - if let Some(k) = edit.value().cloned().flatten() { - live.optimize.k = Some(k); + // An `f32` field takes no blank value, so empty text does not parse, as text that is not a number does not. + let edit = NumberField::named(words.optimize_size.clone(), Bind::given(live.optimize.desired_k() as f32)) + .codec(NumberCodec::new(units.reader(None), 0)) + .step(1.0) + .range(DESIRED_K) + .submits() + .show(ui) + .edit; + unparsed = edit.unparsed; + if let Some(k) = edit.value().copied() { + live.optimize.k = Some(f64::from(k)); } if edit.submitted && edit.submit_mods == craft_keymap::Mods::NONE { asked.optimize_request = Some(live.optimize.request(options)); @@ -247,7 +257,7 @@ fn optimize_rows(ui: &mut Ui, kit: &Kit<'_>, options: &SaveForWebOptions, live: Text::new(reason.clone()).role(TypeRole::Caption).shade(Shade::Faint).id_salt("optimize-refused").show(ui); } Row::new().id_salt("optimize-buttons").show(ui, |ui, _| { - if clicked(&Button::new(words.optimize_ok.clone()).id_salt("optimize-ok").default_stop().show(ui)) { + if clicked(&Button::new(words.optimize_ok.clone()).id_salt("optimize-ok").enabled(!unparsed).default_stop().show(ui)) { asked.optimize_request = Some(live.optimize.request(options)); } if clicked(&Button::new(words.optimize_cancel.clone()).id_salt("optimize-cancel").show(ui)) { diff --git a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs index c1d12cdfd9..49f176fb51 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/save_for_web.rs @@ -320,6 +320,40 @@ fn enter_in_the_optimize_rows_files_the_search_and_never_saves() { assert!(host.borrow_mut().get_mut::().and_then(HostedSaveForWeb::pick_path).is_some(), "with the rows closed Enter saves"); } +// While the Desired File Size holds text the field refuses (not a number, or empty), the Optimize rows' OK and Enter in +// the field file no search with the size the rows held before; once the text parses, OK files the typed size. +#[trial] +fn the_optimize_rows_file_nothing_while_the_size_text_is_refused() { + let (host, mut fixture) = open(HostedSaveForWeb::new("poster.psd", IMAGE, texture()).optimize()); + let opener = fixture.by_label("Optimize to File Size…").expect("the Optimize button"); + fixture.click(&opener).idle(4); + assert!(host.borrow_mut().get_mut::().expect("open").take_optimize_open(), "opening the rows asks for the opening size"); + host.borrow_mut().get_mut::().expect("open").answer_optimize_start(Some(48 * 1024)); + fixture.idle(4); + let request = |host: &Rc>| host.borrow_mut().get_mut::().and_then(HostedSaveForWeb::take_optimize_request); + + for (text, what) in [("abc", "text that is not a number"), ("", "an empty field")] { + let field = fixture.by_label("Desired File Size (K)").expect("the Desired File Size field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).key(Key::Backspace, Modifiers::NONE).type_text(text); + fixture.idle(2); + fixture.key(Key::Enter, Modifiers::NONE).idle(4); + assert!(request(&host).is_none(), "Enter in the field files nothing while it holds {what}"); + let ok = fixture.by_label("OK").expect("the rows' OK"); + fixture.click(&ok).idle(4); + assert!(request(&host).is_none(), "OK files nothing while the field holds {what}"); + } + + let field = fixture.by_label("Desired File Size (K)").expect("the Desired File Size field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("20"); + fixture.idle(2); + let ok = fixture.by_label("OK").expect("the rows' OK"); + fixture.click(&ok).idle(4); + let filed = request(&host).expect("OK files the search once the text parses"); + assert_eq!(filed.desired_k, 20.0, "the search asks for the typed size"); +} + /// The frame the animation shows after the host's passes. fn frame_of(host: &Rc>) -> u32 { host.borrow_mut().get_mut::().map(|web| web.frame()).expect("the dialog is open")