diff --git a/src/compact_encoding/frame.py b/src/compact_encoding/frame.py index e3bf190..79cbc9e 100644 --- a/src/compact_encoding/frame.py +++ b/src/compact_encoding/frame.py @@ -1,4 +1,5 @@ from . import integer +from .codec import OutOfBounds from .state import State @@ -21,6 +22,8 @@ def decode(self, state): outer_end = state.end length = integer.uint.decode(state) frame_end = state.start + length + if frame_end > outer_end: + raise OutOfBounds("Out of bounds") state.end = frame_end try: m = self._codec.decode(state) diff --git a/tests/test_frame.py b/tests/test_frame.py index 893ac9e..020a93e 100644 --- a/tests/test_frame.py +++ b/tests/test_frame.py @@ -71,3 +71,16 @@ def test_frame_decode_truncated_raises(): # aren't present; verified this also raises against the JS reference. with pytest.raises(OutOfBounds): cenc.decode(cenc.frame(cenc.uint), bytes.fromhex("01fd")) + + +def test_frame_decode_length_past_the_end_raises(): + # A frame announcing more bytes than follow it is a rejection rather than + # the value inside it: 0501 announces five bytes with one behind it. The + # cursor must not be left past the buffer either, or a later read works + # from a position that does not exist. + from compact_encoding.state import State + + state = State(bytes.fromhex("0501")) + with pytest.raises(OutOfBounds): + cenc.frame(cenc.uint).decode(state) + assert state.remaining >= 0