Skip to content

parse() / load() silently decode invalid UTF-8 bytes as latin-1 instead of raising #720

Backlog

Description

@8eoyw

Description

When given bytes (via tomlkit.parse, tomlkit.loads, or tomlkit.load on a file opened in binary mode), tomlkit falls back to latin-1 if the input is not valid UTF-8. Invalid documents are accepted and produce mojibake instead of an error.

The TOML spec requires documents to be valid UTF-8, and tomllib / tomli raise UnicodeDecodeError for the same input.

Reproduction

import io, tomllib, tomlkit

data = b'a = "\xff"\n'
tomlkit.parse(data)             # {'a': 'ÿ'}
tomllib.load(io.BytesIO(data))  # UnicodeDecodeError

tomlkit 0.15.3, Python 3.13.

Cause

Parser.__init__ calls tomlkit._compat.decode(), which tries ["utf-8", "latin1", "ascii"] in order. Since latin-1 accepts any byte sequence, decoding never fails.

The toml-test invalid/encoding/* cases don't catch this because test_invalid_encode opens the files in text mode (encoding="utf-8"), so Python raises before tomlkit sees the data. With the files opened in "rb", the 6 invalid/encoding/bad-* cases are accepted.

Possible fix

Decode bytes strictly as UTF-8 in Parser.__init__, and add a binary-mode variant of test_invalid_encode. I have a small patch for this (a few lines in parser.py plus the test), and the full test suite passes with it.

Before opening a PR, I wanted to check:

  • Is the latin-1 fallback intentional, e.g. kept for backward compatibility?
  • Should invalid input raise UnicodeDecodeError (as tomllib does) or a TOMLKitError subclass?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions