From c2e4b20cb096f230925a29579a758be147d5c5ba Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sat, 7 Nov 2026 01:19:34 +0200 Subject: [PATCH 1/7] Bound mesh vertex memory before collecting positions Loading a mesh should fail with a package error instead of allocating unbounded vertex buffers first, matching the existing triangle limit intent. Add a vertex-count bound checked while parsing OBJ and glTF positions so excess vertices are rejected before the full mesh is collected, with a regression test using an OBJ whose vertex count exceeds the bound but whose triangle count does not. Test: obj_with_excess_vertices_is_rejected failed before the change and passes after. --- crates/formats/src/mesh.rs | 53 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 2 deletions(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 9d712879..e7fbd829 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -13,6 +13,40 @@ pub const MESH_EXTENSIONS: &[&str] = &["obj", "glb", "gltf"]; /// Largest mesh accepted (triangles). const MAX_TRIANGLES: usize = 4_000_000; +/// Largest mesh accepted (vertices). +const MAX_VERTICES: usize = 4_000_000; + +fn check_vertex_bound(current: usize, added: usize) -> Result<()> { + if current.checked_add(added).map_or(true, |total| total > MAX_VERTICES) { + return Err(bad("the mesh is too large")); + } + Ok(()) +} + +fn is_obj_vertex_line(line: &[u8]) -> bool { + let mut bytes = line.iter().copied().skip_while(|b| matches!(b, b' ' | b'\t')); + match (bytes.next(), bytes.next()) { + (Some(b'v'), Some(b' ') | Some(b'\t') | Some(b'\r')) | (Some(b'v'), None) => true, + _ => false, + } +} + +/// Reject an OBJ whose raw vertex definitions exceed the bound before the +/// parser allocates storage for them. Unreferenced vertices never reach the +/// parsed mesh, so counting parsed vertices alone cannot bound this input. +fn check_obj_vertex_bound(bytes: &[u8]) -> Result<()> { + let mut count = 0usize; + for line in bytes.split(|b| *b == b'\n') { + if is_obj_vertex_line(line) { + count = count.saturating_add(1); + if count > MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + } + } + Ok(()) +} + fn bad(msg: impl Into) -> FormatError { FormatError::BadPackage(msg.into()) } @@ -81,6 +115,7 @@ pub fn load_mesh(name: &str, bytes: &[u8]) -> Result { } fn obj(bytes: &[u8]) -> Result { + check_obj_vertex_bound(bytes)?; let mut reader = std::io::BufReader::new(bytes); let opts = tobj::LoadOptions { triangulate: true, single_index: true, ..Default::default() }; let (models, _) = crate::guard( @@ -95,6 +130,7 @@ fn obj(bytes: &[u8]) -> Result { let base = positions.len() as u32; let mesh = &m.mesh; let n = mesh.positions.len() / 3; + check_vertex_bound(positions.len(), n)?; for i in 0..n { positions.push(Vec3::new(mesh.positions[i * 3], mesh.positions[i * 3 + 1], mesh.positions[i * 3 + 2])); if mesh.normals.len() == mesh.positions.len() { @@ -129,8 +165,10 @@ fn gltf(bytes: &[u8]) -> Result { let reader = prim.reader(|b| buffers.get(b.index()).map(|d| d.0.as_slice())); let Some(pos) = reader.read_positions() else { continue }; let base = positions.len() as u32; - let pos: Vec = pos.map(|p| m.transform_point3(Vec3::from(p))).collect(); - let n = pos.len(); + let pos_it = pos.map(|p| m.transform_point3(Vec3::from(p))); + let n = pos_it.len(); + check_vertex_bound(positions.len(), n)?; + let pos: Vec = pos_it.collect(); match reader.read_normals() { Some(ns) => { for q in ns { @@ -244,6 +282,17 @@ mod tests { assert_eq!(read, 6); } + #[test] + fn obj_with_excess_vertices_is_rejected() { + let mut obj = String::from("v 0 0 0\nv 1 0 0\nv 0 1 0\n"); + for _ in 0..4_000_000 { + obj.push_str("v 1 0 0\n"); + } + obj.push_str("f 1 2 3\n"); + + assert!(load_mesh("excess.obj", obj.as_bytes()).is_err()); + } + #[test] fn obj_non_finite_normals_are_rejected() { assert!(load_mesh("x.obj", b"v 0 0 0\nv 1 0 0\nv 0 1 0\nvn nan 0 1\nf 1//1 2//1 3//1\n").is_err()); From 4b6c02a83fdd8e2173f7d956af6e6437c9527b62 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sat, 7 Nov 2026 03:35:51 +0200 Subject: [PATCH 2/7] Address remaining review requests --- crates/formats/src/mesh.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index e7fbd829..b654899d 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -17,7 +17,7 @@ const MAX_TRIANGLES: usize = 4_000_000; const MAX_VERTICES: usize = 4_000_000; fn check_vertex_bound(current: usize, added: usize) -> Result<()> { - if current.checked_add(added).map_or(true, |total| total > MAX_VERTICES) { + if current.checked_add(added).is_none_or(|total| total > MAX_VERTICES) { return Err(bad("the mesh is too large")); } Ok(()) @@ -25,10 +25,7 @@ fn check_vertex_bound(current: usize, added: usize) -> Result<()> { fn is_obj_vertex_line(line: &[u8]) -> bool { let mut bytes = line.iter().copied().skip_while(|b| matches!(b, b' ' | b'\t')); - match (bytes.next(), bytes.next()) { - (Some(b'v'), Some(b' ') | Some(b'\t') | Some(b'\r')) | (Some(b'v'), None) => true, - _ => false, - } + matches!((bytes.next(), bytes.next()), (Some(b'v'), Some(b' ') | Some(b'\t') | Some(b'\r')) | (Some(b'v'), None)) } /// Reject an OBJ whose raw vertex definitions exceed the bound before the From 98af9a3dfd127aa56eac2f7dbb79cbaf442eeb58 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sat, 7 Nov 2026 04:02:49 +0200 Subject: [PATCH 3/7] Address review findings --- crates/formats/src/mesh.rs | 53 ++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index b654899d..40cb88d7 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -23,22 +23,49 @@ fn check_vertex_bound(current: usize, added: usize) -> Result<()> { Ok(()) } -fn is_obj_vertex_line(line: &[u8]) -> bool { - let mut bytes = line.iter().copied().skip_while(|b| matches!(b, b' ' | b'\t')); - matches!((bytes.next(), bytes.next()), (Some(b'v'), Some(b' ') | Some(b'\t') | Some(b'\r')) | (Some(b'v'), None)) -} - -/// Reject an OBJ whose raw vertex definitions exceed the bound before the -/// parser allocates storage for them. Unreferenced vertices never reach the -/// parsed mesh, so counting parsed vertices alone cannot bound this input. +/// Reject an OBJ whose raw attribute or face definitions exceed the bounds +/// before the parser allocates storage for them. Unreferenced definitions +/// never reach the parsed mesh, so counting parsed vertices alone cannot +/// bound this input. First tokens are matched with `split_whitespace`, the +/// same Unicode whitespace rules the OBJ parser uses. fn check_obj_vertex_bound(bytes: &[u8]) -> Result<()> { - let mut count = 0usize; + let mut vertices = 0usize; + let mut texcoords = 0usize; + let mut normals = 0usize; + let mut face_corners = 0usize; for line in bytes.split(|b| *b == b'\n') { - if is_obj_vertex_line(line) { - count = count.saturating_add(1); - if count > MAX_VERTICES { - return Err(bad("the mesh is too large")); + let Ok(line) = std::str::from_utf8(line) else { continue }; + let mut tokens = line.split_whitespace(); + match tokens.next() { + Some("v") => { + vertices = vertices.saturating_add(1); + if vertices > MAX_VERTICES { + return Err(bad("the mesh is too large")); + } } + Some("vt") => { + texcoords = texcoords.saturating_add(1); + if texcoords > MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + } + Some("vn") => { + normals = normals.saturating_add(1); + if normals > MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + } + Some("f") => { + // A triangulated face with k corners yields k - 2 triangles, so + // a mesh within the triangle limit has at most 3 * MAX_TRIANGLES + // corners. Bounding corners also bounds the vertices the parser + // expands from distinct face index combinations. + face_corners = face_corners.saturating_add(tokens.count()); + if face_corners > 3 * MAX_TRIANGLES { + return Err(bad("the mesh is too large")); + } + } + _ => {} } } Ok(()) From 611e2c690b9bb6fe28c4d42eea1b603b2e2c7555 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sat, 7 Nov 2026 08:38:39 +0200 Subject: [PATCH 4/7] Address review for pull request 142 --- crates/formats/src/mesh.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 40cb88d7..7dd88607 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -14,7 +14,7 @@ pub const MESH_EXTENSIONS: &[&str] = &["obj", "glb", "gltf"]; const MAX_TRIANGLES: usize = 4_000_000; /// Largest mesh accepted (vertices). -const MAX_VERTICES: usize = 4_000_000; +const MAX_VERTICES: usize = 3 * MAX_TRIANGLES; fn check_vertex_bound(current: usize, added: usize) -> Result<()> { if current.checked_add(added).is_none_or(|total| total > MAX_VERTICES) { @@ -379,4 +379,10 @@ mod tests { assert!(load_mesh("x.fbx", b"").is_err()); assert!(load_mesh("x.obj", b"v 0 0 0\nf 1 2 3\n").is_err()); } + + #[test] + fn vertex_bound_allows_three_vertices_per_triangle() { + assert!(check_vertex_bound(0, 3 * MAX_TRIANGLES).is_ok()); + assert!(check_vertex_bound(0, 3 * MAX_TRIANGLES + 1).is_err()); + } } From d7878b30ded377976225d0ab9d1dcc233fdbeae8 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sat, 7 Nov 2026 10:49:50 +0200 Subject: [PATCH 5/7] Repair review branch integration --- crates/formats/src/mesh.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 7dd88607..85bff036 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -309,7 +309,7 @@ mod tests { #[test] fn obj_with_excess_vertices_is_rejected() { let mut obj = String::from("v 0 0 0\nv 1 0 0\nv 0 1 0\n"); - for _ in 0..4_000_000 { + for _ in 0..3 * MAX_TRIANGLES { obj.push_str("v 1 0 0\n"); } obj.push_str("f 1 2 3\n"); From 2a7ce968a6fac84c1c3288c61dfa7c7e66b41475 Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:17:08 +0200 Subject: [PATCH 6/7] Address remaining review requests --- crates/formats/src/mesh.rs | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index 85bff036..ae11e2e4 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -314,7 +314,39 @@ mod tests { } obj.push_str("f 1 2 3\n"); - assert!(load_mesh("excess.obj", obj.as_bytes()).is_err()); + let e = load_mesh("excess.obj", obj.as_bytes()).unwrap_err(); + assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}"); + } + + #[test] + fn gltf_with_excess_vertices_is_rejected() { + use base64::Engine as _; + // One position accessor of 100_000 vertices, referenced by 121 + // primitives: the cumulative count exceeds MAX_VERTICES on the + // last primitive, while the single indexed triangle per primitive + // stays far below the triangle limit. + const COUNT: usize = 100_000; + let mut buf = vec![0u8; COUNT * 12]; + // Give the referenced triangle non-degenerate positions. + for (i, v) in [[0.0f32, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]].iter().enumerate() { + buf[i * 12..i * 12 + 12].copy_from_slice(&v.iter().flat_map(|f| f.to_le_bytes()).collect::>()); + } + buf.extend([0u16, 1, 2].iter().flat_map(|i| i.to_le_bytes())); + let b64 = base64::engine::general_purpose::STANDARD.encode(&buf); + let prim = r#"{"attributes":{"POSITION":0},"indices":1}"#; + let prims = (0..121).map(|_| prim).collect::>().join(","); + let gltf = format!( + r#"{{"asset":{{"version":"2.0"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0}}], +"meshes":[{{"primitives":[{prims}]}}], +"accessors":[{{"bufferView":0,"componentType":5126,"count":{COUNT},"type":"VEC3","min":[0.0,0.0,0.0],"max":[1.0,1.0,0.0]}},{{"bufferView":1,"componentType":5123,"count":3,"type":"SCALAR"}}], +"bufferViews":[{{"buffer":0,"byteOffset":0,"byteLength":{}}},{{"buffer":0,"byteOffset":{},"byteLength":6}}], +"buffers":[{{"byteLength":{},"uri":"data:application/octet-stream;base64,{b64}"}}]}}"#, + COUNT * 12, + COUNT * 12, + buf.len() + ); + let e = load_mesh("excess.gltf", gltf.as_bytes()).unwrap_err(); + assert!(matches!(&e, FormatError::BadPackage(msg) if msg == "the mesh is too large"), "{e:?}"); } #[test] From af2893e4ed0e2ad34b0f19671e0d41206cbba55d Mon Sep 17 00:00:00 2001 From: eliets2 <287273517+eliets2@users.noreply.github.com> Date: Sat, 7 Nov 2026 11:36:01 +0200 Subject: [PATCH 7/7] Address review findings --- crates/formats/src/mesh.rs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/mesh.rs b/crates/formats/src/mesh.rs index ae11e2e4..539b3952 100644 --- a/crates/formats/src/mesh.rs +++ b/crates/formats/src/mesh.rs @@ -55,11 +55,12 @@ fn check_obj_vertex_bound(bytes: &[u8]) -> Result<()> { return Err(bad("the mesh is too large")); } } - Some("f") => { + Some("f") | Some("l") => { // A triangulated face with k corners yields k - 2 triangles, so // a mesh within the triangle limit has at most 3 * MAX_TRIANGLES - // corners. Bounding corners also bounds the vertices the parser - // expands from distinct face index combinations. + // corners. Lines are expanded by the parser like faces, so + // bounding their corners too bounds the vertices the parser + // expands from distinct index combinations. face_corners = face_corners.saturating_add(tokens.count()); if face_corners > 3 * MAX_TRIANGLES { return Err(bad("the mesh is too large")); @@ -196,6 +197,9 @@ fn gltf(bytes: &[u8]) -> Result { match reader.read_normals() { Some(ns) => { for q in ns { + if normals.len() >= MAX_VERTICES { + return Err(bad("the mesh is too large")); + } let v = m.transform_vector3(Vec3::from(q)); if !v.is_finite() { return Err(bad("the mesh has non-finite (NaN or infinite) normals")); @@ -206,7 +210,14 @@ fn gltf(bytes: &[u8]) -> Result { None => all_normals = false, } match reader.read_tex_coords(0) { - Some(t) => uvs.extend(t.into_f32().map(Vec2::from)), + Some(t) => { + for uv in t.into_f32() { + if uvs.len() >= MAX_VERTICES { + return Err(bad("the mesh is too large")); + } + uvs.push(Vec2::from(uv)); + } + } None => uvs.extend(std::iter::repeat_n(Vec2::ZERO, n)), } match reader.read_indices() {