[stdlib] Prevent coercion from Bool to numerical types when decoding JSON and plist #11885
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
JSONEncoder
andPropertyListEncoder
both useNSNumber
to boxBool
values. An encodedBool
can be coerced to any numerical type during decoding because(false as NSNumber).intValue == 0
. As a remedy, all of theunbox(_:as:)
methods of_JSONDecoder
and_PlistDecoder
for numerical types include a check that the value is not identical to eitherkCFBooleanTrue
orkCFBooleanFalse
, and throw aDecodingError._typeMismatch(at:expectation:)
if this check fails.Right now, Swift can dangerously decode
Bool
data as a numeric type as in the following examples:This issue has the potential to affect the correctness of many programs, and in particular programs that depend on the decoding system to validate the application-specific correctness of JSON. It could also be more troublesome for programs when unkeyed containers are used.
Note that currently the opposite is not an issue. Encoded numerical types cannot decode to
Bool
.