Skip to content

Commit 246226b

Browse files
committed
PHPC-613: toJSON() should throw if bson_as_json() fails
1 parent fbd2931 commit 246226b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/bson.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1583,6 +1583,13 @@ PHP_FUNCTION(toJSON)
15831583
char *str;
15841584
size_t str_len;
15851585
str = bson_as_json(b, &str_len);
1586+
1587+
if (!str) {
1588+
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE TSRMLS_CC, "Could not convert BSON document to a JSON string");
1589+
bson_reader_destroy(reader);
1590+
return;
1591+
}
1592+
15861593
PHONGO_RETVAL_STRINGL(str, str_len);
15871594
bson_free(str);
15881595
} else {

tests/bson/bson-toJSON_error-003.phpt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
--TEST--
2+
BSON\toJSON(): BSON decoding exceptions for bson_as_json() failure
3+
--SKIPIF--
4+
<?php require __DIR__ . "/../utils/basic-skipif.inc"?>
5+
--FILE--
6+
<?php
7+
require_once __DIR__ . "/../utils/basic.inc";
8+
9+
$tests = array(
10+
// Invalid UTF-8 characters (i.e. 0xFE, 0xFF) in field name
11+
pack('VCCCxVa*xx', 17, 2, 254, 255, 3, 'bar'),
12+
/* Note: we don't use a three-character string in the underflow case, as
13+
* the 4-byte string length and payload (i.e. three characters + null byte)
14+
* coincidentally satisfy the expected size for an 8-byte double. We also
15+
* don't use a four-character string, since its null byte would be
16+
* interpreted as the document terminator. The actual document terminator
17+
* would then remain in the buffer and trigger a "did not exhaust" error.
18+
*/
19+
pack('VCa*xVa*xx', 17, 1, 'foo', 3, 'ab'), // Invalid field type (underflow)
20+
pack('VCa*xVa*xx', 20, 1, 'foo', 6, 'abcde'), // Invalid field type (overflow)
21+
);
22+
23+
foreach ($tests as $bson) {
24+
echo throws(function() use ($bson) {
25+
toJSON($bson);
26+
}, 'MongoDB\Driver\Exception\UnexpectedValueException'), "\n";
27+
}
28+
29+
?>
30+
===DONE===
31+
<?php exit(0); ?>
32+
--EXPECTF--
33+
OK: Got MongoDB\Driver\Exception\UnexpectedValueException
34+
Could not convert BSON document to a JSON string
35+
OK: Got MongoDB\Driver\Exception\UnexpectedValueException
36+
Could not convert BSON document to a JSON string
37+
OK: Got MongoDB\Driver\Exception\UnexpectedValueException
38+
Could not convert BSON document to a JSON string
39+
===DONE===

0 commit comments

Comments
 (0)