From b89badcd6f883751f79960f93c554fb77f063885 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 15:42:13 -0500 Subject: [PATCH 1/5] Budget the total payload of one .mcmat (#499) * formats: budget the total payload of one .mcmat * formats: format the .mcmat map-limit test --- crates/formats/src/mcmat.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/crates/formats/src/mcmat.rs b/crates/formats/src/mcmat.rs index 55b6f6ee..441bae10 100644 --- a/crates/formats/src/mcmat.rs +++ b/crates/formats/src/mcmat.rs @@ -20,6 +20,10 @@ const FORMAT: &str = "craft-material"; const VERSION: u32 = 1; /// Largest entry read (maps are at most 8192² × 16 bits, compressed). const MAX_ENTRY: u64 = 512 << 20; +/// Most map entries one manifest may name (a material has at most nine usages). +const MAX_MAPS: usize = 64; +/// Largest total payload read from one `.mcmat`: maps and source together (audit: TextureCraft #4). +const MAX_TOTAL: u64 = 1 << 30; const KIND: &str = "MaterialCraft material"; #[derive(Clone, Debug, PartialEq, Deserialize)] @@ -69,6 +73,7 @@ fn malformed(msg: impl Into) -> FormatError { /// Read `.mcmat` bytes. pub fn read_mcmat(bytes: &[u8]) -> Result { let mut z = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|e| malformed(e.to_string()))?; + let mut total = 0u64; let mut read = |name: &str| -> Result> { let mut out = Vec::new(); let f = z.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?; @@ -76,6 +81,10 @@ pub fn read_mcmat(bytes: &[u8]) -> Result { if out.len() as u64 > MAX_ENTRY { return Err(FormatError::TooLarge(name.to_string())); } + total = total.saturating_add(out.len() as u64); + if total > MAX_TOTAL { + return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)"))); + } Ok(out) }; let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|e| malformed(format!("material.json: {e}")))?; @@ -85,6 +94,9 @@ pub fn read_mcmat(bytes: &[u8]) -> Result { if manifest.version > VERSION { return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version))); } + if manifest.maps.len() > MAX_MAPS { + return Err(malformed(format!("{} maps, over the {MAX_MAPS} map limit", manifest.maps.len()))); + } let maps = manifest.maps.iter().map(|m| Ok((m.usage.clone(), read(&m.file)?))).collect::>>()?; let source = read(&manifest.source)?; Ok(PortableMaterial { manifest, maps, source }) @@ -167,6 +179,22 @@ mod tests { assert!(read_mcmat(b"junk").is_err()); } + #[test] + fn an_unbounded_map_list_is_refused() { + let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect(); + let manifest = + serde_json::json!({"format": FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"}); + let mut z = zip::ZipWriter::new(Cursor::new(Vec::new())); + let o = zip::write::SimpleFileOptions::default(); + z.start_file("material.json", o).unwrap(); + z.write_all(manifest.to_string().as_bytes()).unwrap(); + z.start_file("maps/baseColor.png", o).unwrap(); + z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap(); + z.start_file("source.mcraft", o).unwrap(); + z.write_all(b"pkg").unwrap(); + assert!(read_mcmat(&z.finish().unwrap().into_inner()).is_err()); + } + #[test] fn mesh_maps_encode_as_16_bit() { let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap(); From 73083d418a2b680867d823e6542bdefb20f92d1e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 17:02:27 -0500 Subject: [PATCH 2/5] formats: cap default resource image decode at 64 M texels (#506) Imported images still used the 16384-pixel edge limit with no texel ceiling, so a small 16k square PNG expanded to multi-gigabyte RGBA f32 buffers. Default resource decoding now refuses more than 8192 square texels from the header, and the engine import path uses the same budget. --- crates/engine/src/resource_cmds.rs | 2 +- crates/formats/src/image_res.rs | 15 +++++++++++++-- crates/formats/src/lib.rs | 4 ++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/resource_cmds.rs b/crates/engine/src/resource_cmds.rs index 54876d19..67665c4e 100644 --- a/crates/engine/src/resource_cmds.rs +++ b/crates/engine/src/resource_cmds.rs @@ -38,7 +38,7 @@ pub(crate) fn decoded(d: texturecraft_formats::DecodedImage) -> Arc { impl Session { /// Add an image resource from bytes (one undo step); returns its unique, sanitized name pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec) -> Result { - self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, u64::MAX)) + self.edit("Import resource", |s| s.add_image_resource(file_name, bytes, texturecraft_formats::MAX_RESOURCE_TEXELS)) } /// Add an image within a decoded texel budget, inside the caller's edit diff --git a/crates/formats/src/image_res.rs b/crates/formats/src/image_res.rs index 85590d9d..bcff2435 100644 --- a/crates/formats/src/image_res.rs +++ b/crates/formats/src/image_res.rs @@ -1,6 +1,6 @@ //! Decoding imported image resources (fills, alphas, stencils). -use crate::{FormatError, MAX_IMAGE_SIZE, Result}; +use crate::{FormatError, MAX_IMAGE_SIZE, MAX_RESOURCE_TEXELS, Result}; /// A decoded image: RGBA as 0..1 floats in the file's own encoding (8/16-bit files stay /// sRGB-encoded; `srgb` says so), row-major, top row first. @@ -15,7 +15,7 @@ pub struct DecodedImage { /// Decode PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR bytes. pub fn decode_image(bytes: &[u8]) -> Result { - decode_image_within(bytes, u64::MAX) + decode_image_within(bytes, MAX_RESOURCE_TEXELS) } /// [`decode_image`] for an image of at most `max_texels` (width × height), checked from the @@ -100,4 +100,15 @@ mod tests { assert!(matches!(decode_image_within(&png, 63), Err(FormatError::TooLarge(_)))); assert!(decode_image(&png).is_ok()); } + + #[test] + fn the_default_decoder_refuses_more_than_the_resource_texel_budget_from_the_header() { + // An 18-byte TGA header: 16384² is inside the edge limit but far over 64 M texels. + let mut header = [0u8; 18]; + header[2] = 2; + header[12..14].copy_from_slice(&16_384u16.to_le_bytes()); + header[14..16].copy_from_slice(&16_384u16.to_le_bytes()); + header[16] = 24; + assert!(matches!(decode_image(&header), Err(FormatError::TooLarge(_)))); + } } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 6e57432e..d8550531 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -95,6 +95,10 @@ pub(crate) fn guard(kind: &'static str, f: impl FnOnce() -> Result) -> Res /// Largest image edge accepted or produced anywhere in this crate. pub const MAX_IMAGE_SIZE: u32 = 16_384; +/// Most texels an imported image resource may decode to by default (8192 × 8192). +/// Larger images are refused from their header before any pixels are decoded. +pub const MAX_RESOURCE_TEXELS: u64 = 1 << 26; + /// Read a whole file, refusing files over `cap` bytes. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { From 0fa3a392fd61b3e02a86e8136bfbaa178be76100 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 17:23:06 -0500 Subject: [PATCH 3/5] formats: create atomic-write temps exclusively so a planted symlink is never followed (#502) --- crates/formats/src/lib.rs | 48 +++++++++++++++++++++++--- crates/formats/src/project_file/mod.rs | 6 ++-- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index d8550531..3708d737 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -112,15 +112,53 @@ pub(crate) fn read_capped(path: &std::path::Path, cap: u64) -> Result> { Ok(std::fs::read(path)?) } -/// Write `bytes` to `path` atomically: `.tmp` first, then rename over the target. +/// Create a new temporary file beside `path`, refusing to reuse an existing (possibly symlinked) name. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn create_temp(path: &std::path::Path) -> Result<(std::path::PathBuf, std::fs::File)> { + let parent = path.parent().unwrap_or_else(|| std::path::Path::new(".")); + let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("out"); + for attempt in 0..100u32 { + let tmp = parent.join(format!(".{name}.{}.{attempt}.tmp", std::process::id())); + match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) { + Ok(file) => return Ok((tmp, file)), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => return Err(e.into()), + } + } + Err(FormatError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, "could not create a temporary file"))) +} + +/// Write `bytes` to `path` atomically: a new temporary file first, then rename over the target. #[cfg(not(target_arch = "wasm32"))] pub fn write_atomic(path: &std::path::Path, bytes: &[u8]) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); - let res = std::fs::write(&tmp, bytes).and_then(|_| std::fs::rename(&tmp, path)); + use std::io::Write; + let (tmp, mut file) = create_temp(path)?; + let res = file.write_all(bytes).and_then(|_| file.sync_all()); + drop(file); + let res = res.and_then(|_| std::fs::rename(&tmp, path)); if res.is_err() { let _ = std::fs::remove_file(&tmp); } Ok(res?) } + +#[cfg(all(test, unix))] +mod atomic_tests { + use super::write_atomic; + + #[test] + fn write_atomic_does_not_follow_a_planted_temp_symlink() -> std::io::Result<()> { + let dir = std::env::temp_dir().join(format!("tc-atomic-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir)?; + let target = dir.join("out.png"); + let victim = dir.join("victim.txt"); + std::fs::write(&victim, b"safe")?; + std::os::unix::fs::symlink(&victim, dir.join("out.png.tmp"))?; + write_atomic(&target, b"new").map_err(std::io::Error::other)?; + assert_eq!(std::fs::read(&victim)?, b"safe"); + assert_eq!(std::fs::read(&target)?, b"new"); + let _ = std::fs::remove_dir_all(&dir); + Ok(()) + } +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 8390220a..e982d761 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -101,11 +101,9 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result> { /// Save atomically: `.tmp` first, then rename over `path`. #[cfg(not(target_arch = "wasm32"))] pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { - let mut tmp = path.as_os_str().to_owned(); - tmp.push(".tmp"); - let tmp = std::path::PathBuf::from(tmp); + let (tmp, file) = crate::create_temp(path)?; let res = (|| -> Result<()> { - let mut file = std::io::BufWriter::new(std::fs::File::create(&tmp)?); + let mut file = std::io::BufWriter::new(file); write_project(&mut file, pf)?; file.into_inner().map_err(|e| e.into_error())?.sync_all()?; std::fs::rename(&tmp, path)?; From 9ed81da8cbcfff0bf11d362f0e83fa4baa9d1300 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 14 Nov 2026 17:28:04 -0500 Subject: [PATCH 4/5] formats: account for the USDC path table's real allocation (#507) The PATHS table charged 64 bytes per entry but allocates Option (about 80), letting a small declared count exceed the decoded-byte budget, and had no entry ceiling. Charge the real element size and cap the table at four million paths. --- crates/formats/src/mesh_import/usd/usdc.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 221c7b4a..0a07b637 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -15,6 +15,9 @@ const MIN_VERSION: (u8, u8, u8) = (0, 4, 0); const MAX_SECTIONS: usize = 64; /// Items in one table or array. const MAX_ITEMS: usize = 1 << 28; +/// Entries in the PATHS table. The declared count is tiny in the file but each entry is a +/// materialised path, so it needs its own ceiling as well as the decoded-byte budget. +const MAX_PATHS: usize = 4_000_000; /// Spec types. const SPEC_ATTRIBUTE: i64 = 1; @@ -248,7 +251,11 @@ impl<'a> Crate<'a> { let index = s.ints(n, 4, budget)?; let elements = s.ints(n, 4, budget)?; let jumps = s.ints(n, 4, budget)?; - budget.take(total.saturating_mul(64))?; + if total > MAX_PATHS { + return Err(FormatError::TooLarge(format!("the USD path table has {total} entries (limit {MAX_PATHS})"))); + } + // Charge what the vector really allocates, not a guessed 64 bytes per entry. + budget.take(total.saturating_mul(std::mem::size_of::>()))?; self.paths = vec![None; total]; let mut work: Vec<(usize, Option)> = vec![(0, None)]; let mut steps = 0usize; From 5e4f511f178d6691d052123321e194113c1bcae0 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Sat, 14 Nov 2026 21:18:26 -0500 Subject: [PATCH 5/5] Added CODE_STYLE (not referenced by AGENTS) as helper for maintaining better code quality --- CODE_STYLE.md | 77 ++++++++++++++++++++++++++++ docs/helpful-pr-review-guidelines.md | 36 +------------ 2 files changed, 79 insertions(+), 34 deletions(-) create mode 100644 CODE_STYLE.md diff --git a/CODE_STYLE.md b/CODE_STYLE.md new file mode 100644 index 00000000..86dcc057 --- /dev/null +++ b/CODE_STYLE.md @@ -0,0 +1,77 @@ +# Code style + +Style conventions for MaterialCraft's Rust code. +Read alongside [AGENTS.md](AGENTS.md) for repository requirements. + +## Naming and Rust conventions + +- Use descriptive names that explain purpose; include units where useful. Avoid misleading names + and abbreviations whose meaning is unclear in context. +- Follow Rust naming conventions: `snake_case` for functions, variables, fields, and modules; + `UpperCamelCase` for types and traits; `SCREAMING_SNAKE_CASE` for constants and statics. +- Conventional Rust names are not cryptic abbreviations. Keep names such as `fmt`, `iter`, `len`, + `args`, `err`, `id`, and `ui` when their meaning is clear. Do not expand them just to make them + longer. +- Keep standard file and directory names such as `lib.rs`, `main.rs`, `mod.rs`, `src`, `tests`, + `examples`, and `benches`. Rust keywords such as `mut`, `ref`, `impl`, and `mod` are language + syntax, not naming problems. +- Short names are appropriate in a clear local context: `i` for an index, `x` and `y` for + coordinates, `w` and `h` for image dimensions, and conventional generic parameters such as `T`. + Use more descriptive names when scope or ambiguity makes those hard to follow. + +## Magic numbers + +- Give non-obvious limits, thresholds, sizes, and tuning values descriptive named constants + instead of leaving unexplained numeric literals in the code. +- Name constants for their purpose, with units where useful, rather than for their literal value. + Keep them in the narrowest useful scope. +- Reuse an existing constant when it represents the same concept. Equal numeric values alone do + not mean two concepts should share a constant. +- Explain the origin or rationale of non-obvious coefficients and tolerances in a short comment. + Use standard library constants for standard mathematical values. +- Keep literals inline when their role is clear, such as zero initialization, incrementing by one, + or dividing by two to find a midpoint. Do not introduce names such as `ZERO` or `TWO` that add + no meaning. +- Apply this guidance to tests too; clear fixture values and expected results can remain literal. + +## Formatting and spacing + +- Let `cargo fmt` and the repository's [rustfmt.toml](rustfmt.toml) handle mechanical formatting. + Do not introduce a competing indentation or line-wrapping convention. +- Use one blank line between distinct logical steps: input preparation, validation, computation, + mutation, and result construction. +- Keep closely related statements together. Do not add a blank line after every declaration or + fragment a single operation with extra spacing. +- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before + the next statement. +- Put a blank line before a comment introducing a new step, with no blank line between the + comment and the code it explains. +- Keep documentation and attributes attached to their declarations. +- Separate function definitions with one blank line. Avoid extra empty lines just inside braces + or between every field, argument, or statement. +- In tests, separate preparation, action, and verification with blank lines when those phases + are distinct; keep related assertions together. + +## Source organization + +- Give each struct or enum its own source file, with its implementation beside it. Use the full + type name in `snake_case`, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings`. +- Preserve conventional crate roots and module entry points such as `lib.rs`, `main.rs`, and + `mod.rs`. Follow the command and node module placement required by `AGENTS.md`. +- Prefer singular folder names for new domain modules, such as `map`, `setting`, or `tracing`. + Keep standard Rust directories and repository-mandated paths unchanged. +- Group related types into focused modules rather than collecting unrelated types in one large file. +- Apply these preferences to new types and source organization changes within scope. Do not + reorganize unrelated existing code to enforce them. + +## Comments + +- Explain intent or a non-obvious constraint rather than narrating the code. +- Use short `//` comments. Avoid block comments and wrapped prose in ordinary implementation + comments; adjacent comment lines should each express a concise point. +- Do not add trailing punctuation to ordinary code comments. +- Preserve explanations of guards and invariants. Remove stale or redundant comments without + losing necessary rationale. +- API documentation, required license headers, and examples may use conventional multiline + formatting and punctuation. +- Apply the same comment guidance to production code and tests. diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md index 098b6ae1..fbe4f69d 100644 --- a/docs/helpful-pr-review-guidelines.md +++ b/docs/helpful-pr-review-guidelines.md @@ -8,7 +8,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Review-only requests call for findings; requests to fix or improve also authorize focused local edits - A review may conclude that no changes are needed. If the PR meets the applicable standards and no actionable issues are found, leave it unchanged. Do not invent findings, add unnecessary tests, or make edits merely to produce a diff. Report what was checked and any remaining validation limits - Apply all review standards across the entire affected method, including existing code and relevant tests -- Complete naming, spacing, and comment cleanup throughout it +- Read and apply [CODE_STYLE.md](../CODE_STYLE.md) throughout that scope - Make additional correctness or performance changes when supported by evidence and appropriate validation - Separate substantial changes that address an independent problem, explaining why - Apply the same scope to standalone functions and inspect relevant callers when verifying behavior @@ -27,6 +27,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi ## Optimization and simplicity - Prefer the smallest complete solution that is efficient and easy to understand +- Keep control flow direct and share repeated logic when it makes the code simpler - Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access - For loops, batches, and streaming operations, trace allocations and buffer lifetimes across multiple iterations, including outputs retained from earlier iterations. Identify work that belongs once per operation rather than once per item, using the full selection when making retention decisions - Consider caching, batching, and parallelism when measurements justify their complexity and memory cost @@ -35,39 +36,6 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Check what the compiler already optimizes before replacing clear arithmetic with micro-optimizations - Avoid speculative optimization, unnecessary dependencies, and abstractions that add more code than clarity -## Clarity, naming, and spacing - -- Clean up the functions or methods being changed and their relevant tests within the scope above -- Use descriptive names that explain purpose; include units where useful -- Avoid cryptic abbreviations, misleading names, and unexplained production constants -- Keep control flow direct and share repeated logic when it makes the code simpler -- Use a single blank line to separate logical steps, such as input preparation, validation, computation, mutation, and result construction, when those steps are distinct -- Keep closely related statements together; avoid spacing that fragments a single operation or inserts a blank line after every declaration -- Put a blank line after a multiline early-exit guard, including `if` and `let ... else`, before the next statement -- Keep comments attached to the code they explain; put a blank line before a comment introducing a new step, with no blank line between the comment and that step -- Keep documentation and attributes attached to their declarations -- Separate function definitions with one blank line; avoid extra empty lines immediately inside braces or between every field, argument, or statement -- Group tests into preparation, action, and verification with blank lines where those phases are distinct; keep related assertions together -- Apply this spacing consistently throughout affected functions, methods, and tests, and follow the repository's formatter for mechanical formatting - -## Source organization - -- Keep each class, enum, or struct in its own source file, with its implementation beside it -- Spell out the full type name in the filename; use the language's filename convention, such as `mesh_curvature_settings.rs` for `MeshCurvatureSettings` in Rust -- Use singular folder names, such as `map`, `setting`, or `tracing` -- Group related types into focused modules and share helpers where useful without collecting unrelated types into one large file -- Apply these preferences to new types and source organization changes within scope; follow mandatory repository layout rules and leave unrelated existing structure alone - -## Comments - -- Use short, single-line comments; adjacent comment lines should each express a concise point -- Avoid block comments and wrapped prose in ordinary implementation comments -- Explain intent or a non-obvious constraint rather than narrating the code -- No trailing punctuation on ordinary code comments -- Preserve explanations of guards and invariants; remove stale or redundant comments without losing necessary rationale -- API documentation, required license headers, and examples may use their conventional multiline formatting and punctuation -- Apply these standards to both production code and tests - ## Validation and reporting - Run relevant tests and required repository checks with the project's expected toolchain