Improve decodeBase64() to throw on invalid input rather than silently accept it by dconeybe · Pull Request #7019 · firebase/firebase-js-sdk (original) (raw)
Fix all decodeBase64() functions to throw an exception when given invalid input. Previously, some implementations silently accepted invalid input, potentially leading to bugs.
The decodeBase64() function in packages/firestore/src/platform/base64.ts has different implementations on different platforms (e.g. browser, node, and react native). These implementations behave differently when given an invalid base64 string to decode:
- browser throws
DOMExceptionon any invalid input. - node silently ignores invalid input by truncating at the first invalid character.
- react native throws
Erroron some invalid inputs, and silently accepts others.
The node implementation used to have a regular expression that validated the input (link); however, it was removed in #6008 because it was too slow.
The "parent" decodeBase64() function now validates that the input string is valid base64 using an algorithm that is orders of magnitude more efficient and robust than a regular expression. It verifies that the input string has the expected length based on the number of bytes returned from the platform-specific base64 decoding function to which it delegates. If the length is not correct then the platform-specific function must have truncated at an invalid base64 character. In this case a new Base64DecodeError is thrown.
Credit for this PR goes to @milaGGL from #6992. I'm merely merging a small component of that PR into the master branch to reduce the diff when her PR ultimately gets merged.