Debian Codegraph @

tests/test_gap_fuzzer.py

raw symbols SCIP
1 """Fuzz coverage for the GAP parser.
2
3 The broad fuzz loop is intentionally unseeded so each CI run explores
4 fresh inputs — that is how regressions like the off-by-one fixed in
5 PR #221 surface. The seed used for a given run is printed (and can be
6 pinned with the ``FUZZ_SEED`` environment variable) so any failure is
7 reproducible locally.
8
9 Only the uncached parse path is fuzzed: ``parse_advertisement_data`` and
10 friends are thin LRU-cache wrappers around it, so re-running the same
11 bytes through them adds cost without coverage.
12 """
13
14 import os
15 import random
16 from typing import Any
17
18 from bluetooth_data_tools.gap import (
19 _uncached_parse_advertisement_data,
20 parse_advertisement_data,
21 parse_advertisement_data_bytes,
22 )
23
24 _FUZZ_ITERATIONS = 1000
25
26 # AD type bytes used by the constructive fuzzer below. Kept as literals (rather
27 # than importing BLEGAPType) so the test pins the wire format independently of
28 # the production enum — a regression that renumbered a type would be caught.
29 _AD_TYPE_FLAGS = 0x01
30 _AD_TYPE_16BIT_UUID_MORE = 0x02
31 _AD_TYPE_16BIT_UUID_COMPLETE = 0x03
32 _AD_TYPE_32BIT_UUID_MORE = 0x04
33 _AD_TYPE_32BIT_UUID_COMPLETE = 0x05
34 _AD_TYPE_128BIT_UUID_MORE = 0x06
35 _AD_TYPE_128BIT_UUID_COMPLETE = 0x07
36 _AD_TYPE_SHORT_LOCAL_NAME = 0x08
37 _AD_TYPE_COMPLETE_LOCAL_NAME = 0x09
38 _AD_TYPE_TX_POWER = 0x0A
39 _AD_TYPE_SERVICE_DATA_16BIT = 0x16
40 _AD_TYPE_APPEARANCE = 0x19 # unhandled by the parser -> must be ignored
41 _AD_TYPE_SERVICE_DATA_32BIT = 0x20
42 _AD_TYPE_SERVICE_DATA_128BIT = 0x21
43 _AD_TYPE_MANUFACTURER_SPECIFIC = 0xFF
44
45 _BLE_BASE_UUID_TAIL = "0000-1000-8000-00805f9b34fb"
46
47
48 def _encode_ad(ad_type: int, payload: bytes) -> bytes:
49 """Encode one AD structure as ``[length][type][payload...]``.
50
51 ``length`` covers the type byte plus the payload, mirroring the on-the-wire
52 GAP framing the parser consumes.
53 """
54 return bytes([1 + len(payload), ad_type]) + payload
55
56
57 def _expected_16bit_uuid(value: int) -> str:
58 return f"0000{value:04x}-{_BLE_BASE_UUID_TAIL}"
59
60
61 def _expected_32bit_uuid(value: int) -> str:
62 return f"{value:08x}-{_BLE_BASE_UUID_TAIL}"
63
64
65 def _expected_128bit_uuid(le_bytes: bytes) -> str:
66 # The wire form is little-endian; the canonical string is big-endian hex.
67 hex_ = le_bytes[::-1].hex()
68 return f"{hex_[:8]}-{hex_[8:12]}-{hex_[12:16]}-{hex_[16:20]}-{hex_[20:]}"
69
70
71 def test_gap_fuzzer_random_bytes_do_not_crash() -> None:
72 seed = int(os.environ.get("FUZZ_SEED", random.randrange(2**64)))
73 print(f"fuzz seed: {seed:#x}")
74 rng = random.Random(seed)
75 for _ in range(_FUZZ_ITERATIONS):
76 adv = (
77 bytes(rng.randint(0, 255) for _ in range(rng.randint(1, 31))),
78 bytes(rng.randint(0, 255) for _ in range(rng.randint(1, 31))),
79 bytes(rng.randint(0, 255) for _ in range(rng.randint(1, 31))),
80 )
81 _uncached_parse_advertisement_data(b"".join(adv))
82
83
84 def test_gap_fuzzer_truncated_length_does_not_crash() -> None:
85 """An AD struct that claims more bytes than remain must be rejected, not read."""
86 rng = random.Random(0xB1EC0FFEE)
87 for _ in range(200):
88 # Claim a length that overruns the buffer, then provide a shorter body.
89 body = bytes(rng.randint(0, 255) for _ in range(rng.randint(0, 5)))
90 payload = bytes([100, rng.randint(1, 0xFF)]) + body
91 adv = parse_advertisement_data((payload,))
92 assert adv.local_name is None
93 assert adv.manufacturer_data == {}
94 assert adv.service_data == {}
95 assert adv.service_uuids == []
96
97
98 # Per-kind builders for the constructive fuzzer. Each takes ``(rng, chunks,
99 # expected)``, appends one encoded AD structure to ``chunks`` and folds its
100 # contribution into ``expected`` using the parser's own accumulation rules.
101 # A dispatch table (rather than an if/elif ladder) keeps kind selection and
102 # per-kind encode logic together, so adding an AD type is a single entry.
103
104
105 def _emit_flags(
106 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
107 ) -> None:
108 # Common in real adverts and explicitly fast-skipped — no output.
109 chunks.append(_encode_ad(_AD_TYPE_FLAGS, bytes([rng.randint(0, 0xFF)])))
110
111
112 def _emit_appearance(
113 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
114 ) -> None:
115 # A type the parser does not handle — must fall through to nothing.
116 body = bytes(rng.randint(0, 255) for _ in range(rng.randint(1, 4)))
117 chunks.append(_encode_ad(_AD_TYPE_APPEARANCE, body))
118
119
120 def _emit_complete_name(
121 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
122 ) -> None:
123 # COMPLETE name is last-wins — it always overwrites the running value.
124 # Restrict to printable ASCII so decode("utf-8") is unambiguous.
125 name = bytes(rng.randint(0x20, 0x7E) for _ in range(rng.randint(1, 12)))
126 chunks.append(_encode_ad(_AD_TYPE_COMPLETE_LOCAL_NAME, name))
127 expected["local_name"] = name.decode("utf-8")
128
129
130 def _emit_short_name(
131 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
132 ) -> None:
133 # SHORT name is first-wins (``local_name is None``): the parser keeps it
134 # only when no name has been seen yet, unlike COMPLETE's last-wins.
135 name = bytes(rng.randint(0x20, 0x7E) for _ in range(rng.randint(1, 12)))
136 chunks.append(_encode_ad(_AD_TYPE_SHORT_LOCAL_NAME, name))
137 if expected["local_name"] is None:
138 expected["local_name"] = name.decode("utf-8")
139
140
141 def _emit_uuid16(
142 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
143 ) -> None:
144 ad_type = rng.choice([_AD_TYPE_16BIT_UUID_COMPLETE, _AD_TYPE_16BIT_UUID_MORE])
145 values = [rng.randint(0, 0xFFFF) for _ in range(rng.randint(1, 4))]
146 payload = b"".join(v.to_bytes(2, "little") for v in values)
147 chunks.append(_encode_ad(ad_type, payload))
148 expected["service_uuids"].extend(_expected_16bit_uuid(v) for v in values)
149
150
151 def _emit_uuid32(
152 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
153 ) -> None:
154 ad_type = rng.choice([_AD_TYPE_32BIT_UUID_COMPLETE, _AD_TYPE_32BIT_UUID_MORE])
155 values = [rng.randint(0, 0xFFFFFFFF) for _ in range(rng.randint(1, 3))]
156 payload = b"".join(v.to_bytes(4, "little") for v in values)
157 chunks.append(_encode_ad(ad_type, payload))
158 expected["service_uuids"].extend(_expected_32bit_uuid(v) for v in values)
159
160
161 def _emit_uuid128(
162 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
163 ) -> None:
164 ad_type = rng.choice([_AD_TYPE_128BIT_UUID_COMPLETE, _AD_TYPE_128BIT_UUID_MORE])
165 uuids = [
166 bytes(rng.randint(0, 255) for _ in range(16)) for _ in range(rng.randint(1, 2))
167 ]
168 chunks.append(_encode_ad(ad_type, b"".join(uuids)))
169 expected["service_uuids"].extend(_expected_128bit_uuid(u) for u in uuids)
170
171
172 def _emit_service_data16(
173 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
174 ) -> None:
175 uuid16 = rng.randint(0, 0xFFFF)
176 body = bytes(rng.randint(0, 255) for _ in range(rng.randint(0, 6)))
177 payload = uuid16.to_bytes(2, "little") + body
178 chunks.append(_encode_ad(_AD_TYPE_SERVICE_DATA_16BIT, payload))
179 expected["service_data"][_expected_16bit_uuid(uuid16)] = body
180
181
182 def _emit_service_data32(
183 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
184 ) -> None:
185 # 32-bit service data slices the body at start+4 — a distinct offset from
186 # the 16-bit case, so a slicing regression here is invisible to uuid16.
187 uuid32 = rng.randint(0, 0xFFFFFFFF)
188 body = bytes(rng.randint(0, 255) for _ in range(rng.randint(0, 6)))
189 payload = uuid32.to_bytes(4, "little") + body
190 chunks.append(_encode_ad(_AD_TYPE_SERVICE_DATA_32BIT, payload))
191 expected["service_data"][_expected_32bit_uuid(uuid32)] = body
192
193
194 def _emit_service_data128(
195 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
196 ) -> None:
197 # 128-bit service data slices the body at start+16; the UUID key is the
198 # little-endian 16-byte prefix, same conversion as the 128-bit UUID list.
199 uuid128 = bytes(rng.randint(0, 255) for _ in range(16))
200 body = bytes(rng.randint(0, 255) for _ in range(rng.randint(0, 6)))
201 payload = uuid128 + body
202 chunks.append(_encode_ad(_AD_TYPE_SERVICE_DATA_128BIT, payload))
203 expected["service_data"][_expected_128bit_uuid(uuid128)] = body
204
205
206 def _emit_manufacturer(
207 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
208 ) -> None:
209 mid = rng.randint(0, 0xFFFF)
210 body = bytes(rng.randint(0, 255) for _ in range(rng.randint(0, 6)))
211 payload = mid.to_bytes(2, "little") + body
212 chunks.append(_encode_ad(_AD_TYPE_MANUFACTURER_SPECIFIC, payload))
213 expected["manufacturer_data"][mid] = body
214
215
216 def _emit_tx_power(
217 rng: random.Random, chunks: list[bytes], expected: dict[str, Any]
218 ) -> None:
219 raw = rng.randint(0, 0xFF)
220 chunks.append(_encode_ad(_AD_TYPE_TX_POWER, bytes([raw])))
221 expected["tx_power"] = raw - 256 if raw >= 128 else raw
222
223
224 _BUILDERS = {
225 "flags": _emit_flags,
226 "appearance": _emit_appearance,
227 "name_complete": _emit_complete_name,
228 "name_short": _emit_short_name,
229 "uuid16": _emit_uuid16,
230 "uuid32": _emit_uuid32,
231 "uuid128": _emit_uuid128,
232 "service_data16": _emit_service_data16,
233 "service_data32": _emit_service_data32,
234 "service_data128": _emit_service_data128,
235 "manufacturer": _emit_manufacturer,
236 "tx_power": _emit_tx_power,
237 }
238
239
240 def _build_random_advertisement(rng: random.Random) -> tuple[bytes, dict[str, Any]]:
241 """Build a well-formed advertisement and the output it must parse back to.
242
243 Returns ``(gap_bytes, expected)`` where ``expected`` mirrors the parser's
244 accumulation rules: service UUID lists append in encounter order, the
245 manufacturer-data and service-data dicts apply last-writer-wins per key,
246 COMPLETE local name / tx power keep the last well-formed value, and SHORT
247 local name keeps the first. ``FLAGS`` and an unhandled type are interleaved
248 to assert they never corrupt the result.
249 """
250 chunks: list[bytes] = []
251 expected: dict[str, Any] = {
252 "local_name": None,
253 "service_uuids": [],
254 "service_data": {},
255 "manufacturer_data": {},
256 "tx_power": None,
257 }
258
259 for _ in range(rng.randint(0, 8)):
260 kind = rng.choice(list(_BUILDERS))
261 _BUILDERS[kind](rng, chunks, expected)
262
263 return b"".join(chunks), expected
264
265
266 def test_gap_fuzzer_constructive_round_trip() -> None:
267 """Well-formed adverts must parse back to exactly the values that built them.
268
269 The existing fuzzers only assert the parser does not crash; this one asserts
270 output correctness. A regression in UUID byte order, service-data slicing,
271 manufacturer-id decode, or tx-power sign-folding would change a parsed field
272 away from the value the encoder put in, and fail here.
273 """
274 seed = int(os.environ.get("FUZZ_SEED", random.randrange(2**64)))
275 print(f"constructive fuzz seed: {seed:#x}")
276 rng = random.Random(seed)
277 for _ in range(_FUZZ_ITERATIONS):
278 gap_bytes, expected = _build_random_advertisement(rng)
279 local_name, service_uuids, service_data, manufacturer_data, tx_power = (
280 parse_advertisement_data_bytes(gap_bytes)
281 )
282 assert local_name == expected["local_name"]
283 assert service_uuids == expected["service_uuids"]
284 assert service_data == expected["service_data"]
285 assert manufacturer_data == expected["manufacturer_data"]
286 assert tx_power == expected["tx_power"]
287
288 # The same payload split across a multi-chunk tuple must agree, since
289 # the tuple path joins before delegating to the bytes parser.
290 adv = parse_advertisement_data((gap_bytes,))
291 assert adv.local_name == expected["local_name"]
292 assert adv.service_uuids == expected["service_uuids"]
293 assert adv.service_data == expected["service_data"]
294 assert adv.manufacturer_data == expected["manufacturer_data"]
295 assert adv.tx_power == expected["tx_power"]