Skip to content

read_po raises IndexError for a negative msgstr[N] index, even with abort_invalid=True #1534

Backlog

Description

@Kevin-Youngg

Overview Description

A negative plural index such as msgstr[-3] is never rejected.

  1. PoFileParser._process_keyword_line() parses the index with int(), which accepts a minus sign (pofile.py#L275-L276):

    kwarg, has_bracket, idxarg = keyword.partition('[')
    idx = int(idxarg[:-1]) if has_bracket else 0
  2. _add_message() checks only the upper bound and then uses the index on a list of length num_plurals (pofile.py#L196-L205):

    string = ['' for _ in range(self.catalog.num_plurals)]
    for idx, translation in sorted(self.translations):
        if idx >= self.catalog.num_plurals:
            self._invalid_pofile(...)
            continue
        string[idx] = translation.denormalize()

Because Python counts negative list indexes from the end, there are two outcomes:

  • -num_plurals <= idx <= -1 is accepted silently and fills another plural form (msgstr[-1] becomes msgstr[1] when nplurals=2);
  • idx < -num_plurals raises a bare IndexError, also with abort_invalid=True, where PoFileError is expected.

Steps to Reproduce

import io

from babel.messages.pofile import read_po

po = b'''msgid ""
msgstr ""
"Plural-Forms: nplurals=2; plural=(n != 1);\\n"

msgid "apple"
msgid_plural "apples"
msgstr[0] "x"
msgstr[-3] "y"
'''
read_po(io.BytesIO(po), abort_invalid=True)

Actual Results

Traceback (most recent call last):
  File "babel_negative_msgstr_index.py", line 14, in <module>
    read_po(io.BytesIO(po), abort_invalid=True)
  File ".../babel/messages/pofile.py", line 438, in read_po
    parser.parse(fileobj)
  File ".../babel/messages/pofile.py", line 365, in parse
    self._finish_current_message()
  File ".../babel/messages/pofile.py", line 238, in _finish_current_message
    self._add_message()
  File ".../babel/messages/pofile.py", line 205, in _add_message
    string[idx] = translation.denormalize()
IndexError: list assignment index out of range

Without abort_invalid the result is the same.

An index from -nplurals to -1 does not raise, but it is not reported either, while a too-large index is:

import io

from babel.messages.pofile import read_po

HEADER = '''msgid ""
msgstr ""
"Plural-Forms: nplurals=2; plural=(n != 1);\\n"

msgid "apple"
msgid_plural "apples"
'''

for entry in ('msgstr[0] "x"\nmsgstr[-1] "y"\n',
              'msgstr[0] "x"\nmsgstr[1] "y"\nmsgstr[-1] "z"\n',
              'msgstr[0] "x"\nmsgstr[5] "y"\n'):
    print("---", entry.replace("\n", "  ").strip())
    catalog = read_po(io.BytesIO((HEADER + entry).encode()))
    print(catalog["apple"].string)
--- msgstr[0] "x"  msgstr[-1] "y"
('x', 'y')
--- msgstr[0] "x"  msgstr[1] "y"  msgstr[-1] "z"
('x', 'y')
--- msgstr[0] "x"  msgstr[5] "y"
WARNING: msg has more translations than num_plurals of catalog
WARNING: Problem on line 5: ''
('x', '')

msgstr[-1] is used as index 1 without a warning. In the second case "z" is written first (the translations are sorted by index) and then overwritten by msgstr[1], also without a warning.

Expected Results

A negative index is invalid in the same way as an index >= nplurals: report it through _invalid_pofile() (warning, or PoFileError with abort_invalid=True). For example (the warning text may then need rewording):

--- a/babel/messages/pofile.py
+++ b/babel/messages/pofile.py
@@ -195,7 +195,7 @@
             msgid = tuple(m.denormalize() for m in self.messages)
             string = ['' for _ in range(self.catalog.num_plurals)]
             for idx, translation in sorted(self.translations):
-                if idx >= self.catalog.num_plurals:
+                if idx < 0 or idx >= self.catalog.num_plurals:
                     self._invalid_pofile(
                         "",
                         self.offset,

Reproducibility

Always. Reproduced on babel 2.19.0 and on master (3a7d239), Python 3.13.7, Linux.

Additional Information

  1. Related issues: Unhandled ValueError raised in read_po #1209 / PR Handle invalid plural index in msgstr[...] instead of raising ValueError (#1209) #1279 handle a non-integer index (int() raising ValueError); a negative integer still passes there. num_plurals checker is toothless on parsed pofiles #1323 discusses what to do with too-large indexes.
  2. Disclosure: found by fuzzing read_po with Atheris harnesses from an automatic harness generator.

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