diff --git a/Cargo.lock b/Cargo.lock index 9bfcb88ccd..9c867c2df3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5228,6 +5228,7 @@ dependencies = [ "calamine", "csv", "encoding_rs", + "flatbuffers 24.12.23", "flate2", "flatgeobuf", "geo", diff --git a/crates/data/Cargo.toml b/crates/data/Cargo.toml index cb7789aeaf..bfadf8f7cb 100644 --- a/crates/data/Cargo.toml +++ b/crates/data/Cargo.toml @@ -103,6 +103,8 @@ arrow-schema = { workspace = true } proptest = { workspace = true } # Writing LERC blobs with masks, band sets and padded strips that GDAL never writes. lerc-writer = "0.5" +# Building FlatGeobuf geometries no writer makes (the version flatgeobuf uses). +flatbuffers = "24.12" [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] # Writing Zstandard-compressed GeoTIFFs. diff --git a/crates/data/src/source/fgb.rs b/crates/data/src/source/fgb.rs index 1e11f15ed9..244ea5b360 100644 --- a/crates/data/src/source/fgb.rs +++ b/crates/data/src/source/fgb.rs @@ -313,6 +313,7 @@ impl FgbSource { crate::progress::begin(self.info.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(0)); let mut states = vec![0u8; self.info.fields.len()]; let mut iter = open_reader(reader)?.select_all().map_err(err)?; + let kind = iter.geometry_type(); while let Some(feature) = iter.next().map_err(err)? { crate::progress::step(1)?; let mut props = Props { @@ -322,9 +323,14 @@ impl FgbSource { unread_dates: Vec::new(), rounded_dates: Vec::new(), }; - // Reads skip a feature with unreadable properties and report it in Batch::skipped. - // Such a feature must not influence the inferred date type either. - if !properties_fit(feature, &self.kinds) || feature.process_properties(&mut props).is_err() { + // Reads skip a feature with unreadable properties or geometry and report it in + // Batch::skipped. Such a feature must not influence the inferred date type either: its + // geometry is converted as a read converts it, which costs this pass one conversion of + // each geometry. A cheaper check would have to copy what the conversion refuses. + if geometry_of(feature, kind).is_none() + || !properties_fit(feature, &self.kinds) + || feature.process_properties(&mut props).is_err() + { continue; } for &k in columns { @@ -394,6 +400,7 @@ impl FgbSource { if late { crate::progress::begin(usize::try_from(matched).unwrap_or(0)); } + let kind = iter.geometry_type(); while let Some(f) = iter.next().map_err(err)? { if late { crate::progress::step(1)?; @@ -404,7 +411,7 @@ impl FgbSource { if !late && !sample.wants() { continue; } - let geometry = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, req)); + let geometry = geometry_of(f, kind).and_then(|g| self.reproject.place(g, req)); let Some(geometry) = geometry else { out.skipped += 1; continue; @@ -466,12 +473,12 @@ impl FgbSource { let mut out = Batch { complete: true, ..Batch::default() }; let mut n = 0u64; crate::progress::begin(iter.features_count().unwrap_or(0)); + let kind = iter.geometry_type(); while let Some(f) = iter.next().map_err(err)? { crate::progress::step(1)?; n += 1; let id = numbers.as_ref().and_then(|v| v.get(usize::try_from(n - 1).unwrap_or(usize::MAX)).copied()).unwrap_or(n); - let geometry = - f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, &req)); + let geometry = geometry_of(f, kind).and_then(|g| self.reproject.place(g, &req)); let Some(geometry) = geometry else { out.skipped += 1; continue; @@ -505,9 +512,10 @@ impl FgbSource { fn peek_kind(&self) -> GeometryType { let first = |r: Box| -> Option { let mut iter = open_reader(r).ok()?.select_all().ok()?; + let kind = iter.geometry_type(); for _ in 0..16 { let f = iter.next().ok()??; - if let Some(g) = f.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode) { + if let Some(g) = geometry_of(f, kind) { return Some(g.kind()); } } @@ -774,6 +782,7 @@ impl FgbSource { if late { crate::progress::begin(n); } + let kind = iter.geometry_type(); while let Some(feat) = iter.next().map_err(err)? { if late { crate::progress::step(1)?; @@ -784,8 +793,7 @@ impl FgbSource { continue; } let id = hits.items.get(this).map(|(_, i)| i + 1).unwrap_or(this as u64 + 1); - let geometry = - feat.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode).and_then(|g| self.reproject.place(g, req)); + let geometry = geometry_of(feat, kind).and_then(|g| self.reproject.place(g, req)); let Some(geometry) = geometry else { out.skipped += 1; continue; @@ -922,6 +930,80 @@ fn field_type(t: ColumnType) -> Option { }) } +/// A feature's geometry as a read takes it, or `None` when it can't be read: also when it doesn't +/// hold what the reader indexes ([`geometry_fits`]). `kind` is the file's geometry type, from its +/// header. Reads and the date pass all convert through this, so they skip the same features. +fn geometry_of(feature: &flatgeobuf::FgbFeature, kind: GeometryKind) -> Option { + if !geometry_fits(feature, kind) { + return None; + } + feature.to_wkb(CoordDimensions::xy()).ok().as_deref().and_then(wkb::decode) +} + +type GeometryKind = flatgeobuf::GeometryType; + +/// Whether a feature's geometry holds what flatgeobuf 6.0.1 reads from it, in it and in each of its +/// parts: an even number of `xy` values, ring or line ends that never go back and stay within them, +/// and a coordinate where a point is read. The reader indexes `xy` by the ends the file gives, and +/// reads a point's first coordinate whatever `xy` holds; past the end, or on an end before the one +/// before it, it panics, which the browser can't catch. A feature that fails this is skipped as +/// unreadable, as one whose geometry the reader refuses. Found by fuzzing `read_layers` (#3006). +fn geometry_fits(feature: &flatgeobuf::FgbFeature, kind: GeometryKind) -> bool { + // As the reader does: the file's type, or the feature's own when the file says Unknown. + feature.fbs_feature().geometry().is_none_or(|g| { + let kind = if kind == GeometryKind::Unknown { g.type_() } else { kind }; + geometry_part_fits(&g, kind, 0) + }) +} + +/// [`geometry_fits`] for `g`, read as `kind`. +fn geometry_part_fits(g: &flatgeobuf::Geometry<'_>, kind: GeometryKind, depth: u32) -> bool { + use GeometryKind as K; + // Parts within parts are a collection's; a file nesting them deeper is refused, not followed. + if depth > 32 { + return false; + } + // These are read from their parts alone: their own xy and ends are never looked at. + let from_parts = matches!( + kind, + K::MultiPolygon + | K::PolyhedralSurface + | K::GeometryCollection + | K::MultiCurve + | K::MultiSurface + | K::CompoundCurve + | K::CurvePolygon + ); + if !from_parts { + let values = g.xy().map_or(0, |xy| xy.len()); + // A point is read from its own first two values, whatever follows; the rest by pairs. + if (kind != K::Point && !values.is_multiple_of(2)) || (kind == K::Point && values < 2) { + return false; + } + // Ends are read only for these kinds, and only when there are two or more of them. + let reads_ends = matches!(kind, K::Polygon | K::MultiLineString | K::Triangle | K::TIN); + if let Some(ends) = g.ends().filter(|ends| reads_ends && ends.len() > 1) { + let mut last = 0usize; + for end in ends.iter() { + let end = usize::try_from(end).unwrap_or(usize::MAX); + if end < last || end.saturating_mul(2) > values { + return false; + } + last = end; + } + } + // Read from its own xy alone: parts it carries are never looked at. + return true; + } + // A multi-polygon's parts are read as polygons whatever they say; the rest by their own type. + g.parts().is_none_or(|parts| { + parts.iter().all(|part| { + let read_as = if matches!(kind, K::MultiPolygon | K::PolyhedralSurface) { K::Polygon } else { part.type_() }; + geometry_part_fits(&part, read_as, depth + 1) + }) + }) +} + /// Whether a feature's property bytes hold what they say, laid out as FlatGeobuf has them: each a /// column index (`u16`), then the value, its width fixed by the column's type, or a `u32` length /// and that many bytes for text, JSON, date-times and binary. flatgeobuf 6.0.1 slices them as the @@ -1184,6 +1266,164 @@ fn write_run( Ok(Some(left_out)) } +#[cfg(test)] +mod geometry_fits_tests { + use super::{GeometryKind, geometry_part_fits}; + use flatbuffers::FlatBufferBuilder; + use flatgeobuf::{Geometry, GeometryArgs}; + + /// `g`, built in a buffer of its own, as the reader would see it. + fn fits(build: impl FnOnce(&mut FlatBufferBuilder<'static>) -> flatbuffers::WIPOffset>, kind: GeometryKind) -> bool { + let mut fbb = FlatBufferBuilder::new(); + let root = build(&mut fbb); + fbb.finish(root, None); + let g = flatbuffers::root::(fbb.finished_data()).unwrap(); + geometry_part_fits(&g, kind, 0) + } + + fn square<'a>(fbb: &mut FlatBufferBuilder<'a>) -> flatbuffers::WIPOffset> { + let xy = fbb.create_vector(&[0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0]); + Geometry::create(fbb, &GeometryArgs { xy: Some(xy), type_: GeometryKind::Polygon, ..Default::default() }) + } + + /// A multi-polygon whose own `xy` is there but empty reads from its parts, so it fits; a point + /// with an empty or absent `xy` doesn't, nor a collection's point part (#3006). + #[test] + fn a_point_is_held_to_its_coordinate_and_a_multi_part_geometry_is_not() { + let multi = |kind| { + fits( + |fbb| { + let part = square(fbb); + let parts = fbb.create_vector(&[part]); + let xy = fbb.create_vector::(&[]); + Geometry::create(fbb, &GeometryArgs { xy: Some(xy), parts: Some(parts), type_: kind, ..Default::default() }) + }, + kind, + ) + }; + assert!(multi(GeometryKind::MultiPolygon)); + assert!(multi(GeometryKind::GeometryCollection), "its polygon part fits"); + // Read as a point, as a file whose header says Point reads it: refused. + assert!(!multi(GeometryKind::Point)); + let empty_point = |fbb: &mut FlatBufferBuilder<'static>| { + let xy = fbb.create_vector::(&[]); + Geometry::create(fbb, &GeometryArgs { xy: Some(xy), type_: GeometryKind::Point, ..Default::default() }) + }; + assert!(!fits(empty_point, GeometryKind::Point)); + let no_xy = |fbb: &mut FlatBufferBuilder<'static>| { + Geometry::create(fbb, &GeometryArgs { type_: GeometryKind::Point, ..Default::default() }) + }; + assert!(!fits(no_xy, GeometryKind::Point), "a point with no xy at all is refused too"); + let collection = fits( + |fbb| { + let point = empty_point(fbb); + let parts = fbb.create_vector(&[point]); + Geometry::create(fbb, &GeometryArgs { parts: Some(parts), type_: GeometryKind::GeometryCollection, ..Default::default() }) + }, + GeometryKind::GeometryCollection, + ); + assert!(!collection, "a collection reads its point part as a point"); + assert!(fits(square, GeometryKind::Polygon)); + // A multi-polygon's own xy, odd or not, is never read; a polygon's is, parts or not. + let odd_own = |kind| { + fits( + |fbb| { + let part = square(fbb); + let parts = fbb.create_vector(&[part]); + let xy = fbb.create_vector(&[1.0, 2.0, 3.0]); + Geometry::create(fbb, &GeometryArgs { xy: Some(xy), parts: Some(parts), type_: kind, ..Default::default() }) + }, + kind, + ) + }; + assert!(odd_own(GeometryKind::MultiPolygon)); + assert!(!odd_own(GeometryKind::Polygon)); + // A polygon's parts are never read, so a broken one doesn't refuse it. + let polygon_with_broken_part = fits( + |fbb| { + let xy = fbb.create_vector(&[1.0, 2.0, 3.0]); + let part = Geometry::create(fbb, &GeometryArgs { xy: Some(xy), type_: GeometryKind::Point, ..Default::default() }); + let parts = fbb.create_vector(&[part]); + let xy = fbb.create_vector(&[0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0]); + Geometry::create( + fbb, + &GeometryArgs { xy: Some(xy), parts: Some(parts), type_: GeometryKind::Polygon, ..Default::default() }, + ) + }, + GeometryKind::Polygon, + ); + assert!(polygon_with_broken_part); + // Stray ends are refused only where the reader follows them: on a polygon, two or more. + let with_ends = |kind, ends: &'static [u32]| { + fits( + |fbb| { + let xy = fbb.create_vector(&[0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0]); + let ends = fbb.create_vector(ends); + Geometry::create(fbb, &GeometryArgs { xy: Some(xy), ends: Some(ends), type_: kind, ..Default::default() }) + }, + kind, + ) + }; + assert!(with_ends(GeometryKind::LineString, &[9, 2])); + assert!(with_ends(GeometryKind::MultiPoint, &[9, 2])); + assert!(with_ends(GeometryKind::Polygon, &[9]), "one end is never read"); + assert!(!with_ends(GeometryKind::Polygon, &[2, 9])); + assert!(!with_ends(GeometryKind::MultiLineString, &[3, 2])); + assert!(with_ends(GeometryKind::Polygon, &[2, 4])); + // A point reads its first two values alone, so a third doesn't refuse it. + let three = |fbb: &mut FlatBufferBuilder<'static>| { + let xy = fbb.create_vector(&[1.0, 2.0, 3.0]); + Geometry::create(fbb, &GeometryArgs { xy: Some(xy), type_: GeometryKind::Point, ..Default::default() }) + }; + assert!(fits(three, GeometryKind::Point)); + assert!(!fits(three, GeometryKind::LineString), "a line reads by pairs"); + // A multi-polygon's part is read as a polygon, so bad ring ends in it are refused. + let multi_with_ends = |ends: &'static [u32]| { + fits( + |fbb| { + let first = square(fbb); + let xy = fbb.create_vector(&[0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0]); + let ends = fbb.create_vector(ends); + let second = Geometry::create( + fbb, + &GeometryArgs { xy: Some(xy), ends: Some(ends), type_: GeometryKind::Polygon, ..Default::default() }, + ); + let parts = fbb.create_vector(&[first, second]); + Geometry::create(fbb, &GeometryArgs { parts: Some(parts), type_: GeometryKind::MultiPolygon, ..Default::default() }) + }, + GeometryKind::MultiPolygon, + ) + }; + assert!(!multi_with_ends(&[2, 9])); + assert!(multi_with_ends(&[2, 4])); + } + + /// Collections nested past 32 levels are refused before the reader recurses into them; 32 are + /// followed (#3006). + #[test] + fn collections_nest_no_deeper_than_the_limit() { + let nested = |levels: usize| { + fits( + |fbb| { + let xy = fbb.create_vector(&[1.0, 2.0]); + let mut g = Geometry::create(fbb, &GeometryArgs { xy: Some(xy), type_: GeometryKind::Point, ..Default::default() }); + for _ in 0..levels { + let parts = fbb.create_vector(&[g]); + g = Geometry::create( + fbb, + &GeometryArgs { parts: Some(parts), type_: GeometryKind::GeometryCollection, ..Default::default() }, + ); + } + g + }, + GeometryKind::GeometryCollection, + ) + }; + assert!(nested(32)); + assert!(!nested(33)); + } +} + #[cfg(test)] mod write_tests { use super::*; diff --git a/crates/data/src/source/fgb/checked.rs b/crates/data/src/source/fgb/checked.rs index 39ccaa2701..2e9041e631 100644 --- a/crates/data/src/source/fgb/checked.rs +++ b/crates/data/src/source/fgb/checked.rs @@ -70,6 +70,11 @@ impl Features { self.inner.features_count() } + /// The file's geometry type, which the reader reads a feature as unless it is Unknown. + pub(super) fn geometry_type(&self) -> flatgeobuf::GeometryType { + self.inner.header().geometry_type() + } + /// Checks failures even when selection or advance swallowed them as end-of-file. pub(super) fn next(&mut self) -> flatgeobuf::Result> { if let Some(e) = self.failure.borrow_mut().take() { diff --git a/crates/data/src/source/tests.rs b/crates/data/src/source/tests.rs index 7fb0d4625f..9214ef9c2e 100644 --- a/crates/data/src/source/tests.rs +++ b/crates/data/src/source/tests.rs @@ -4631,6 +4631,98 @@ fn flatgeobuf_property_lengths_past_the_end_skip_the_feature() { assert_eq!((rows, streamed.skipped), (2, 1)); } +/// A polygon's ring ends that run past its coordinates, or go back, skip that feature as +/// unreadable, whole and streamed, instead of panicking in the reader; the features around it are +/// read. Found by fuzzing `read_layers` (#3006). +#[test] +fn flatgeobuf_ring_ends_past_the_coordinates_skip_the_feature() { + let square = |x: f64, size: f64| { + vec![Coord::new(x, 0.0), Coord::new(x + size, 0.0), Coord::new(x + size, size), Coord::new(x, size), Coord::new(x, 0.0)] + }; + let mut ds = Dataset::new("parcels", GeometryType::Polygon, vec![Field::new("n", FieldType::Integer)]); + ds.push(Some(Geometry::Polygon(vec![vec![square(0.0, 1.0)]])), vec![Value::Int(1)]); + // Two rings: its ends are written as [5, 10]. + ds.push(Some(Geometry::Polygon(vec![vec![square(10.0, 4.0), square(11.0, 1.0)]])), vec![Value::Int(2)]); + ds.push(Some(Geometry::Polygon(vec![vec![square(20.0, 1.0)]])), vec![Value::Int(3)]); + let written = fgb::write(&ds).unwrap(); + // The file as written reads whole: the check refuses no ring that fits. + let clean = open_bytes("parcels.fgb", written.clone(), None).unwrap().read(&Request::all()).unwrap(); + assert_eq!((clean.features.len(), clean.skipped), (3, 0)); + let at = written.windows(12).position(|w| w == [2, 0, 0, 0, 5, 0, 0, 0, 10, 0, 0, 0]).unwrap(); + for (first, second) in [(5u32, 11u32), (5, 0x7fff_ffff), (7, 6)] { + let mut bytes = written.clone(); + bytes[at + 4..at + 8].copy_from_slice(&first.to_le_bytes()); + bytes[at + 8..at + 12].copy_from_slice(&second.to_le_bytes()); + let src = open_bytes("parcels.fgb", bytes, None).unwrap(); + let batch = src.read(&Request::all()).unwrap(); + assert_eq!(batch.skipped, 1, "ends {first}, {second}"); + let mut kept: Vec = batch.features.iter().map(|f| f.attrs[0].to_string()).collect(); + kept.sort(); + assert_eq!(kept, ["1", "3"], "ends {first}, {second}"); + let mut rows = 0; + let streamed = src + .visit_chunks(None, 256, &mut |chunk| { + rows += chunk.len(); + Ok(()) + }) + .unwrap(); + assert_eq!((rows, streamed.skipped), (2, 1), "ends {first}, {second}"); + } +} + +/// A point whose coordinates are empty is skipped as unreadable, whole and streamed, instead of +/// panicking in the reader, which reads a point's first coordinate whatever its length (#3006). +#[test] +fn flatgeobuf_a_point_without_its_coordinate_skips_the_feature() { + let mut ds = Dataset::new("places", GeometryType::Point, vec![]); + for x in [1.0, 1234.5, 3.0] { + ds.push(Some(Geometry::Point(Coord::new(x, 0.0))), vec![]); + } + let written = fgb::write(&ds).unwrap(); + let clean = open_bytes("places.fgb", written.clone(), None).unwrap().read(&Request::all()).unwrap(); + assert_eq!((clean.features.len(), clean.skipped), (3, 0)); + // The middle point's xy vector (its length, 2, then x) made empty. + let mut needle = 2u32.to_le_bytes().to_vec(); + needle.extend_from_slice(&1234.5f64.to_le_bytes()); + let mut bytes = written; + let at = bytes.windows(needle.len()).position(|w| w == needle.as_slice()).unwrap(); + bytes[at..at + 4].copy_from_slice(&0u32.to_le_bytes()); + let src = open_bytes("places.fgb", bytes, None).unwrap(); + let batch = src.read(&Request::all()).unwrap(); + assert_eq!((batch.features.len(), batch.skipped), (2, 1)); + let mut rows = 0; + let streamed = src + .visit_chunks(None, 256, &mut |chunk| { + rows += chunk.len(); + Ok(()) + }) + .unwrap(); + assert_eq!((rows, streamed.skipped), (2, 1)); +} + +/// A feature skipped for its geometry doesn't decide a column's date type either: its time of day +/// would otherwise make an all-date column text (#3006). +#[test] +fn flatgeobuf_dates_skip_features_with_unreadable_geometry() { + let mut ds = Dataset::new("dates", GeometryType::Point, vec![Field::new("day", FieldType::Date)]); + ds.push(Some(Geometry::Point(Coord::new(1.0, 0.0))), vec![Value::parse("2001-01-01", FieldType::Date)]); + ds.push(Some(Geometry::Point(Coord::new(1234.5, 0.0))), vec![Value::parse("2002-02-02", FieldType::Date)]); + let mut bytes = fgb::write(&ds).unwrap(); + // Its day made a time of day, the same length, which would make the column text. + let day = bytes.windows(10).position(|w| w == b"2002-02-02").unwrap(); + bytes[day..day + 10].copy_from_slice(b"10:30:00.5"); + // The second point's xy vector (its length, 2, then x) made empty. + let mut needle = 2u32.to_le_bytes().to_vec(); + needle.extend_from_slice(&1234.5f64.to_le_bytes()); + let at = bytes.windows(needle.len()).position(|w| w == needle.as_slice()).unwrap(); + bytes[at..at + 4].copy_from_slice(&0u32.to_le_bytes()); + let source = open_bytes("dates.fgb", bytes, None).unwrap(); + assert_eq!(source.info().fields[0].ty, FieldType::Date); + let read = source.read(&Request::all()).unwrap(); + assert_eq!((read.features.len(), read.skipped), (1, 1)); + assert_eq!(read.features[0].attrs[0].to_string(), "2001-01-01"); +} + /// A readable size prefix can contain invalid UTF-8 properties. Classification ignores /// that row just as whole and streamed reads do, and the read reports the skipped feature. #[test]