From 23b080d094dbb74c024d173142134a022448abbe Mon Sep 17 00:00:00 2001 From: Jarry Shaw Date: Mon, 2 Nov 2026 11:54:04 -0500 Subject: [PATCH] fix(application): parse an HTTP/2 SETTINGS frame cut inside its settings (#2659) A SETTINGS frame the capture cuts short falls back to Raw. Its settings list is sized by the frame's Length, so past the octets present a SettingPair consumes nothing, and ListField.unpack refuses it as a loop making no progress. - SettingPairListField sizes SettingsFrame.settings by the octets present: the setting the data ends inside is kept as far as it goes, and Schema.unpack records the short read. ListField is unchanged. - HTTPv2.make takes frame_length, which HTTPv2._make_data passes through. One that is no int from the frame's own Length to 0xFFFFFF, or above it before a payload, raises ProtocolError (#2617). - HTTPv2.pack has a frame made short of its Length parsed back at that Length, as the capture was, rather than refused by HTTPv2.read. - Tests: cuts at every offset through TCP and through HTTPv2, a whole frame, the next frame left alone, the field on bytes and a stream, frame_length's refusals and edges, a dict with no length, and the short-read sweep. HTTP, HTTP/2, schema, sweep, doc-claim and member-order modules pass; captures parse identically to main. --- .../pcapkit/protocols/application/httpv2.rst | 4 + pcapkit/protocols/application/httpv2.py | 50 ++- .../protocols/schema/application/httpv2.py | 48 ++- .../test_httpv2_settings_cut_2659_unit.py | 288 ++++++++++++++++++ .../test_short_read_roundtrip_unit.py | 4 + 5 files changed, 386 insertions(+), 8 deletions(-) create mode 100644 tests/protocols/application/test_httpv2_settings_cut_2659_unit.py diff --git a/docs/source/pcapkit/protocols/application/httpv2.rst b/docs/source/pcapkit/protocols/application/httpv2.rst index 7cd2178585..a5a5adf04f 100644 --- a/docs/source/pcapkit/protocols/application/httpv2.rst +++ b/docs/source/pcapkit/protocols/application/httpv2.rst @@ -149,6 +149,10 @@ Header Schemas :members: :show-inheritance: +.. autoclass:: pcapkit.protocols.schema.application.httpv2.SettingPairListField + :members: + :show-inheritance: + .. autoclass:: pcapkit.protocols.schema.application.httpv2.SettingsFrame :members: :show-inheritance: diff --git a/pcapkit/protocols/application/httpv2.py b/pcapkit/protocols/application/httpv2.py index 73653c6f07..34f24d9950 100644 --- a/pcapkit/protocols/application/httpv2.py +++ b/pcapkit/protocols/application/httpv2.py @@ -208,6 +208,10 @@ class HTTPv2(HTTPBase[Data_HTTP, Schema_HTTP], * A whole frame after the first in a segment is a further layer of this class, where it was kept as :class:`~pcapkit.protocols.misc.raw.Raw` (:issue:`2536`). + * A ``SETTINGS`` frame the capture cut inside its settings parses as far + as its octets go, where it was :class:`~pcapkit.protocols.misc.raw.Raw`, + and :meth:`make` takes ``frame_length``, so it rebuilds as captured + (:issue:`2659`). """ @@ -314,6 +318,11 @@ def unpack(self, length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Data_HTTP' holds one frame per packet and has no form for a frameless segment. """ + # NOTE: A frame ``pack`` made short of its Length parses at that Length (#2659). + made_length = vars(self).pop('_made_length', None) + if length is None: + length = made_length + preface_len = len(_HTTP2_PREFACE) if self.__header__ is None and self._data[:preface_len] == _HTTP2_PREFACE \ and (length is None or length >= preface_len): @@ -418,6 +427,7 @@ def make(self, # type: ignore[override] frame: 'Optional[bytes | Data_HTTP | Schema_FrameType | dict[str, Any]]' = None, payload: 'bytes | ProtocolBase | Schema' = b'', preface: 'bool' = False, # pylint: disable=unused-argument + frame_length: 'Optional[int]' = None, **kwargs: 'Any') -> 'Schema_HTTP': """Make (construct) packet data. @@ -437,6 +447,12 @@ def make(self, # type: ignore[override] payload: Octets after the frame, e.g. the next frame. preface: Whether the HTTP/2 connection preface goes ahead of the frame; :meth:`pack` writes it. + frame_length: Length of the frame payload, as transmitted on the + wire, the 9-octet header excluded (:rfc:`9113#section-4.1`); + computed from ``frame`` when not given, so a ``SETTINGS`` frame + the capture cut inside its settings rebuilds as captured. A + Length above the one ``frame`` packs to is written as given, + as on a frame the capture cut short. **kwargs: Arbitrary keyword arguments. Returns: @@ -446,7 +462,11 @@ def make(self, # type: ignore[override] ProtocolError: If ``frame`` is none of the forms this maker reads -- raw :obj:`bytes`, a :obj:`dict` of frame arguments, an :class:`~pcapkit.protocols.data.application.httpv2.HTTPv2` data - model or a :class:`~pcapkit.protocols.schema.schema.Schema`. + model or a :class:`~pcapkit.protocols.schema.schema.Schema`; or + if ``frame_length`` is not an :obj:`int` from the Length + ``frame`` packs to up to ``0xFFFFFF``, or exceeds that Length + with a non-empty ``payload``, which the frame would read as its + own (:issue:`2617`). .. versionchanged:: 1.5.0 @@ -497,6 +517,16 @@ def make(self, # type: ignore[override] flags_val[f'bit_{bit}'] = (int(flags) & (1 << bit)) >> bit length = self._make_http_length(frame_val, flags) + if frame_length is not None: + if isinstance(frame_length, bool) or not isinstance(frame_length, int) \ + or not length <= frame_length <= 0xFFFFFF: + raise ProtocolError(f'HTTP/2: [Type {type_val}] invalid frame_length: {frame_length!r} ' + f'for a frame payload of {length} octet(s)') + # NOTE: Past the frame payload, the Length would read the next frame as its own. + if frame_length > length and payload is not None and len(payload) > 0: + raise ProtocolError(f'HTTP/2: [Type {type_val}] invalid frame_length: {frame_length!r} ' + f'for a frame payload of {length} octet(s) with a payload after it') + length = frame_length return Schema_HTTP( length=length, @@ -528,11 +558,22 @@ def pack(self, **kwargs: 'Any') -> 'bytes': type's own schema. Any other call leaves the instance's header as it was (:issue:`1769`). + A frame whose payload falls short of its Length, as + :meth:`from_data` rebuilds a ``SETTINGS`` frame the capture cut + inside its settings, is parsed back at that Length, as the capture + was, rather than refused as a frame the data cannot back + (:issue:`2659`). + """ data = super().pack(**kwargs) # NOTE: Constructing, by the test ``ProtocolBase._packing_target`` makes. if '_info' not in vars(self): self.__header__ = None # type: ignore[assignment] + + start = len(_HTTP2_PREFACE) if kwargs.get('preface', False) else 0 + declared = start + 9 + int.from_bytes(data[start:start + 3], 'big') + if declared > len(data): + self._made_length = declared return data @classmethod @@ -600,10 +641,8 @@ def _make_data(cls, data: 'Data_HTTP') -> 'dict[str, Any]': # type: ignore[over Key-value pairs for protocol construction. """ - # NOTE: No ``length``: :meth:`make` computes the frame's Length from the - # frame it builds, and a ``length`` keyword would instead be taken by - # ``ProtocolBase.__init__`` as the number of octets to parse back -- - # the payload length alone, nine octets short of the frame. + # NOTE: The Length as on the wire, so a cut SETTINGS frame keeps it (#2659); + # ``length`` would be taken by ``ProtocolBase.__init__`` as octets to parse. return { 'type': data.type, 'flags': data.flags.__value__ if data.flags is not None else 0, @@ -612,6 +651,7 @@ def _make_data(cls, data: 'Data_HTTP') -> 'dict[str, Any]': # type: ignore[over 'frame': data, 'payload': cls._make_payload(data), 'preface': bool(data.get('preface')), + 'frame_length': data.get('length'), } @staticmethod diff --git a/pcapkit/protocols/schema/application/httpv2.py b/pcapkit/protocols/schema/application/httpv2.py index dd3770e307..5af50e1825 100644 --- a/pcapkit/protocols/schema/application/httpv2.py +++ b/pcapkit/protocols/schema/application/httpv2.py @@ -12,6 +12,7 @@ class is renamed :class:`~pcapkit.protocols.schema.application.httpv2.HTTPv2`, import collections import enum +import io from typing import TYPE_CHECKING, cast from pcapkit.const.http.error_code import ErrorCode as Enum_ErrorCode @@ -35,7 +36,7 @@ class is renamed :class:`~pcapkit.protocols.schema.application.httpv2.HTTPv2`, ] if TYPE_CHECKING: - from typing import Any, Optional + from typing import IO, Any, Optional from pcapkit.corekit.fields.field import FieldBase as Field from pcapkit.protocols.protocol import ProtocolBase @@ -343,6 +344,46 @@ class SettingPair(Schema): def __init__(self, id: 'Enum_Setting', value: 'int') -> 'None': ... +class SettingPairListField(ListField): + """Setting list that ends with the data. + + :attr:`SettingsFrame.settings` is sized by the frame's Length, which exceeds + the octets present once the capture cuts the frame short. A setting read + past them consumes nothing, which :meth:`ListField.unpack + ` refuses to loop on, + so the list is sized by the octets present instead: the setting the data + ends inside is kept as far as it goes, and :meth:`Schema.unpack + ` records the short read + (:issue:`2659`). + + """ + + def unpack(self, buffer: 'bytes | IO[bytes]', packet: 'dict[str, Any]') -> 'list[SettingPair]': + """Unpack field value from :obj:`bytes`. + + Args: + buffer: Field buffer. + packet: Packet data. + + Returns: + Unpacked settings. + + """ + if isinstance(buffer, bytes): + present = len(buffer) + else: + start = buffer.tell() + present = buffer.seek(0, io.SEEK_END) - start + buffer.seek(start, io.SEEK_SET) + + declared = self._length + self._length = min(declared, present) + try: + return cast('list[SettingPair]', super().unpack(buffer, packet)) + finally: + self._length = declared + + @schema_final class SettingsFrame(FrameType, code=Enum_Frame.SETTINGS): """Header schema for HTTP/2 ``SETTINGS`` frames.""" @@ -352,8 +393,9 @@ class Flags(FrameType.Flags): ACK = BIT_0 = 0x1 - #: Settings. - settings: 'list[SettingPair]' = ListField( + #: Settings, read no further than the data goes (see + #: :class:`SettingPairListField`). + settings: 'list[SettingPair]' = SettingPairListField( length=lambda pkt: pkt['__length__'], item_type=SchemaField(length=6, schema=SettingPair), ) diff --git a/tests/protocols/application/test_httpv2_settings_cut_2659_unit.py b/tests/protocols/application/test_httpv2_settings_cut_2659_unit.py new file mode 100644 index 0000000000..b729333f8e --- /dev/null +++ b/tests/protocols/application/test_httpv2_settings_cut_2659_unit.py @@ -0,0 +1,288 @@ +# -*- coding: utf-8 -*- +"""An HTTP/2 ``SETTINGS`` frame cut inside its settings parses as far as it goes (#2659). + +A capture cut short hands the frame fewer octets than its Length, which the IPv4 +total length still backs. ``SettingsFrame.settings`` was sized by that Length, so past +the octets present a ``SettingPair`` consumed nothing and ``ListField.unpack`` raised +``FieldValueError``, leaving the segment ``Raw``. ``HTTPv2.make`` also recomputed the +Length from the settings held, so a parsed cut frame could not rebuild as captured. + +Every case builds its own octets. + +""" + +import io +import unittest +import warnings + +from tests._support import reimport_once_per_class +from tests.foundation import _roundtrip as wire + + +def _frame(type_: int, flags: int, sid: int, payload: bytes) -> bytes: + """An HTTP/2 frame; its Length counts the payload alone (RFC 9113, section 4.1).""" + return len(payload).to_bytes(3, 'big') + bytes([type_, flags]) + sid.to_bytes(4, 'big') + payload + + +#: ``SETTINGS_HEADER_TABLE_SIZE`` (0x1) of 4096, ``SETTINGS_MAX_CONCURRENT_STREAMS`` +#: (0x3) of 100 and ``SETTINGS_INITIAL_WINDOW_SIZE`` (0x4) of 65536, each a 16-bit +#: identifier and a 32-bit value (RFC 9113, sections 6.5.1 and 6.5.2). +PAIRS = bytes.fromhex('000100001000' '000300000064' '000400010000') +SETTINGS = _frame(0x4, 0x0, 0, PAIRS) +#: A connection-level ``WINDOW_UPDATE`` of 65535. +WINDOW_UPDATE = _frame(0x8, 0x0, 0, bytes.fromhex('0000ffff')) + + +def _datagram(app: bytes) -> bytes: + """``app`` to TCP port 80, where HTTP is bound, in an IPv4 datagram declaring all of it.""" + return wire.ipv4(wire.tcp(app, seq=1, ack=1, dport=80), proto=6) + + +def _expected(present: bytes) -> 'list[tuple[int, int]]': + """The pairs ``present`` holds, the last one zero-filled as a short read is.""" + padded = present + bytes(-len(present) % 6) + return [(int.from_bytes(padded[i:i + 2], 'big'), int.from_bytes(padded[i + 2:i + 6], 'big')) + for i in range(0, len(padded), 6)] + + +class SettingsCutTests(unittest.TestCase): + """A ``SETTINGS`` frame cut at every offset inside its settings (#2659).""" + + def setUp(self) -> None: + reimport_once_per_class(self) + + def assert_cut(self, http: 'object', keep: int) -> None: + """``http`` holds the first ``keep`` octets of the settings and rebuilds them.""" + from pcapkit.protocols.application.httpv2 import HTTPv2 + from pcapkit.protocols.misc.no_payload import NoPayload + + self.assertIsInstance(http, HTTPv2) + self.assertEqual(http.data, SETTINGS[:9 + keep]) + self.assertEqual(http.info.length, len(PAIRS)) + self.assertEqual(http.info['__short_read__'], ('frame', keep)) + self.assertEqual([(int(k), v) for k, v in http.info.settings.items(multi=True)], + _expected(PAIRS[:keep])) + self.assertIsInstance(http.payload, NoPayload) + self.assertEqual(HTTPv2.from_data(http.info).data, http.data) + self.assertEqual(HTTPv2.from_data(http.info.to_dict()).data, http.data) + + def test_cut_through_tcp_at_every_offset(self) -> None: + from pcapkit.protocols.internet.ipv4 import IPv4 + + packet = _datagram(SETTINGS) + head = len(packet) - len(SETTINGS) + for keep in range(len(PAIRS)): + raw = packet[:head + 9 + keep] + with self.subTest(keep=keep): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + ipv4 = IPv4(raw, len(raw)) + self.assertEqual(str(ipv4.protochain), 'IPv4:TCP:HTTP/2') + self.assert_cut(ipv4.payload.payload, keep) + self.assertEqual(IPv4.from_data(ipv4.info).data, raw) + self.assertEqual(IPv4.from_data(ipv4.info.to_dict()).data, raw) + self.assertEqual(caught, []) + + def test_cut_through_httpv2_at_every_offset(self) -> None: + from pcapkit.protocols.application.httpv2 import HTTPv2 + + for keep in range(len(PAIRS)): + with self.subTest(keep=keep): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + self.assert_cut(HTTPv2(SETTINGS[:9 + keep], len(SETTINGS)), keep) + self.assertEqual(caught, []) + + def test_a_setting_cut_inside_its_value_keeps_its_identifier(self) -> None: + from pcapkit.const.http.setting import Setting + from pcapkit.protocols.application.httpv2 import HTTPv2 + + http = HTTPv2(SETTINGS[:9 + 9], len(SETTINGS)) + self.assertEqual(list(http.info.settings.items(multi=True)), + [(Setting.HEADER_TABLE_SIZE, 4096), (Setting.MAX_CONCURRENT_STREAMS, 0)]) + + def test_whole_frame_is_the_control(self) -> None: + from pcapkit.const.http.setting import Setting + from pcapkit.protocols.application.httpv2 import HTTPv2 + from pcapkit.protocols.internet.ipv4 import IPv4 + + packet = _datagram(SETTINGS) + for name, http in (('TCP', IPv4(packet, len(packet)).payload.payload), + ('HTTPv2', HTTPv2(SETTINGS, len(SETTINGS)))): + with self.subTest(via=name): + self.assertNotIn('__short_read__', http.info) + self.assertEqual(http.info.length, 18) + self.assertEqual(list(http.info.settings.items(multi=True)), + [(Setting.HEADER_TABLE_SIZE, 4096), (Setting.MAX_CONCURRENT_STREAMS, 100), + (Setting.INITIAL_WINDOW_SIZE, 65536)]) + self.assertEqual([int(key) for key in http.info.settings], [0x1, 0x3, 0x4]) + self.assertEqual(HTTPv2.from_data(http.info).data, SETTINGS) + + def test_the_next_frame_is_not_swallowed(self) -> None: + from pcapkit.protocols.application.httpv2 import HTTPv2 + from pcapkit.protocols.internet.ipv4 import IPv4 + from pcapkit.protocols.misc.raw import Raw + + packet = _datagram(SETTINGS + WINDOW_UPDATE) + for keep in (len(WINDOW_UPDATE), len(WINDOW_UPDATE) - 1): + raw = packet[:len(packet) - len(WINDOW_UPDATE) + keep] + with self.subTest(next_frame=keep): + first = IPv4(raw, len(raw)).payload.payload + self.assertIsInstance(first, HTTPv2) + self.assertNotIn('__short_read__', first.info) + self.assertEqual(len(list(first.info.settings.items(multi=True))), 3) + rest = first.payload + self.assertEqual(rest.data, WINDOW_UPDATE[:keep]) + if keep == len(WINDOW_UPDATE): + self.assertIsInstance(rest, HTTPv2) + self.assertEqual(rest.info.increment, 65535) + else: + self.assertIs(type(rest), Raw) + self.assertIsNone(rest.info.error) + + +class SettingPairListFieldTests(unittest.TestCase): + """The settings list is sized by the octets present, no further than its Length.""" + + def setUp(self) -> None: + reimport_once_per_class(self) + + def test_reads_bytes_and_a_live_stream_alike(self) -> None: + from pcapkit.protocols.schema.application.httpv2 import SettingsFrame + + field = SettingsFrame.__fields__['settings']({'__length__': len(PAIRS)}) + stream = io.BytesIO(b'\xde\xad' + PAIRS[:9]) + stream.seek(2) + for name, buffer in (('bytes', PAIRS[:9]), ('stream', stream)): + with self.subTest(buffer=name): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter('always') + parsed = field.unpack(buffer, {}) + self.assertEqual(caught, []) + self.assertEqual([(int(pair.id), pair.value) for pair in parsed], [(1, 4096), (3, 0)]) + self.assertEqual(field.length, len(PAIRS)) + + def test_a_live_stream_is_read_no_further_than_the_length(self) -> None: + from pcapkit.protocols.schema.application.httpv2 import SettingsFrame + + field = SettingsFrame.__fields__['settings']({'__length__': 12}) + stream = io.BytesIO(PAIRS + WINDOW_UPDATE) + parsed = field.unpack(stream, {}) + self.assertEqual([(int(pair.id), pair.value) for pair in parsed], [(1, 4096), (3, 100)]) + self.assertEqual(stream.tell(), 12) + + +class SettingsFrameLengthTests(unittest.TestCase): + """``HTTPv2.make`` writes the ``frame_length`` it is given only as an :obj:`int` + from the Length the frame packs to up to ``0xFFFFFF``, and above that Length + only with no payload after the frame; any other is refused (#2617, #2659).""" + + #: One setting, so the frame packs to a Length of 6. + ONE_PAIR = {'settings': [(0x1, 4096)]} + + def setUp(self) -> None: + reimport_once_per_class(self) + + def test_a_length_the_frame_or_the_field_cannot_carry_is_refused(self) -> None: + import re + + from pcapkit.const.http.frame import Frame + from pcapkit.protocols.application.httpv2 import HTTPv2 + from pcapkit.utilities.exceptions import ProtocolError + + cases = ( + ('past the 24-bit field', Frame.SETTINGS, self.ONE_PAIR, 2 ** 24, b'', 6), + ('a bool', Frame.SETTINGS, self.ONE_PAIR, False, b'', 6), + # each in range as an int, so only the bool clause refuses it + ('True for one octet', Frame.DATA, {'data': b'a'}, True, b'', 1), + ('False for no octets', Frame.DATA, {'data': b''}, False, b'', 0), + ('a float', Frame.SETTINGS, self.ONE_PAIR, 2.0, b'', 6), + ('a str', Frame.SETTINGS, self.ONE_PAIR, '9', b'', 6), + ('negative', Frame.SETTINGS, self.ONE_PAIR, -1, b'', 6), + ('short of the settings', Frame.SETTINGS, self.ONE_PAIR, 0, b'', 6), + ('short of the data', Frame.DATA, {'data': b'abc'}, 2, b'', 3), + ('past the settings, before a frame', Frame.SETTINGS, self.ONE_PAIR, 18, WINDOW_UPDATE, 6), + ) + for label, type_, frame, length, payload, built in cases: + with self.subTest(label), self.assertRaisesRegex( + ProtocolError, rf'^HTTP/2: \[Type \d\] invalid frame_length: {re.escape(repr(length))} ' + rf'for a frame payload of {built} octet'): + HTTPv2(type=type_, sid=0 if type_ is Frame.SETTINGS else 1, frame=frame, + frame_length=length, payload=payload) + + def test_a_length_from_the_frame_to_the_field_maximum_is_written(self) -> None: + from pcapkit.const.http.frame import Frame + from pcapkit.protocols.application.httpv2 import HTTPv2 + + # A SETTINGS Length is a multiple of 6 (RFC 9113, section 6.5), which + # ``_read_http_settings`` holds it to, so the edge one past a frame is on DATA. + cases = ( + ('the settings, before a frame', Frame.SETTINGS, self.ONE_PAIR, 6, WINDOW_UPDATE, PAIRS[:6]), + ('the data, before a frame', Frame.DATA, {'data': b'abc'}, 3, WINDOW_UPDATE, b'abc'), + ('one past the data', Frame.DATA, {'data': b'abc'}, 4, b'', b'abc'), + ('one past the data, payload None', Frame.DATA, {'data': b'abc'}, 4, None, b'abc'), + ) + for label, type_, frame, length, payload, body in cases: + with self.subTest(label): + http = HTTPv2(type=type_, sid=0 if type_ is Frame.SETTINGS else 1, frame=frame, + frame_length=length, payload=payload) + self.assertEqual(http.data[:3], length.to_bytes(3, 'big')) + self.assertEqual(http.data[9:], body + (payload or b'')) + self.assertEqual(http.info.length, length) + if payload: + self.assertEqual(http.payload.info.increment, 65535) + + # Parsed back, a Length this far past the octets meets ``MAX_ZERO_PAD_LENGTH``, + # so the field maximum is checked on what ``make`` builds. + header = object.__new__(HTTPv2).make(type=Frame.SETTINGS, frame=self.ONE_PAIR, frame_length=0xFFFFFF) + self.assertEqual(header.length, 0xFFFFFF) + self.assertEqual(bytes(header)[:3], b'\xff\xff\xff') + + def test_a_length_past_the_settings_is_kept(self) -> None: + from pcapkit.const.http.frame import Frame + from pcapkit.const.http.setting import Setting + from pcapkit.protocols.application.httpv2 import HTTPv2 + + http = HTTPv2(type=Frame.SETTINGS, frame={'settings': [(Setting.HEADER_TABLE_SIZE, 4096)]}, + frame_length=18) + self.assertEqual(http.data, SETTINGS[:15]) + self.assertEqual(http.info.length, 18) + self.assertEqual(http.info['__short_read__'], ('frame', 6)) + self.assertEqual(list(http.info.settings.items(multi=True)), [(Setting.HEADER_TABLE_SIZE, 4096)]) + + def test_the_length_is_computed_when_not_given(self) -> None: + from pcapkit.const.http.frame import Frame + from pcapkit.const.http.setting import Setting + from pcapkit.protocols.application.httpv2 import HTTPv2 + + http = HTTPv2(type=Frame.SETTINGS, frame={'settings': [(Setting.HEADER_TABLE_SIZE, 4096)]}) + self.assertEqual(http.data, _frame(0x4, 0x0, 0, PAIRS[:6])) + self.assertEqual(http.info.length, 6) + self.assertNotIn('__short_read__', http.info) + + def test_an_explicit_parse_length_leaves_no_state_behind(self) -> None: + from pcapkit.const.http.frame import Frame + from pcapkit.protocols.application.httpv2 import HTTPv2 + + http = HTTPv2(type=Frame.SETTINGS, frame=self.ONE_PAIR, frame_length=18, length=27) + self.assertEqual(http.info.length, 18) + self.assertNotIn('_made_length', vars(http)) + + def test_a_dict_with_no_length_computes_it(self) -> None: + from pcapkit.const.http.frame import Frame + from pcapkit.const.http.setting import Setting + from pcapkit.protocols.application.httpv2 import HTTPv2 + + for label, data, wire_ in ( + ('SETTINGS', {'type': Frame.SETTINGS, 'flags': {'ACK': False, '__value__': 0}, 'reserved': 0, + 'sid': 0, 'settings': [(Setting.HEADER_TABLE_SIZE, 4096)]}, + _frame(0x4, 0x0, 0, PAIRS[:6])), + ('WINDOW_UPDATE', {'type': Frame.WINDOW_UPDATE, 'flags': {'__value__': 0}, 'reserved': 0, + 'sid': 0, 'increment_reserved': 0, 'increment': 65535}, + WINDOW_UPDATE)): + with self.subTest(label): + self.assertEqual(HTTPv2.from_data(data).data, wire_) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/protocols/test_short_read_roundtrip_unit.py b/tests/protocols/test_short_read_roundtrip_unit.py index ffa20795b3..96973c2070 100644 --- a/tests/protocols/test_short_read_roundtrip_unit.py +++ b/tests/protocols/test_short_read_roundtrip_unit.py @@ -102,6 +102,10 @@ def _ipv6(code: int, body: bytes) -> bytes: '13881389deadbeef000000000003001400000001000100020000000061626364')), ('ftp', 'application.ftp:FTP', {}, b'XYZW arg\r\n'), ('http1', 'application.httpv1:HTTPv1', {}, b'GET / HTTP/1.1\r\n\r\n'), + # an HTTP/2 SETTINGS frame of three settings, to TCP port 80 (#2659) + ('httpv2-settings', 'internet.ipv4:IPv4', {}, bytes.fromhex( + '450000431234000040067c4ac0000201c6336402' '9c40005000000001000000015010ffff00000000' + '000012040000000000' '000100001000' '000300000064' '000400010000')), )