Fix the bounds check in a TLV parser

Review the AI's codeMedium15 minCisco style

Your task

Your binary protocol carries TLV records: a type byte, a 2-byte length, then that many value bytes. The first parser crashed within seconds of fuzzing because it trusted the length from the wire. The fix walks the packet and rejects it whole if any record does not fit.

An assistant wrote parse_tlv_types(packet). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • packet: the packet's bytes, as a list of integers.
  • Return the type byte of every record, in order, or [-1] if the packet is malformed.

Rules the tests check:

  • If any value is below 0 or above 255, return [-1].
  • Walk the records from index 0. A record at index i has its type at i, a big-endian length at i + 1 and i + 2 (first byte times 256, plus the second), and its value in the next length bytes.
  • If fewer than 3 bytes remain at i, return [-1].
  • If fewer than length bytes remain after the 3 header bytes, return [-1].
  • The next record starts right after the value. The walk ends when it reaches the end of the packet exactly.
  • An empty packet has no records, so return [].

Examples

parse_tlv_types(packet: list[int]) -> list[int]
Example 1
Inputparse_tlv_types([1, 0, 2, 65, 66])
Output[1]
Example 2
Inputparse_tlv_types([1, 0, 1, 65, 2, 0, 0, 3, 0, 2, 9, 9])
Output[1, 2, 3]
Example 3
Inputparse_tlv_types([7, 255, 255, 1, 2])
Output[-1]