Skip to content

Commit f5bdd25

Browse files
committed
Catch non-strings in BinaryEncoder.writeString
The javascript serializeBinary() function silently tosses away any non-string placed into what should be a string field, writing the equivalent of an empty string instead Not sure if or why anyone would be relying on that existing arbitrary behavior today, but silent data loss seems very undesirable and worth defending against
1 parent 3561b05 commit f5bdd25

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

binary/decoder_test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,16 @@ describe('binaryDecoderTest', function() {
376376
assertEquals(utf8_four_bytes, decoder.readString(utf8_four_bytes.length));
377377
});
378378

379+
/**
380+
* Verifies that passing a non-string to writeString raises an error.
381+
*/
382+
it('testBadString', function() {
383+
var encoder = new jspb.BinaryEncoder();
384+
385+
assertThrows(function() {encoder.writeString(42)});
386+
assertThrows(function() {encoder.writeString(null)});
387+
});
388+
379389
/**
380390
* Verifies that misuse of the decoder class triggers assertions.
381391
*/

binary/encoder.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,9 @@ jspb.BinaryEncoder.prototype.writeFixedHash64 = function(hash) {
473473
jspb.BinaryEncoder.prototype.writeString = function(value) {
474474
var oldLength = this.buffer_.length;
475475

476+
// Protect against non-string values being silently ignored.
477+
goog.asserts.assert(value.charCodeAt);
478+
476479
for (var i = 0; i < value.length; i++) {
477480

478481
var c = value.charCodeAt(i);

0 commit comments

Comments
 (0)