From 9d0000b8b9b102ae4923a7ecdf7e447583a0a3a0 Mon Sep 17 00:00:00 2001 From: Yshuro Date: Tue, 24 Nov 2026 16:48:31 +0100 Subject: [PATCH] fix: decode bytes strictly as UTF-8 when parsing Decode bytes input strictly as UTF-8 in Parser.__init__ instead of falling back to latin-1, ensuring invalid UTF-8 bytes raise UnicodeDecodeError in parse(), loads(), and load(). Fixes #720 Signed-off-by: Yshuro --- tests/test_api.py | 20 ++++++++++++++++++++ tests/test_toml_tests.py | 9 +++++++++ tomlkit/parser.py | 6 ++++-- 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/tests/test_api.py b/tests/test_api.py index 0dd1a233..b398194a 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -884,3 +884,23 @@ def test_parse_dotted_key_with_subsequent_key_at_nesting_limit() -> None: # Inside table doc_table = tomlkit.parse(f"[t]\n{key} = 1\na.b = 2\n") assert doc_table["t"]["a"]["b"] == 2 + + +def test_parse_bytes_invalid_utf8_raises() -> None: + data = b'a = "\xff"\n' + with pytest.raises(UnicodeDecodeError): + parse(data) + + with pytest.raises(UnicodeDecodeError): + loads(data) + + with pytest.raises(UnicodeDecodeError): + load(io.BytesIO(data)) + + +def test_parse_bytes_valid_utf8() -> None: + data = b'a = "\xc3\xa9"\n' + doc = parse(data) + assert doc["a"] == "\xe9" + assert loads(data)["a"] == "\xe9" + assert load(io.BytesIO(data))["a"] == "\xe9" diff --git a/tests/test_toml_tests.py b/tests/test_toml_tests.py index 2eba2a21..daa78083 100644 --- a/tests/test_toml_tests.py +++ b/tests/test_toml_tests.py @@ -166,3 +166,12 @@ def test_invalid_encode(toml11_invalid_encode_case: str) -> None: with open(toml11_invalid_encode_case, encoding="utf-8") as f: with pytest.raises((TOMLKitError, UnicodeDecodeError)): load(f) + + +@pytest.mark.parametrize( + "toml11_invalid_encode_case", INVALID_ENCODE_CASES, ids=INVALID_ENCODE_IDS +) +def test_invalid_encode_bytes(toml11_invalid_encode_case: str) -> None: + with open(toml11_invalid_encode_case, "rb") as f: + with pytest.raises((TOMLKitError, UnicodeDecodeError)): + load(f) diff --git a/tomlkit/parser.py b/tomlkit/parser.py index 4ca7bc94..8654c2f5 100644 --- a/tomlkit/parser.py +++ b/tomlkit/parser.py @@ -7,7 +7,6 @@ from typing import Any from typing import Callable -from tomlkit._compat import decode from tomlkit._utils import RFC_3339_LOOSE from tomlkit._utils import _escaped from tomlkit._utils import parse_rfc3339 @@ -102,7 +101,10 @@ class Parser: def __init__(self, string: str | bytes) -> None: # Input to parse - self._src = Source(decode(string)) + if isinstance(string, bytes): + string = string.decode("utf-8") + + self._src = Source(string) self._aot_stack: list[Key] = [] self._nesting_depth = 0