Skip to content

Commit aceae77

Browse files
authored
gh-161808: Raise SyntaxError for unsupported ElementPath tokens (GH-161810)
ElementPath currently leaks a KeyError when a path contains a token that cannot start a supported XPath step, such as @, =, or ). Check the token's handler before calling it and raise SyntaxError("invalid path") when none exists. Keep the C accelerator's literal tag fast path unchanged. This addresses the exception leak described in the issue without changing which paths the accelerator delegates to ElementPath. The regression test covers find(), findall(), findtext(), and iterfind() on both Element and ElementTree objects. The shared test suite runs it with both the Python implementation and the C accelerator. Paths starting with ./ ensure that the accelerator also delegates these cases to ElementPath. Fixes #161808
1 parent cffc305 commit aceae77

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎Lib/test/test_xml_etree.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4069,6 +4069,19 @@ def test_bad_find(self):
40694069
with self.assertRaisesRegex(SyntaxError, 'cannot use absolute path'):
40704070
e.findall('/tag')
40714071

4072+
def test_find_invalid_path(self):
4073+
e = ET.XML(SAMPLE_XML)
4074+
paths = ('@', './x=y', './(', './)', './]', './!=', './::',
4075+
'./()', "./'tag'", './"tag"', 'tag/@')
4076+
for obj in (e, ET.ElementTree(e)):
4077+
for method in ('find', 'findall', 'findtext', 'iterfind'):
4078+
for path in paths:
4079+
with self.subTest(type=type(obj).__name__,
4080+
method=method, path=path):
4081+
self.assertRaisesRegex(
4082+
SyntaxError, '^invalid path$',
4083+
getattr(obj, method), path)
4084+
40724085
def test_find_through_ElementTree(self):
40734086
e = ET.XML(SAMPLE_XML)
40744087
self.assertEqual(ET.ElementTree(e).find('tag').tag, 'tag')

‎Lib/xml/etree/ElementPath.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,8 +387,11 @@ def iterfind(elem, path, namespaces=None):
387387
return
388388
selector = []
389389
while 1:
390+
prepare = ops.get(token[0])
391+
if prepare is None:
392+
raise SyntaxError("invalid path") from None
390393
try:
391-
selector.append(ops[token[0]](next, token))
394+
selector.append(prepare(next, token))
392395
except StopIteration:
393396
raise SyntaxError("invalid path") from None
394397
try:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Raise :exc:`SyntaxError` instead of :exc:`KeyError` for unsupported XPath
2+
tokens in :mod:`xml.etree.ElementTree` path searches.

0 commit comments

Comments
 (0)