From 072856f9f34809f8eb33235bea70b43ce9db3998 Mon Sep 17 00:00:00 2001 From: Bala Avulapati Date: Fri, 20 Nov 2026 15:02:05 +0000 Subject: [PATCH] Reject a frame announcing more bytes than follow it Decode trusted the announced length, so a short frame read its value and left the cursor past the end of the buffer, where state.remaining goes negative and everything decoded after it works from a position that does not exist. Closes #18. --- src/compact_encoding/frame.py | 3 +++ tests/test_frame.py | 13 +++++++++++++ 2 files changed, 16 insertions(+) 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