Skip to content

fix: improve geography/geometry parser robustness#1843

Open
dhensby wants to merge 1 commit intotediousjs:masterfrom
dhensby:fix/udt-parser
Open

fix: improve geography/geometry parser robustness#1843
dhensby wants to merge 1 commit intotediousjs:masterfrom
dhensby:fix/udt-parser

Conversation

@dhensby
Copy link
Copy Markdown
Collaborator

@dhensby dhensby commented Apr 15, 2026

Summary

Fixes three bugs in the geography/geometry binary parser (lib/udt.js) that caused crashes on certain spatial data inputs.

Bugs Fixed

  1. H flag (IsLargerThanAHemisphere) collision with P flag — The H flag was checked against bit 3 (1 << 3), which is the same bit as the P (single point) flag. This meant v2 geography data with the H flag set would be incorrectly parsed as a single point. Fixed to use the correct bit 5 (1 << 5).

  2. No bounds checking on buffer reads — The parser performed no validation that sufficient data remained in the buffer before reading. Truncated or corrupt spatial data would produce cryptic RangeError: Attempt to access memory outside buffer bounds errors. Added an ensureBytes() helper that throws a clear 'Spatial data is truncated' error before every read section.

  3. Segment count check off-by-one — The check for whether segments existed used buffer.position < buffer.length, which would allow 1-3 trailing bytes to trigger a 4-byte read that overflows the buffer. Fixed to buffer.position + 4 <= buffer.length.

Tests Added

16 new unit tests covering:

  • Single point (P flag) for geography and geometry
  • Single line segment (L flag)
  • Z values, M values, and Z+M combined
  • v2 with circular arc segments
  • v2 with multiple segment types
  • v2 H flag (IsLargerThanAHemisphere) — validates the bit 5 fix
  • MultiPolygon and GeometryCollection (nested shapes)
  • Null geometry (SRID = -1)
  • Empty geometry (zero points/figures/shapes)
  • Truncated data: too-short header, truncated points, truncated figures, truncated Z data

Fixes #322

- Fix H flag check (IsLargerThanAHemisphere) using correct bit 5
  instead of bit 3 which collided with P flag
- Add bounds checking (ensureBytes) before all buffer reads to throw
  clear errors on truncated/corrupt spatial data instead of cryptic
  RangeErrors
- Fix segment count check to require 4 bytes available instead of 1

Fixes tediousjs#322

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

parseGeography fails on certain inputs

1 participant