From 132db1b37c49aa5cf9c5386d2111a193707bbf08 Mon Sep 17 00:00:00 2001 From: iefa m Date: Sat, 21 Nov 2026 16:49:11 +0530 Subject: [PATCH] reject out-of-range start offsets in parse() parse() passed the caller's start straight to Parser(s, pos=start), and the generated parser only compares pos against self.end, so a position below zero or past the length got through. A negative offset became ordinary Python negative indexing, so parse('012', start=-2) read off the end of the string, wrapped round to the front and returned 12012; a start past the end let _err_str index msg[errpos] out of range and raised IndexError out of parse(), loads() and load(). Check start against the input length next to the existing empty-string guard and return the usual error tuple, so loads() and load() report it as the ValueError they document. --- json5/lib.py | 2 ++ tests/lib_test.py | 10 ++++++++++ 2 files changed, 12 insertions(+) diff --git a/json5/lib.py b/json5/lib.py index ecf375a..d8a1de4 100644 --- a/json5/lib.py +++ b/json5/lib.py @@ -349,6 +349,8 @@ def parse( if not s: return None, 'Empty strings are not legal JSON5', 0 start = start or 0 + if not 0 <= start <= len(s): + return None, f'Invalid start position {start}', 0 parser = Parser(s, '', pos=start) ast, err, pos = parser.parse( global_vars={'_strict': strict, '_consume_trailing': consume_trailing} diff --git a/tests/lib_test.py b/tests/lib_test.py index fa85e7e..8487614 100644 --- a/tests/lib_test.py +++ b/tests/lib_test.py @@ -549,6 +549,16 @@ def test_parse_empty_input(self): (None, 'Empty strings are not legal JSON5', 0), ) + def test_parse_invalid_start(self): + # A negative start indexes the string from the end and a start past + # the end indexes off it; neither is an offset into the document. + for source, start in (('012', -2), ('012', 4)): + with self.subTest(source=source, start=start): + self.assertEqual( + json5.parse(source, start=start), + (None, f'Invalid start position {start}', 0), + ) + def test_parse(self): self.check('4', 4, err=None, pos=1) self.check('4 ', 4, err=None, pos=2)