fix(anatomy): R5.3 non-object children refused at add, reads confined to the seed, array length in the shape check, only run-created folders, seed guard tested in place

This commit is contained in:
bchanot committed 2026-10-23 10:11:51 +02:00
1 parent 42bbc48fcc
commit 86273b6206
6 files changed
+149 -21

No files matched your search

+52 -16
View File
@@ -61,17 +61,25 @@ struct Folder {
/// 1.1 MB): a resource cap on what the tool reads.
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
/// A regular file of the seed (never a symbolic link, a device or a pipe), read under the cap.
/// A regular file of the seed folder, read under the cap: its canonical path (every symbolic
/// link resolved, folders included) must lie in the canonical seed folder, so a link never
/// leads a read outside it; devices and pipes are refused. The repository is a single user's
/// working copy: a swap between the check and the read is not defended (RUST.md §11.13).
fn read(path: &Path) -> Result<Vec<u8>, String> {
let refuse = |why: &str| format!("{}: {why}", path.display());
let metadata = fs::symlink_metadata(path).map_err(|error| refuse(&error.to_string()))?;
let seed = fs::canonicalize(SEED).map_err(|error| format!("{SEED}: {error}"))?;
let canonical = fs::canonicalize(path).map_err(|error| refuse(&error.to_string()))?;
if !inside(&canonical, &seed) {
return Err(refuse("leads outside the seed folder"));
}
let metadata = fs::metadata(&canonical).map_err(|error| refuse(&error.to_string()))?;
if !metadata.file_type().is_file() {
return Err(refuse("not a regular file"));
}
if metadata.len() > MAX_FILE_BYTES {
return Err(refuse(&format!("larger than {MAX_FILE_BYTES} bytes")));
}
fs::read(path).map_err(|error| refuse(&error.to_string()))
fs::read(&canonical).map_err(|error| refuse(&error.to_string()))
}
/// `readFile(path, 'utf8')`: invalid UTF-8 becomes U+FFFD, as the TypeScript read the
@@ -201,7 +209,7 @@ fn check(folder: &Folder) -> Result<Vec<String>, String> {
/// (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> {
fn claim_destination(typed: &Path, seed: &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());
@@ -219,8 +227,7 @@ fn claim_destination(typed: &Path) -> Result<PathBuf, String> {
}
None => return Err(refuse("not a destination folder")),
};
let seed = fs::canonicalize(SEED).map_err(|error| format!("{SEED}: {error}"))?;
if inside(&parent, &seed) {
if inside(&parent, seed) {
return Err(refuse("inside the seed folder"));
}
let name = out
@@ -258,10 +265,15 @@ fn base_dir() -> PathBuf {
.unwrap_or_default()
}
/// 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> {
/// Creates `relative` and the folders leading to it under `root`: every folder is one this run
/// created (`created`), every file 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],
created: &mut Vec<PathBuf>,
) -> Result<(), String> {
// The claimed folder is checked again: a swap for a symbolic link since the claim is refused.
if !fs::symlink_metadata(root).is_ok_and(|m| m.file_type().is_dir()) {
return Err(format!("{}: no longer the claimed folder", root.display()));
@@ -277,11 +289,11 @@ fn write_exclusive(root: &Path, relative: &Path, bytes: &[u8]) -> Result<(), Str
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())),
if created.contains(&folder) {
continue;
}
fs::create_dir(&folder).map_err(|error| format!("{}: {error}", folder.display()))?;
created.push(folder.clone());
}
let path = folder.join(file);
let mut handle = OpenOptions::new()
@@ -297,9 +309,11 @@ fn write_exclusive(root: &Path, relative: &Path, bytes: &[u8]) -> Result<(), Str
/// Writes every file under the claimed destination; returns the file count.
fn write(folders: &[Folder], root: &Path) -> Result<usize, String> {
let mut written = 0;
let mut created = Vec::new();
for folder in folders {
for (name, bytes) in &folder.files {
write_exclusive(root, &Path::new(folder.name).join(name), bytes)?;
let relative = Path::new(folder.name).join(name);
write_exclusive(root, &relative, bytes, &mut created)?;
written += 1;
}
}
@@ -330,7 +344,8 @@ fn run(args: &[String]) -> Result<i32, String> {
if dir.is_empty() {
return Err("--out needs a destination path".to_owned());
}
let root = claim_destination(&base_dir().join(dir))?;
let seed = fs::canonicalize(SEED).map_err(|error| format!("{SEED}: {error}"))?;
let root = claim_destination(&base_dir().join(dir), &seed)?;
println!("writing to {}", root.display());
let written = write(&folders, &root)?;
println!("{written} files written to {}", root.display());
@@ -362,6 +377,27 @@ fn main() {
mod tests {
use super::*;
/// Fixed fixtures under the system's temporary folder: created once, never deleted, never
/// written by the refusals below.
fn fixture_seed() -> PathBuf {
let base = env::temp_dir().join("faunosteo-import-equine-claim");
fs::create_dir_all(base.join("seed/draft")).unwrap_or_else(|e| panic!("{e}"));
fs::canonicalize(base.join("seed")).unwrap_or_else(|e| panic!("{e}"))
}
#[test]
fn the_claim_refuses_a_destination_inside_the_seed_and_creates_nothing() {
let seed = fixture_seed();
for typed in [seed.join("new"), seed.join("draft/new")] {
let refused = claim_destination(&typed, &seed).err().unwrap_or_default();
assert!(refused.contains("inside the seed folder"), "{refused}");
assert!(fs::symlink_metadata(&typed).is_err());
}
let parent = seed.parent().map(Path::to_path_buf).unwrap_or_default();
let refused = claim_destination(&parent, &seed).err().unwrap_or_default();
assert!(refused.contains("not empty"), "{refused}");
}
#[test]
fn a_folder_under_the_seed_or_the_seed_itself_is_inside_it() {
let seed = Path::new("/repo/supabase/seed/anatomical-sheets/equine");
+26
View File
@@ -238,6 +238,31 @@ fn add_destination(doc: &mut Value, op: &AddOp) -> Result<Destination, PipelineE
})
}
/// Every entry of a `children` or `categories` list of an added value must be an object. The
/// TypeScript met a null or a primitive there inconsistently (a TypeError when it walked it,
/// silently skipped when a rename walked past it, refused by the gate when it stayed); the
/// port refuses it at the add (RUST.md §11.12). Walked with an explicit stack.
fn assert_object_children(value: &Value) -> Result<(), PipelineError> {
let mut pending = vec![value];
while let Some(item) = pending.pop() {
let Some(map) = item.as_object() else {
continue;
};
for key in ["children", "categories"] {
let Some(list) = map.get(key).and_then(Value::as_array) else {
continue;
};
if list.iter().any(|entry| !entry.is_object()) {
return Err(fail(format!(
"the added item holds a \"{key}\" entry that is not an object"
)));
}
pending.extend(list);
}
}
Ok(())
}
fn apply_add(
doc: &mut Value,
recorder: &mut Recorder<'_>,
@@ -246,6 +271,7 @@ fn apply_add(
let Some(value) = op.value.as_object() else {
return Err(fail("add needs an object value"));
};
assert_object_children(&op.value)?;
let dest = add_destination(doc, op)?;
let Some(id) = value.get(dest.key).and_then(Value::as_str) else {
return Err(fail(format!(
+6 -1
View File
@@ -44,7 +44,12 @@ fn first_mismatch(written: &Value, typed: &Value, path: &str) -> Option<String>
None => Some(format!("unexpected key at {here}")),
}
}),
(Value::Array(w), Value::Array(t)) if w.len() == t.len() => w
(Value::Array(w), Value::Array(t)) if w.len() != t.len() => Some(format!(
"expected {} items at {path}, received {}",
t.len(),
w.len()
)),
(Value::Array(w), Value::Array(t)) => w
.iter()
.zip(t)
.enumerate()