fix(anatomy): R5.3 final gates: NUL field segments refused, field path and document depth bounded, --out writes exclusive, .. / missing parent / seed destination refused

This commit is contained in:
bchanot committed 2026-10-23 01:08:07 +02:00
1 parent 865490512e
commit 9f11499f2c
4 files changed
+215 -37

No files matched your search

+76 -37
View File
@@ -14,7 +14,9 @@
//! `report-compare`, this file is the only one of its tool allowed the file system.
#![allow(clippy::disallowed_methods)]
use std::path::{Path, PathBuf};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Component, Path, PathBuf};
use std::{env, fs, process};
use faunosteo_core::curation::draft::{
@@ -179,47 +181,55 @@ fn check(folder: &Folder) -> Result<Vec<String>, String> {
Ok(problems)
}
/// Claims a destination this tool may fill and returns its canonical path: a non-empty path
/// that is absent (created here, so nothing can appear between the check and the writes) or
/// an empty folder that is not a symbolic link. The canonical path is where the files land,
/// symbolic links of the parent folders resolved, and is what the success line prints.
/// Claims a destination this tool may fill and returns its canonical path. The typed path
/// must be non-empty, hold no `..`, have an existing parent folder, and name either nothing
/// (the folder is created here, its parent's symbolic links resolved) or an empty folder that
/// is not a symbolic link. A destination inside the seed folder is refused: the tool never
/// writes into the official seed. The writes that follow are exclusive (`write_exclusive`).
fn claim_destination(typed: &Path) -> Result<PathBuf, String> {
let refuse = |why: &str| format!("{}: {why}, nothing written", typed.display());
if typed.as_os_str().is_empty() {
return Err("--out needs a destination path".to_owned());
}
if typed.components().any(|c| c == Component::ParentDir) {
return Err(refuse("`..` is not accepted"));
}
// Rebuilt from its components: a trailing `/` would make the system resolve a final
// symbolic link before the check below could see it.
let out: PathBuf = typed.components().collect();
let out = out.as_path();
match fs::symlink_metadata(out) {
Err(_) => {
if let Some(parent) = out.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
}
fs::create_dir(out).map_err(|e| format!("{}: {e}, nothing written", out.display()))?;
}
Ok(metadata) if metadata.file_type().is_symlink() => {
return Err(format!(
"{}: a symbolic link, nothing written",
out.display()
));
}
Ok(metadata) if !metadata.is_dir() => {
return Err(format!("{}: not a folder, nothing written", out.display()));
let parent = out.parent().filter(|p| !p.as_os_str().is_empty());
let parent = match parent {
Some(parent) => {
fs::canonicalize(parent).map_err(|_| refuse("the parent folder does not exist"))?
}
None => return Err(refuse("not a destination folder")),
};
let seed = fs::canonicalize(SEED).map_err(|error| format!("{SEED}: {error}"))?;
if parent.starts_with(&seed) {
return Err(refuse("inside the seed folder"));
}
let name = out
.file_name()
.ok_or_else(|| format!("{}: not a destination folder", typed.display()))?;
let root = parent.join(name);
match fs::symlink_metadata(&root) {
Err(_) => fs::create_dir(&root).map_err(|error| refuse(&error.to_string()))?,
Ok(metadata) if metadata.file_type().is_symlink() => return Err(refuse("a symbolic link")),
Ok(metadata) if !metadata.is_dir() => return Err(refuse("not a folder")),
Ok(_) => {
let mut entries =
fs::read_dir(out).map_err(|error| format!("{}: {error}", out.display()))?;
fs::read_dir(&root).map_err(|error| format!("{}: {error}", root.display()))?;
if entries.next().is_some() {
return Err(format!("{}: not empty, nothing written", out.display()));
return Err(refuse("not empty"));
}
}
}
fs::canonicalize(out).map_err(|error| format!("{}: {error}", out.display()))
Ok(root)
}
/// Where a relative destination is typed from: `INIT_CWD` when pnpm set it to an absolute
/// path, else the current folder.
/// path, else the current folder (the repository root when the script is run directly: it
/// moves there first).
fn base_dir() -> PathBuf {
env::var_os("INIT_CWD")
.map(PathBuf::from)
@@ -228,22 +238,42 @@ fn base_dir() -> PathBuf {
.unwrap_or_default()
}
/// Writes every file under the claimed destination; returns it and the file count.
fn write(folders: &[Folder], out: &Path) -> Result<(PathBuf, usize), String> {
let root = claim_destination(out)?;
/// Creates `path` and the folders leading to it under `root`, each one new: an entry that
/// appeared since the claim, file, folder or symbolic link, is refused, never followed or
/// truncated (`create_dir`, `create_new`).
fn write_exclusive(root: &Path, relative: &Path, bytes: &[u8]) -> Result<(), String> {
let mut folder = root.to_path_buf();
let components: Vec<_> = relative.components().collect();
let (file, folders) = components.split_last().ok_or("an empty file name")?;
for component in folders {
folder.push(component);
match fs::create_dir(&folder) {
Ok(()) => {}
Err(_) if fs::symlink_metadata(&folder).is_ok_and(|m| m.is_dir()) => {}
Err(error) => return Err(format!("{}: {error}", folder.display())),
}
}
let path = folder.join(file);
let mut handle = OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
.map_err(|error| format!("{}: {error}", path.display()))?;
handle
.write_all(bytes)
.map_err(|error| format!("{}: {error}", path.display()))
}
/// Writes every file under the claimed destination; returns the file count.
fn write(folders: &[Folder], root: &Path) -> Result<usize, String> {
let mut written = 0;
for folder in folders {
for (name, bytes) in &folder.files {
let path = root.join(folder.name).join(name);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|error| format!("{}: {error}", parent.display()))?;
}
fs::write(&path, bytes).map_err(|error| format!("{}: {error}", path.display()))?;
write_exclusive(root, &Path::new(folder.name).join(name), bytes)?;
written += 1;
}
}
Ok((root, written))
Ok(written)
}
fn run(args: &[String]) -> Result<i32, String> {
@@ -270,7 +300,9 @@ fn run(args: &[String]) -> Result<i32, String> {
if dir.is_empty() {
return Err("--out needs a destination path".to_owned());
}
let (root, written) = write(&folders, &base_dir().join(dir))?;
let root = claim_destination(&base_dir().join(dir))?;
println!("writing to {}", root.display());
let written = write(&folders, &root)?;
println!("{written} files written to {}", root.display());
Ok(0)
}
@@ -279,7 +311,14 @@ fn run(args: &[String]) -> Result<i32, String> {
}
fn main() {
let args: Vec<String> = env::args().skip(1).collect();
let args: Option<Vec<String>> = env::args_os()
.skip(1)
.map(|a| a.into_string().ok())
.collect();
let Some(args) = args else {
eprintln!("an argument is not valid UTF-8");
process::exit(2);
};
match run(&args) {
Ok(code) => process::exit(code),
Err(message) => {