Skip to content

Commit 6d3e3bc

Browse files
committed
Validate extension type codes before packing
1 parent 874b828 commit 6d3e3bc

2 files changed

Lines changed: 43 additions & 0 deletions

File tree

‎msgpack/_packer.pyx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,10 @@ cdef class Packer:
288288
@cython.critical_section
289289
def pack_ext_type(self, typecode, data):
290290
self._check_exports()
291+
if not isinstance(typecode, int):
292+
raise TypeError("typecode must have int type.")
293+
if not 0 <= typecode <= 127:
294+
raise ValueError("typecode should be 0-127")
291295
if len(data) > ITEM_LIMIT:
292296
raise ValueError("ext data too large")
293297
msgpack_pack_ext(&self.pk, typecode, len(data))

‎test/test_extension.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import array
22

3+
import pytest
4+
35
import msgpack
46
from msgpack import ExtType
57

@@ -85,3 +87,40 @@ def default(obj):
8587
testout = msgpack.packb(obj, default=default)
8688

8789
assert refout == testout
90+
91+
92+
@pytest.mark.parametrize("autoreset", [False, True])
93+
@pytest.mark.parametrize(
94+
"typecode, error",
95+
[
96+
(-129, ValueError),
97+
(-128, ValueError),
98+
(-1, ValueError),
99+
(128, ValueError),
100+
(256, ValueError),
101+
(2**100, ValueError),
102+
(1.5, TypeError),
103+
(None, TypeError),
104+
("1", TypeError),
105+
],
106+
)
107+
def test_pack_ext_type_invalid_code(typecode, error, autoreset):
108+
packer = msgpack.Packer(autoreset=autoreset)
109+
packer.pack(42)
110+
before = packer.bytes()
111+
with pytest.raises(error):
112+
packer.pack_ext_type(typecode, b"A")
113+
assert packer.bytes() == before
114+
115+
packed = packer.pack_ext_type(0, b"A")
116+
if not autoreset:
117+
packed = packer.bytes()
118+
assert packed[:1] == msgpack.packb(42)
119+
packed = packed[1:]
120+
assert msgpack.unpackb(packed) == ExtType(0, b"A")
121+
122+
123+
@pytest.mark.parametrize("typecode", [0, 127])
124+
def test_pack_ext_type_code_boundary(typecode):
125+
packed = msgpack.Packer().pack_ext_type(typecode, b"A")
126+
assert msgpack.unpackb(packed) == ExtType(typecode, b"A")

0 commit comments

Comments
 (0)