Skip to content

fix(codec): return InvalidVarint instead of panic on excess continuation bytes#3271

Open
erenyegit wants to merge 1 commit intocommonwarexyz:mainfrom
erenyegit:fix/varint-decoder-overflow-panic
Open

fix(codec): return InvalidVarint instead of panic on excess continuation bytes#3271
erenyegit wants to merge 1 commit intocommonwarexyz:mainfrom
erenyegit:fix/varint-decoder-overflow-panic

Conversation

@erenyegit
Copy link

Problem

varint::Decoder::feed could panic when the decoder received more continuation bytes than fit in the target type. For example, for Decoder::<u32> (max 5 bytes), feeding a 6th byte with the continuation bit set caused max_bits.checked_sub(self.bits_read) to return None, and .unwrap() panicked.

This is a robustness issue: malformed or adversarial input could crash the process instead of returning an error.

Solution

Replace the .unwrap() with .ok_or(Error::InvalidVarint(U::SIZE))?, so excess continuation bytes produce a proper Error::InvalidVarint instead of a panic. The decoder already uses this error variant for other invalid varint cases.

Testing

  • Added unit test decoder_rejects_excess_continuation_bytes that feeds 6 continuation bytes to Decoder::<u32> and asserts an InvalidVarint(4) error is returned.
  • cargo test -p commonware-codec passes (110 tests + doc tests).

…ion bytes

Decoder::feed could panic when fed more continuation bytes than fit in the
target type (e.g. 6+ bytes for u32). Replaced unwrap() with proper
Error::InvalidVarint return for malformed or adversarial input.
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

}
let err = decoder.feed(0x80).unwrap_err();
assert!(matches!(err, Error::InvalidVarint(4)));
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test doesn't exercise the new checked_sub code path

Low Severity

The test decoder_rejects_excess_continuation_bytes never exercises the new checked_subok_or guard. Because feed returns an error before incrementing bits_read (line 155 is unreached on error), bits_read stays at 28 after the 5th feed. The 6th feed still computes remaining_bits = 4 via a successful checked_sub, and the error comes from the existing overflow check at lines 140–144, not the new guard. The new defensive code has no test coverage.

Additional Locations (1)

Fix in Cursor Fix in Web

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant