Debian Codegraph @

tests/test_idna_fuzz_targets.py

raw
1 """Smoke-test the OSS-Fuzz harnesses (``tests/fuzz_*.py``) without libFuzzer.
2
3 The real fuzzers need ``atheris`` (and a libFuzzer-capable clang) to run.
4 Here a minimal stand-in for the parts of ``atheris`` the harnesses use is
5 installed into ``sys.modules`` and each ``TestOneInput`` is driven with
6 pseudo-random bytes. This catches harnesses that fall out of step with the
7 library API long before OSS-Fuzz reports a build or run failure.
8 """
9
10 from __future__ import annotations
11
12 import contextlib
13 import importlib.util
14 import random
15 import sys
16 import types
17 import unittest
18 from pathlib import Path
19 from typing import Any, Callable
20 from unittest import mock
21
22 TARGETS = sorted(Path(__file__).resolve().parent.glob("fuzz_*.py"))
23 ITERATIONS = 2000
24
25 # Well-formed inputs are vanishingly rare in random bytes, so half the
26 # iterations splice one of these behind a random header to reach the
27 # harnesses' success-path assertions (round trips, idempotence, ...).
28 SEEDS = [
29 b"example.com",
30 b"ExAmPlE.COM.",
31 b"a-b.c1.d",
32 "пример.рф".encode(),
33 b"xn--e1afmkfd.xn--p1ai",
34 "παράδειγμα.δοκιμή".encode(),
35 "उदाहरण.परीक्षा".encode(),
36 "例え.テスト".encode(),
37 "bücher.example".encode(),
38 "Faß.de".encode(),
39 "a\u200cb.example".encode(),
40 b"xn--.example",
41 b"-hyphen.example",
42 b"xn--80ak6aa92e.com",
43 b"xn---bbk.example", # non-canonical spelling of xn--bbk
44 b"XN--MNCHEN-3YA.example",
45 ]
46
47
48 class _FuzzedDataProvider:
49 """Just enough of ``atheris.FuzzedDataProvider`` for the harnesses."""
50
51 def __init__(self, data: bytes) -> None:
52 self._data = data
53 self._pos = 0
54
55 def _take(self, n: int) -> bytes:
56 chunk = self._data[self._pos : self._pos + n]
57 self._pos += len(chunk)
58 return chunk
59
60 def ConsumeBool(self) -> bool:
61 return bool(self._take(1)[0] & 1) if self._pos < len(self._data) else False
62
63 def ConsumeIntInRange(self, low: int, high: int) -> int:
64 raw = self._take(4)
65 return low + (int.from_bytes(raw, "little") % (high - low + 1)) if raw else low
66
67 def ConsumeBytes(self, count: int) -> bytes:
68 return self._take(count)
69
70 def ConsumeUnicode(self, count: int) -> str:
71 return self._take(count).decode("utf-8", "surrogatepass" if self.ConsumeBool() else "replace")
72
73
74 def _fake_atheris() -> types.ModuleType:
75 module = types.ModuleType("atheris")
76 module.__dict__.update(
77 FuzzedDataProvider=_FuzzedDataProvider,
78 instrument_imports=contextlib.nullcontext,
79 Setup=lambda *args, **kwargs: None,
80 Fuzz=lambda *args, **kwargs: None,
81 )
82 return module
83
84
85 def _load(path: Path) -> Callable[[bytes], Any]:
86 with mock.patch.dict(sys.modules, {"atheris": _fake_atheris()}):
87 spec = importlib.util.spec_from_file_location(path.stem, path)
88 assert spec is not None and spec.loader is not None
89 module = importlib.util.module_from_spec(spec)
90 spec.loader.exec_module(module)
91 return module.TestOneInput # type: ignore[no-any-return]
92
93
94 class FuzzTargetSmokeTests(unittest.TestCase):
95 def test_targets_survive_random_input(self) -> None:
96 rng = random.Random(0)
97 for path in TARGETS:
98 with self.subTest(target=path.name):
99 test_one_input = _load(path)
100 for i in range(ITERATIONS):
101 data = rng.randbytes(rng.randrange(0, 200))
102 if i % 2:
103 data = rng.randbytes(rng.randrange(4, 12)) + rng.choice(SEEDS)
104 test_one_input(data)
105
106
107 if __name__ == "__main__":
108 unittest.main()