| 1 |
"""Property-based tests using Hypothesis. |
| 2 |
|
| 3 |
The UTS #46 conformance suite covers known-answer cases; these tests explore |
| 4 |
the input space for the failure class behind CVE-2024-3651 and |
| 5 |
CVE-2026-45409 ("pathological input causes unexpected behaviour"). Each |
| 6 |
property asserts an invariant that must hold for *any* input: the only |
| 7 |
exception the public API raises is :class:`idna.IDNAError`, successful |
| 8 |
output is well-formed, and the several routes to the same operation agree. |
| 9 |
|
| 10 |
Set ``HYPOTHESIS_PROFILE=thorough`` to run 10,000 examples per property. |
| 11 |
""" |
| 12 |
|
| 13 |
from __future__ import annotations |
| 14 |
|
| 15 |
import codecs |
| 16 |
import os |
| 17 |
import unicodedata |
| 18 |
import unittest |
| 19 |
import warnings |
| 20 |
from typing import Any, Callable |
| 21 |
|
| 22 |
from hypothesis import HealthCheck, example, given, settings |
| 23 |
from hypothesis import strategies as st |
| 24 |
|
| 25 |
import idna |
| 26 |
import idna.codec # registers the "idna2008" codec |
| 27 |
from idna.intranges import intranges_contain, intranges_from_list |
| 28 |
|
| 29 |
settings.register_profile("idna", deadline=None, print_blob=True) |
| 30 |
settings.register_profile( |
| 31 |
"thorough", |
| 32 |
max_examples=10_000, |
| 33 |
deadline=None, |
| 34 |
print_blob=True, |
| 35 |
suppress_health_check=[HealthCheck.too_slow], |
| 36 |
) |
| 37 |
settings.load_profile(os.environ.get("HYPOTHESIS_PROFILE", "idna")) |
| 38 |
|
| 39 |
|
| 40 |
# --- Strategies ------------------------------------------------------------ |
| 41 |
|
| 42 |
# Characters that exercise the interesting rules in RFC 5891-5893 and |
| 43 |
# UTS #46: label separators, joiners, combining marks, contextual-rule |
| 44 |
# codepoints, hyphens/digits, "xn--" prefixes, and full-width/case variants. |
| 45 |
_interesting = st.sampled_from( |
| 46 |
"abcxyzABCXYZ0189-_ " |
| 47 |
"xn--" |
| 48 |
".。.。" # label separators |
| 49 |
"" # ZWNJ, ZWJ (CONTEXTJ) |
| 50 |
"्̀̈ํ" # combining marks / virama |
| 51 |
"·͵・" # CONTEXTO: middle dot, keraia, katakana middle dot |
| 52 |
"αςбяकम中文カタひ" # sample letters |
| 53 |
"ßẞσÅÅfi①A" # UTS #46 mapped/deviation chars |
| 54 |
"\U0001d400\U0001f600" # supplementary plane |
| 55 |
) |
| 56 |
_bidi_range = st.characters(min_codepoint=0x0590, max_codepoint=0x08FF) # RTL scripts, for bidi rules |
| 57 |
_any_char = st.characters(exclude_categories=()) # includes surrogates and unassigned codepoints |
| 58 |
|
| 59 |
_label = st.text(alphabet=st.one_of(_interesting, _bidi_range, _any_char, st.characters()), max_size=70) |
| 60 |
_structured_domain = st.lists(_label, max_size=6).map(".".join) |
| 61 |
_free_text = st.text(alphabet=st.one_of(_any_char, st.characters()), max_size=300) |
| 62 |
_over_long = st.text(min_size=1000, max_size=1100) |
| 63 |
|
| 64 |
domains = st.one_of(_structured_domain, _free_text, _over_long) |
| 65 |
labels = st.text(alphabet=st.one_of(_interesting, _bidi_range, st.characters()), max_size=100) |
| 66 |
ascii_domains = st.text(alphabet=st.characters(max_codepoint=0x7F), max_size=300) |
| 67 |
binary = st.binary(max_size=300) |
| 68 |
flags = st.booleans() |
| 69 |
_STD3_ASCII = frozenset("abcdefghijklmnopqrstuvwxyz0123456789-.") |
| 70 |
|
| 71 |
|
| 72 |
def _run(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> tuple[Any, idna.IDNAError | None]: |
| 73 |
"""Return ``(result, None)`` or ``(None, error)``, letting anything else propagate.""" |
| 74 |
with warnings.catch_warnings(): |
| 75 |
# transitional=True is deprecated but still exercised deliberately. |
| 76 |
warnings.simplefilter("ignore", DeprecationWarning) |
| 77 |
try: |
| 78 |
return fn(*args, **kwargs), None |
| 79 |
except idna.IDNAError as err: |
| 80 |
return None, err |
| 81 |
|
| 82 |
|
| 83 |
class OnlyIDNAErrorTests(unittest.TestCase): |
| 84 |
"""The public API never raises anything except ``IDNAError`` for any input.""" |
| 85 |
|
| 86 |
@given(domains, flags, flags, flags, flags) |
| 87 |
def test_encode(self, s: str, strict: bool, uts46: bool, std3_rules: bool, transitional: bool) -> None: |
| 88 |
_run(idna.encode, s, strict=strict, uts46=uts46, std3_rules=std3_rules, transitional=transitional) |
| 89 |
|
| 90 |
@given(st.one_of(domains, binary), flags, flags, flags, flags) |
| 91 |
def test_decode(self, s: str | bytes, strict: bool, uts46: bool, std3_rules: bool, display: bool) -> None: |
| 92 |
_run(idna.decode, s, strict=strict, uts46=uts46, std3_rules=std3_rules, display=display) |
| 93 |
|
| 94 |
@given(domains, flags, flags) |
| 95 |
def test_uts46_remap(self, s: str, std3_rules: bool, transitional: bool) -> None: |
| 96 |
_run(idna.uts46_remap, s, std3_rules=std3_rules, transitional=transitional) |
| 97 |
|
| 98 |
@given(labels) |
| 99 |
def test_label_helpers(self, label: str) -> None: |
| 100 |
for fn in ( |
| 101 |
idna.alabel, |
| 102 |
idna.ulabel, |
| 103 |
idna.check_label, |
| 104 |
idna.check_bidi, |
| 105 |
idna.check_hyphen_ok, |
| 106 |
idna.check_initial_combiner, |
| 107 |
idna.check_nfc, |
| 108 |
idna.valid_label_length, |
| 109 |
): |
| 110 |
_run(fn, label) |
| 111 |
_run(idna.ulabel, label.encode("utf-8", "surrogatepass")) |
| 112 |
|
| 113 |
@given(st.one_of(domains, binary), flags) |
| 114 |
def test_codec(self, s: str | bytes, final: bool) -> None: |
| 115 |
if isinstance(s, str): |
| 116 |
_run(s.encode, "idna2008") |
| 117 |
_run(codecs.getincrementalencoder("idna2008")().encode, s, final) |
| 118 |
else: |
| 119 |
_run(s.decode, "idna2008") |
| 120 |
_run(codecs.getincrementaldecoder("idna2008")().decode, s, final) |
| 121 |
|
| 122 |
|
| 123 |
class OutputShapeTests(unittest.TestCase): |
| 124 |
@given(domains, flags, flags, flags) |
| 125 |
def test_encode_output_is_bounded_ascii(self, s: str, strict: bool, uts46: bool, std3_rules: bool) -> None: |
| 126 |
result, err = _run(idna.encode, s, strict=strict, uts46=uts46, std3_rules=std3_rules) |
| 127 |
if err is not None: |
| 128 |
return |
| 129 |
self.assertIsInstance(result, bytes) |
| 130 |
result.decode("ascii") |
| 131 |
self.assertLessEqual(len(result), 254) |
| 132 |
for label in result.rstrip(b".").split(b"."): |
| 133 |
self.assertTrue(0 < len(label) <= 63) |
| 134 |
|
| 135 |
@given(domains, flags, flags) |
| 136 |
def test_uts46_remap_output_is_nfc_and_idempotent(self, s: str, std3_rules: bool, transitional: bool) -> None: |
| 137 |
out, err = _run(idna.uts46_remap, s, std3_rules=std3_rules, transitional=transitional) |
| 138 |
if err is not None: |
| 139 |
return |
| 140 |
self.assertTrue(unicodedata.is_normalized("NFC", out)) |
| 141 |
again, _ = _run(idna.uts46_remap, out, std3_rules=std3_rules, transitional=transitional) |
| 142 |
self.assertEqual(again, out) |
| 143 |
if std3_rules: |
| 144 |
# UTS #46 §4.1 UseSTD3ASCIIRules: only LDH ASCII (plus the label |
| 145 |
# separator) may survive mapping. |
| 146 |
self.assertTrue(all(c in _STD3_ASCII for c in out if c.isascii()), out) |
| 147 |
else: |
| 148 |
# Turning the rules on must never change a result, only reject it. |
| 149 |
strict, err = _run(idna.uts46_remap, s, std3_rules=True, transitional=transitional) |
| 150 |
self.assertTrue(err is not None or strict == out) |
| 151 |
|
| 152 |
|
| 153 |
class RoundTripTests(unittest.TestCase): |
| 154 |
@given(domains, flags, flags) |
| 155 |
def test_encode_decode_encode(self, s: str, uts46: bool, std3_rules: bool) -> None: |
| 156 |
encoded, err = _run(idna.encode, s, uts46=uts46, std3_rules=std3_rules) |
| 157 |
if err is not None: |
| 158 |
return |
| 159 |
decoded = idna.decode(encoded) # anything encode() produced must decode |
| 160 |
# ulabel() lowercases ASCII labels while alabel() preserves case, so the |
| 161 |
# round trip is exact only up to ASCII case. |
| 162 |
self.assertEqual(idna.encode(decoded), encoded.lower()) |
| 163 |
# display=True only changes behaviour for labels that fail to decode |
| 164 |
self.assertEqual(idna.decode(encoded, display=True), decoded) |
| 165 |
|
| 166 |
@given(ascii_domains) |
| 167 |
@example("xn---bbk.example") |
| 168 |
@example("a" * 64) |
| 169 |
def test_decode_encode(self, s: str) -> None: |
| 170 |
# RFC 5891 §5.3: an A-label that decodes must re-encode to itself, so |
| 171 |
# any ASCII input that decodes is (up to case) its own encoding. |
| 172 |
# Restricted to strict, non-UTS46 processing since other modes may |
| 173 |
# legitimately rewrite the input, and to labels within the DNS |
| 174 |
# length limit, which decode() (like UTS #46 ToUnicode) does not |
| 175 |
# enforce but encode() does. |
| 176 |
decoded, err = _run(idna.decode, s, strict=True) |
| 177 |
if err is not None or any(len(label) > 63 for label in s.split(".")): |
| 178 |
return |
| 179 |
self.assertEqual(idna.encode(decoded, strict=True), s.lower().encode("ascii")) |
| 180 |
|
| 181 |
@given(labels) |
| 182 |
def test_alabel_ulabel(self, label: str) -> None: |
| 183 |
encoded, err = _run(idna.alabel, label) |
| 184 |
if err is not None: |
| 185 |
return |
| 186 |
self.assertEqual(idna.alabel(idna.ulabel(encoded)), encoded.lower()) |
| 187 |
|
| 188 |
|
| 189 |
class DifferentialTests(unittest.TestCase): |
| 190 |
"""Different routes to the same operation must agree.""" |
| 191 |
|
| 192 |
@staticmethod |
| 193 |
def _assert_same_outcome(test: unittest.TestCase, a: tuple[Any, Any], b: tuple[Any, Any]) -> None: |
| 194 |
(a_result, a_err), (b_result, b_err) = a, b |
| 195 |
test.assertEqual(a_err is None, b_err is None, f"{a_err!r} vs {b_err!r}") |
| 196 |
test.assertEqual(a_result, b_result) |
| 197 |
|
| 198 |
@given(domains, flags) |
| 199 |
def test_transitional_has_no_effect(self, s: str, std3_rules: bool) -> None: |
| 200 |
# UTS #46 deprecated transitional processing; the flag is accepted |
| 201 |
# for backwards compatibility but deviation characters are kept |
| 202 |
# either way. |
| 203 |
self._assert_same_outcome( |
| 204 |
self, |
| 205 |
_run(idna.uts46_remap, s, std3_rules=std3_rules, transitional=True), |
| 206 |
_run(idna.uts46_remap, s, std3_rules=std3_rules), |
| 207 |
) |
| 208 |
self._assert_same_outcome( |
| 209 |
self, |
| 210 |
_run(idna.encode, s, uts46=True, std3_rules=std3_rules, transitional=True), |
| 211 |
_run(idna.encode, s, uts46=True, std3_rules=std3_rules), |
| 212 |
) |
| 213 |
|
| 214 |
@given(ascii_domains) |
| 215 |
def test_strict_is_irrelevant_for_ascii(self, s: str) -> None: |
| 216 |
self._assert_same_outcome(self, _run(idna.encode, s, strict=True), _run(idna.encode, s, strict=False)) |
| 217 |
self._assert_same_outcome(self, _run(idna.decode, s, strict=True), _run(idna.decode, s, strict=False)) |
| 218 |
|
| 219 |
@given(domains) |
| 220 |
def test_codec_encode_matches_core(self, s: str) -> None: |
| 221 |
if not s: |
| 222 |
return # the codec short-circuits empty input where core raises "Empty domain" |
| 223 |
self._assert_same_outcome(self, _run(s.encode, "idna2008"), _run(idna.encode, s)) |
| 224 |
|
| 225 |
@given(binary) |
| 226 |
def test_codec_decode_matches_core(self, b: bytes) -> None: |
| 227 |
if not b: |
| 228 |
return |
| 229 |
self._assert_same_outcome(self, _run(b.decode, "idna2008"), _run(idna.decode, b)) |
| 230 |
|
| 231 |
@given(domains, st.lists(st.integers(min_value=0, max_value=300), max_size=8)) |
| 232 |
def test_incremental_encoder_matches_one_shot(self, s: str, cuts: list[int]) -> None: |
| 233 |
if not s: |
| 234 |
return # see test_codec_encode_matches_core |
| 235 |
one_shot, err = _run(idna.encode, s) |
| 236 |
encoder = codecs.getincrementalencoder("idna2008")() |
| 237 |
chunks = _split(s, cuts) |
| 238 |
|
| 239 |
def incremental() -> bytes: |
| 240 |
out = b"".join(encoder.encode(chunk) for chunk in chunks) |
| 241 |
return out + encoder.encode("", final=True) |
| 242 |
|
| 243 |
self._assert_same_outcome(self, (one_shot, err), _run(incremental)) |
| 244 |
|
| 245 |
@given(binary, st.lists(st.integers(min_value=0, max_value=300), max_size=8)) |
| 246 |
def test_incremental_decoder_matches_one_shot(self, b: bytes, cuts: list[int]) -> None: |
| 247 |
if not b: |
| 248 |
return # see test_codec_decode_matches_core |
| 249 |
one_shot, err = _run(idna.decode, b) |
| 250 |
decoder = codecs.getincrementaldecoder("idna2008")() |
| 251 |
chunks = _split(b, cuts) |
| 252 |
|
| 253 |
def incremental() -> str: |
| 254 |
out = "".join(decoder.decode(chunk) for chunk in chunks) |
| 255 |
return out + decoder.decode(b"", final=True) |
| 256 |
|
| 257 |
self._assert_same_outcome(self, (one_shot, err), _run(incremental)) |
| 258 |
|
| 259 |
|
| 260 |
def _split(data: Any, cuts: list[int]) -> list[Any]: |
| 261 |
"""Split ``data`` at the given (unordered, possibly repeated) offsets.""" |
| 262 |
points = [0, *sorted(min(c, len(data)) for c in cuts), len(data)] |
| 263 |
return [data[i:j] for i, j in zip(points, points[1:])] |
| 264 |
|
| 265 |
|
| 266 |
class IntrangesTests(unittest.TestCase): |
| 267 |
@given(st.sets(st.integers(min_value=0, max_value=0x10FFFF)), st.integers(min_value=0, max_value=0x10FFFF)) |
| 268 |
def test_membership_matches_set(self, members: set[int], probe: int) -> None: |
| 269 |
ranges = intranges_from_list(sorted(members)) |
| 270 |
self.assertEqual(intranges_contain(probe, ranges), probe in members) |
| 271 |
for member in members: |
| 272 |
self.assertTrue(intranges_contain(member, ranges)) |