Skip to content

Harden the public API against trapping and invalid input - #117

Merged
trasch merged 3 commits into
mainfrom
fix/api-hardening
Nov 2, 2026
Merged

trasch merged 3 commits into
mainfrom
fix/api-hardening

Conversation

@trasch

@trasch trasch commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Several public APIs trapped (crashed) on bad input, one silently truncated data, and BoundingBox(parsing:) accepted malformed strings. This PR makes the failure modes explicit.

Trapping accessors

map.layerVisible(Int.max)        // Fatal error: Not enough bits to represent the passed value
map.layerSRS(Int(Int32.max) + 1) // same

Four accessors used a plain Int32(index) while their neighbours used Int32(clamping:). They now share a layerIndex(_:) helper and return nil as documented:

Accessor Before After
layerVisible(_:) trap nil
layerSRS(_:) trap nil
layerQueryable(_:) trap nil
layerVisible(_:atScaleDenominator:) trap nil

Metatile.init, TileSequence.init and MetatileSequence.init used precondition for user-facing validation. They now throw MapnikError.invalidInput, so a block or sequence built from external data (a tile list from a database, a zoom range from a URL) reports an error instead of crashing:

try Metatile(origin: tile, metaSize: 32)          // throws, was a trap
try TileSequence(bounds: b, zoomRange: 0 ... 31)  // throws, was a trap

Silent truncation

srs and layerSRS used a fixed 256-byte buffer and ignored the shim's reported length:

long SRS: requested 302 chars, got 255 chars, equal=false

Long PROJ.4 strings (+towgs84, +nadgrids, +comment) exceed 255 characters, and a round trip through setSRS → srs corrupted them. Both now grow the buffer once.

Validation

ImageFormat's options were only checked deep inside mapnik, after the map had already been resized:

png(colors: 0)   -> Rendering failed: invalid color parameter: 0
jpeg(quality: 500) -> Rendering failed: invalid jpeg quality: '500'

They now throw MapnikError.invalidInput up front (png colors 1...256, jpeg/webp quality 0...100). setBufferSize clamps negative values, matching RenderOptions.validate.

Errors

  • MapnikError is Equatable and LocalizedError, and gained serializationFailed.
  • MapnikPoolError.exhausted carries the pool limit and is Equatable, so tests can assert the specific error and logs have context.

BoundingBox parsing

BoundingBox(parsing: "1,2,foo,3,4")  // was: (1,2,3,4) with "foo" silently dropped

compactMap dropped unparseable fields, shifting the rest into the wrong slots. Parsing is now positional, rejects non-finite values, and requires exactly four fields.

Testing

New APIHardeningTests covers huge layer indices, long SRS round trips, negative bufferSize, ImageFormat validation, error equality, Metatile/sequence validation instead of trapping, and malformed bounding-box strings. 88 tests pass across the affected suites.

Breaking changes

  • Metatile.init, TileSequence.init and MetatileSequence.init are now throws.
  • MapnikPoolError.exhausted carries limit:.
  • MapnikError gained a case (exhaustive switches need updating).
  • BoundingBox(parsing:) rejects strings it previously accepted.
  • ImageFormat validation rejects out-of-range options earlier.

Closes #7
Closes #14
Closes #29
Closes #43
Closes #65
Closes #66
Closes #83
Closes #85
Closes #92
Closes #94
Closes #103

Trapping accessors
- layerVisible(_:), layerSRS(_:), layerQueryable(_:) and
  layerVisible(_:atScaleDenominator:) used a plain Int32(index), which
  traps for indices outside Int32 range. They now return nil as
  documented. layerEnvelope, zoomToLayer and setLayerVisible already
  clamped; the four accessors now share the same helper.
- Metatile.init, TileSequence.init and MetatileSequence.init threw away
  invalid input via precondition. They are now throwing and report
  MapnikError.invalidInput, so callers that build blocks or sequences
  from external data get an error instead of a crash. MetatileSequence
  uses an internal non-validating initializer for its own tile lists.
- MetatileOptions.metatileSize/validate no longer trap on a huge
  width x scale.

Silent truncation
- srs and layerSRS grew the buffer instead of returning a silently
  truncated projection string. Long PROJ.4 strings (+towgs84,
  +nadgrids, +comment) exceed 255 characters easily.

Validation
- ImageFormat validates its options (png colors 1...256, jpeg/webp
  quality 0...100), so a bad value surfaces as MapnikError.invalidInput
  instead of a renderingFailed from deep inside mapnik after the map was
  already resized.
- setBufferSize clamps negative values, matching RenderOptions.validate.

Errors
- MapnikError is Equatable and LocalizedError, and gained a
  serializationFailed case.
- MapnikPoolError.exhausted carries the pool limit and is Equatable, so
  tests and logs have context.

BoundingBox parsing
- BoundingBox(parsing:) parses positionally and rejects non-finite
  values. It previously used compactMap, so "1,2,foo,3,4" was accepted as
  (1,2,3,4) with the bad field silently dropped and the rest shifted.

Tests
- New APIHardeningTests: huge layer indices, long SRS round trip,
  negative bufferSize, ImageFormat validation, error equality,
  Metatile/sequence validation instead of trapping, and malformed
  bounding-box strings.

Fixes #7
Fixes #14
Fixes #29
Fixes #43
Fixes #65
Fixes #66
Fixes #83
Fixes #85
Fixes #92
Fixes #94
Fixes #103
@trasch trasch self-assigned this Nov 2, 2026
@trasch trasch added the enhancement New feature or request label Nov 2, 2026
Rebased onto main after #111-#116 landed. Conflicts were resolved by keeping
main's newer logic and re-applying this PR's hardening on top:
- MapnikPool keeps the unlocked-factory acquire from #112.
- TileSequence/MetatileSequence keep main's bounds.isGeographic check, now
  thrown as MapnikError.invalidInput instead of a precondition.

Trapping accessors
- layerVisible(_:), layerSRS(_:), layerQueryable(_:) and
  layerVisible(_:atScaleDenominator:) used a plain Int32(index), which
  traps for indices outside Int32 range. They now return nil as
  documented.
- Metatile.init, TileSequence.init and MetatileSequence.init used
  precondition for user-facing validation. They now throw
  MapnikError.invalidInput, so callers that build blocks or sequences from
  external data get an error instead of a crash.
- MetatileOptions.metatileSize/validate no longer trap on a huge
  width x scale.

Silent truncation
- srs and layerSRS grow the buffer instead of returning a silently
  truncated projection string; long PROJ.4 strings exceed 255 characters.

Validation
- ImageFormat validates its options (png colors 1...256, jpeg/webp quality
  0...100), so a bad value surfaces as MapnikError.invalidInput instead of
  a renderingFailed from deep inside mapnik.
- setBufferSize clamps negative values, matching RenderOptions.validate.

Errors
- MapnikError is Equatable and LocalizedError, and gained a
  serializationFailed case.
- MapnikPoolError.exhausted carries the pool limit and is Equatable.

BoundingBox parsing
- BoundingBox(parsing:) parses positionally and rejects non-finite values.
  It previously used compactMap, so "1,2,foo,3,4" was accepted as
  (1,2,3,4) with the bad field silently dropped.

Tests
- APIHardeningTests: huge layer indices, long SRS round trip, negative
  bufferSize, ImageFormat validation, error equality, Metatile/sequence
  validation instead of trapping, and malformed bounding-box strings.
The docs job builds with --warnings-as-errors, so the link to the internal
validate() method failed the run. Describe the behaviour instead of linking.
@trasch
trasch merged commit ddd2182 into main Nov 2, 2026
5 checks passed
@trasch
trasch deleted the fix/api-hardening branch November 2, 2026 21:08
trasch added a commit that referenced this pull request Nov 2, 2026
Rebased onto main after #117 landed. Conflicts were resolved by keeping
main's newer render pipeline (withRenderState, the cairo resize helper) and
re-applying this PR's additions on top.

TilelistBuilder
- tileCount counts unique tiles instead of additions, so it agrees with
  tilelist (which de-duplicates).

Vector rendering
- renderSVG/renderPDF/renderPostScript take optional width/height so the
  page size is explicit instead of depending on the map's previous size.
  The map size is restored afterwards.

ImageFormat
- typeString is public, so the documented mapnik type mapping is
  observable (and testable without @testable import).

C shim
- The cairo temp file honours TMPDIR via
  std::filesystem::temp_directory_path instead of hard-coding /tmp.
- Removed the unused AGG include.

Packaging
- Package.resolved is no longer committed: for a library it only pins the
  repo's own builds and hides incompatibilities with newer gis-tools
  releases.

Tests
- tileCount uniqueness, vector page size (and that the map size is
  restored), default vector size, and every ImageFormat type string.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment