fix(engine): bound sparse remap, scaled clone sources, path reads, export format, name lookups (#11181)

* fix(engine): bound sparse remap, scaled clone sources, path reads, export format, name lookups

* address review: read footage frames by Path so non-UTF-8 file names still import
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-11 16:30:07 -05:00
1 parent ab4ba9f37c
commit dd19c295d1
12 files changed
+120 -13

No files matched your search

+43
View File
@@ -15,6 +15,23 @@ pub(crate) fn filled<T: Clone>(len: usize, value: T, purpose: &str) -> Result<Ve
Ok(out)
}
/// Reads a regular file of at most `max` bytes. The opened handle must be a regular file (a
/// device such as `/dev/zero` never ends) and reading stops one byte past `max`, so neither a
/// special file nor one that grows after a size check can fill memory.
pub(crate) fn read_file_within(path: impl AsRef<std::path::Path>, max: u64) -> std::io::Result<Vec<u8>> {
use std::io::{Error, ErrorKind, Read};
let file = std::fs::File::open(path)?;
if !file.metadata()?.is_file() {
return Err(Error::new(ErrorKind::InvalidInput, "not a regular file"));
}
let mut out = Vec::new();
file.take(max.saturating_add(1)).read_to_end(&mut out)?;
if out.len() as u64 > max {
return Err(Error::new(ErrorKind::InvalidData, format!("file is larger than {max} bytes")));
}
Ok(out)
}
/// Reserve a vector for a known number of operation results.
pub(crate) fn capacity<T>(len: usize, purpose: &str) -> Result<Vec<T>> {
let bytes = len.checked_mul(std::mem::size_of::<T>()).ok_or_else(|| error(purpose, "requested size overflowed"))?;
@@ -131,4 +148,30 @@ mod tests {
assert!(filled::<u8>(4, 0, "counted").is_err_and(|e| e.to_string().contains("not enough memory for counted")));
assert!(filled::<u8>(4, 0, "done").is_ok());
}
#[test]
fn read_file_within_bounds_the_bytes_and_refuses_special_files() {
let path = std::env::temp_dir().join(format!("pc-read-within-{}", std::process::id()));
std::fs::write(&path, [7u8; 10]).unwrap();
let p = path.to_str().unwrap();
assert_eq!(read_file_within(p, 10).unwrap(), vec![7u8; 10]);
assert!(read_file_within(p, 9).is_err_and(|e| e.kind() == std::io::ErrorKind::InvalidData));
std::fs::remove_file(&path).unwrap();
// A directory (and on unix a device that never ends) is not a regular file.
assert!(read_file_within(std::env::temp_dir().to_str().unwrap(), 10).is_err());
#[cfg(unix)]
assert!(read_file_within("/dev/zero", 1 << 30).is_err_and(|e| e.kind() == std::io::ErrorKind::InvalidInput));
}
#[cfg(unix)]
#[test]
fn read_file_within_reads_a_path_that_is_not_utf8() {
use std::os::unix::ffi::OsStrExt;
let dir = std::env::temp_dir().join(format!("pc-read-within-nonutf8-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(std::ffi::OsStr::from_bytes(b"frame-\xff.png"));
std::fs::write(&path, [3u8; 4]).unwrap();
assert_eq!(read_file_within(&path, 10).unwrap(), vec![3u8; 4]);
std::fs::remove_dir_all(&dir).unwrap();
}
}
+1 -1
View File
@@ -245,7 +245,7 @@ pub fn folder_luts(_: &str) -> Vec<(String, String)> {
#[cfg(not(target_arch = "wasm32"))]
fn read_file(path: &str) -> Option<Vec<u8>> {
std::fs::read(path).ok()
crate::allocation::read_file_within(path, MAX_FOLDER_LUT_BYTES).ok()
}
#[cfg(target_arch = "wasm32")]
fn read_file(_: &str) -> Option<Vec<u8>> {
+3 -1
View File
@@ -47,7 +47,9 @@ fn named(c: Contour, name: &str) -> Contour {
/// `base`, or `base 2`, `base 3`… so a name is neither a standard contour's nor a user contour's
/// (a name alone selects a standard contour, so a user contour may not shadow one).
fn unique(lib: &[Contour], base: &str) -> String {
let taken = |n: &str| builtin_contour(n).is_some() || lib.iter().any(|c| name_of(c) == n);
// One pass over the library, not one per suffix tried.
let used: std::collections::HashSet<&str> = lib.iter().map(name_of).collect();
let taken = |n: &str| builtin_contour(n).is_some() || used.contains(n);
if !taken(base) {
return base.to_string();
}
@@ -44,6 +44,10 @@ pub struct LayerExportReport {
pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<LayerExportReport> {
let cmd = "file.export.layersToFiles";
let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
// The format becomes the file extension inside one filename component handed to `write`.
if format.is_empty() || !format.chars().all(|c| c.is_ascii_alphanumeric()) {
return Err(EngineError::BadParams { cmd: cmd.into(), msg: "`format` must be a file extension such as png".into() });
}
let trim = p.get("trim").and_then(Value::as_bool).unwrap_or(false);
let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true);
// Callers outside `Session::execute` (headless workspace exports) carry the session's gate
+11
View File
@@ -1785,6 +1785,17 @@ fn dds_params_are_none_until_one_is_given() {
assert_eq!(dds_param(&json!({"ddsCompression": "bc2"}), "file.saveAs").unwrap(), Some(DdsOptions { compression: DdsCompression::Bc2, mipmaps: false }));
}
/// The layer export's `format` is an extension, never a path: separators and `..` are refused.
#[test]
fn layer_export_format_cannot_carry_path_components() {
let dir = tmp("fmt-path");
let mut s = session(8, 8, 8);
for bad in ["png/../../x", "..\\x", "a/b", ""] {
let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "format": bad}));
assert!(matches!(r, Err(EngineError::BadParams { .. })), "{bad}: {r:?}");
}
}
/// A `tgaBits` other than 24 or 32 is a bad parameter, reported before anything is written.
#[test]
fn bad_targa_bits_are_refused_before_writing() {
+10 -1
View File
@@ -13,6 +13,9 @@ pub(super) fn clone_mapping(s: &mut Session, p: &Value, stroke: &Stroke, cmd: &s
crate::presets::clone_source::mapping(s, p, (f.x, f.y), cmd)
}
/// Most source pixels one clone sample may read (a 8192 x 8192 window); real strokes stay far below.
const MAX_CLONE_SOURCE_PIXELS: u64 = 1 << 26;
/// Source pixels for destination `rect`: a translated read, or a bilinear resample when the
/// clone source is scaled, rotated or flipped.
#[allow(clippy::too_many_arguments)]
@@ -41,7 +44,13 @@ pub(super) fn clone_sample(
r.rect = rect;
return Ok(r);
}
let src = read(map.source_rect(rect))?;
// A small W/H scale makes the source window enormous for a bounded destination: refuse it
// before the dense read allocates width x height x channels floats.
let sr = map.source_rect(rect);
if u64::from(sr.width()) * u64::from(sr.height()) > MAX_CLONE_SOURCE_PIXELS {
return Err(bad(cmd, "the scaled clone source covers too large an area; raise the clone source's W/H or use a smaller brush"));
}
let src = read(sr)?;
Ok(crate::presets::clone_source::resample(&src, rect, map, alpha_index(&surf.format())))
}
@@ -67,6 +67,22 @@ fn periodic_clone_projection_is_disjoint_and_matches_pixel_modulo() {
}
}
#[test]
fn a_hugely_scaled_clone_source_is_refused_before_the_dense_read() {
use super::clone::clone_sample;
use super::sampling::sample_layers;
use crate::presets::clone_source::Mapping;
let s = session(32, 24, 8, "rgb");
let d = s.active().unwrap();
let id = d.active_layer.unwrap();
let surf = d.doc.layer(id).unwrap().surface().unwrap();
let which = sample_layers(&json!({"sampleLayer": "current"}), "paint.cloneStamp").unwrap();
// 1000x: a 100x100 destination asks for a ~100000x100000 source window.
let map = Mapping { source: (0.0, 0.0), anchor: (0.0, 0.0), m: [1000.0, 0.0, 0.0, 1000.0] };
let r = clone_sample(&d.doc, Some(id), surf, which, Rect::new(0, 0, 100, 100), &map, false, "paint.cloneStamp");
assert!(r.is_err());
}
#[test]
fn periodic_clone_preview_interpolates_across_transformed_source_seam() {
use crate::presets::clone_source::Mapping;
+2 -2
View File
@@ -542,13 +542,13 @@ pub fn read_file(bytes: &[u8], format: Format, group: &str) -> std::result::Resu
AseEntry::Swatch(s) => loose.extend(conv(s)),
AseEntry::Group { name, swatches } => {
let items: Vec<Swatch> = swatches.iter().filter_map(&mut conv).collect();
let name = if name.trim().is_empty() { group.to_string() } else { clip(name.trim()) };
let name = if name.trim().is_empty() { clip(group) } else { clip(name.trim()) };
out.push(Group::new(&name, items));
}
}
}
if !loose.is_empty() || out.is_empty() {
out.insert(0, Group::new(group, loose));
out.insert(0, Group::new(&clip(group), loose));
}
if skipped > 0 {
warnings.push(format!("{skipped} swatches in an unknown colour model were skipped"));
+1 -1
View File
@@ -433,7 +433,7 @@ fn load_frames(path: &str, fmt: photocraft_color::PixelFormat, opts: &photocraft
Ok(())
};
for f in &files {
let bytes = std::fs::read(f).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?;
let bytes = crate::allocation::read_file_within(f, max_footage_bytes).map_err(|e| EngineError::Other(format!("read `{}`: {e}", f.display())))?;
let name = f.to_string_lossy();
// A GIF (a still one is its only frame) or an animated WebP brings every frame.
let animation = match photocraft_codecs::detect(&bytes) {
+5 -1
View File
@@ -567,9 +567,13 @@ pub(crate) fn map_document(p: &Value) -> Option<&Value> {
p.get("mapDocument").filter(|d| !d.is_null() && d.as_i64().is_none_or(|i| i >= 0))
}
/// Largest displacement-map file read (the same cap as imported presets).
const MAX_MAP_FILE_BYTES: u64 = 512 << 20;
/// Displace's map read from a file (flattened, or its `mapLayer`).
fn map_from_path(path: &str, layer: Option<u64>) -> Result<Option<algo::Image>> {
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?;
let bytes =
crate::allocation::read_file_within(path, MAX_MAP_FILE_BYTES).map_err(|e| EngineError::Other(format!("cannot read displacement map `{path}`: {e}")))?;
let imported = crate::file_cmds::import(path, &bytes).map_err(|e| EngineError::Other(format!("cannot open displacement map `{path}`: {e}")))?;
Ok(map_from_document(&imported, layer))
}
+10 -6
View File
@@ -537,12 +537,16 @@ pub fn remap_surface(s: &Surface, map: impl Fn(i32, i32) -> (i32, i32)) -> Surfa
let r = s.content_bounds();
let mut out = Surface::with_default(s.format(), &s.default_pixel());
let n = s.channels();
let raw = s.read_region(r);
let w = r.width() as usize;
for (i, px) in raw.chunks_exact(n).enumerate() {
let (x, y) = (r.x0 + (i % w) as i32, r.y0 + (i / w) as i32);
let (nx, ny) = map(x, y);
out.write_pixel(nx, ny, px);
// Tile by tile: unstored pixels read as the default `out` already has, and the content
// bounds of a sparse surface can span a grid of mostly nothing.
for tr in s.tiles().map(|(c, _)| c.rect().intersect(&r)).filter(|t| !t.is_empty()) {
let raw = s.read_region(tr);
let w = tr.width() as usize;
for (i, px) in raw.chunks_exact(n).enumerate() {
let (x, y) = (tr.x0 + (i % w) as i32, tr.y0 + (i / w) as i32);
let (nx, ny) = map(x, y);
out.write_pixel(nx, ny, px);
}
}
out
}
+14
View File
@@ -468,3 +468,17 @@ fn full_coverage_keeps_the_edit_over_huge_hdr_values() {
assert_eq!(out[..3], [a, a, a], "{a} over {o}");
}
}
/// Remapping walks the stored tiles, not the dense rectangle around them: two pixels a million
/// pixels apart (a ~4 TB rectangle) flip to their mirrored places.
#[test]
fn remap_surface_of_distant_tiles_does_not_densify_the_gap() {
let fmt = PixelFormat::new(ColorMode::Rgb, SampleType::U8, true);
let mut s = Surface::new(fmt);
let (a, b) = ([1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 1.0]);
s.write_pixel(-500_000, 3, &from_rgba(&fmt, a));
s.write_pixel(500_000, 9, &from_rgba(&fmt, b));
let out = remap_surface(&s, |x, y| (-x - 1, y));
assert_eq!(out.pixel(499_999, 3), from_rgba(&fmt, a));
assert_eq!(out.pixel(-500_001, 9), from_rgba(&fmt, b));
}