Skip to content

fix(plugin-mongodb): prevent crash on NaN or infinite document values (#1418)#1423

Merged
datlechin merged 2 commits into
mainfrom
fix/mongodb-nonfinite-number-crash
May 26, 2026
Merged

fix(plugin-mongodb): prevent crash on NaN or infinite document values (#1418)#1423
datlechin merged 2 commits into
mainfrom
fix/mongodb-nonfinite-number-crash

Conversation

@datlechin
Copy link
Copy Markdown
Member

Problem

Opening a MongoDB collection crashes the app (SIGABRT) when a document contains a non-finite floating-point value (NaN, +Infinity, -Infinity). BSON double is IEEE-754, so these values are legal in stored documents. Reported in #1418 with a crash report from 0.44.0.

The crash trace: +[NSJSONSerialization dataWithJSONObject:options:error:] -> _writeJSONArray -> _writeJSONNumber -> objc_exception_throw -> abort().

Root cause

BsonDocumentFlattener.sanitizeForJson was not total: its default branch returned any unrecognized value unchanged, so a non-finite Double/NSNumber reached JSONSerialization.data(withJSONObject:). That method raises an Objective-C NSInvalidArgumentException for non-finite numbers (and for unsupported types). The surrounding do { try ... } catch {} was dead code: Swift cannot catch a raised NSException, only bridged NSError, so the exception unwound to abort().

MongoDBPluginDriver.prettyJson (collection validators, index key specs) had the identical uncatchable try? flaw.

Fix

  • sanitizeForJson is now total: every value resolves to a guaranteed-JSON-safe form. Non-finite doubles become the tokens NaN / Infinity / -Infinity; any unsupported type becomes String(describing:) so nothing invalid can reach the writer.
  • serializeToJson gates on JSONSerialization.isValidJSONObject with an early-return guard, replacing the dead catch.
  • stringValue renders top-level non-finite doubles as the same tokens instead of Swift's lowercase nan/inf.
  • prettyJson sanitizes and validates before serializing.

Token spellings match MongoDB Extended JSON / mongosh. Nested values render quoted ({"v":"NaN"}, valid JSON, consistent with how Data/Date are already coerced); top-level cells render bare (NaN).

Tests

Added 9 tests to BsonDocumentFlattenerTests: nested NaN/+Inf/-Inf in dicts and arrays, the flatten-level crash scenario, top-level token rendering, and an unsupported nested type that now stringifies instead of crashing.

Notes

  • No PluginKit ABI change. MongoDB is registry-only, so this ships on the next plugin-mongodb-v* release after merge.
  • No docs change (crash fix, not a feature/setting change).

@datlechin datlechin merged commit ff3021f into main May 26, 2026
2 checks passed
@datlechin datlechin deleted the fix/mongodb-nonfinite-number-crash branch May 26, 2026 17:05
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.

1 participant