Skip to content

Commit a9d62cc

Browse files
committed
Reject extra $timestamp wrapper fields and guard non-document values
1 parent dee2cf1 commit a9d62cc

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

‎bson/json_util.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,11 @@ def _parse_binary(doc: Any, json_options: JSONOptions) -> Union[Binary, uuid.UUI
788788

789789

790790
def _parse_timestamp(doc: Any, dummy0: Any) -> Timestamp:
791+
if len(doc) != 1:
792+
raise TypeError(f"Bad $timestamp, extra field(s): {doc}")
791793
tsp = doc["$timestamp"]
794+
if not isinstance(tsp, Mapping):
795+
raise TypeError(f'$timestamp value must be a document with "t" and "i" components: {doc}')
792796
if set(tsp) != {"t", "i"}:
793797
raise TypeError(f'$timestamp must include exactly "t" and "i" components: {doc}')
794798
return Timestamp(tsp["t"], tsp["i"])

‎test/test_json_util.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -417,6 +417,18 @@ def test_timestamp_with_invalid_fields(self):
417417
):
418418
json_util.loads(f'{{"ts": {{"$timestamp": {value}}}}}')
419419

420+
def test_timestamp_with_extra_wrapper_fields(self):
421+
with self.assertRaisesRegex(TypeError, r"Bad \$timestamp, extra field\(s\)"):
422+
json_util.loads('{"ts": {"$timestamp": {"t": 4, "i": 13}, "extra": 1}}')
423+
424+
def test_timestamp_with_non_document_value(self):
425+
for value in ('["t", "i"]', '"ti"', "5"):
426+
with self.subTest(value=value):
427+
with self.assertRaisesRegex(
428+
TypeError, r"\$timestamp value must be a document"
429+
):
430+
json_util.loads(f'{{"ts": {{"$timestamp": {value}}}}}')
431+
420432
def test_uuid_default(self):
421433
# Cannot directly encode native UUIDs with the default
422434
# uuid_representation.

0 commit comments

Comments
 (0)