Skip to content

Commit 7419cc1

Browse files
[3.14] gh-156812: Check structural rules when serializing in xml.dom.minidom (GH-161830) (GH-162681)
Only the structure is checked, not the characters. A comment ending with '-' was fused with the closing '-->' into '--->'. A processing instruction was not checked at all: '?>' in the data silently closed it, and the reserved target 'xml' produced a document which cannot be parsed. The identifiers of the document type declaration were interpolated into single quotes without checks, so an identifier containing a quote or other illegal character produced XML which is not well-formed, and a public identifier without a system identifier produced the literal 'None'. (cherry picked from commit 79494e2)
1 parent 5548211 commit 7419cc1

4 files changed

Lines changed: 129 additions & 10 deletions

File tree

‎Doc/library/xml.dom.minidom.rst‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,13 @@ module documentation. This section lists the differences between the API and
151151
otherwise it is set to ``"no"``.
152152
Not stating the argument will omit the declaration from the document.
153153

154+
:exc:`ValueError` is raised if the content of the node cannot be
155+
represented in XML, for example if a comment contains ``"--"`` or
156+
a CDATA section contains ``"]]>"``.
157+
The characters are not checked:
158+
the text, the attribute values and the content of comments,
159+
processing instructions and CDATA sections are written as is.
160+
154161
.. versionchanged:: 3.8
155162
The :meth:`writexml` method now preserves the attribute order specified
156163
by the user.

‎Lib/test/test_minidom.py‎

Lines changed: 59 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2004,10 +2004,65 @@ def testDeepcopiedDocument(self):
20042004
doc2 = copy.deepcopy(doc)
20052005
self.assert_recursive_equal(doc, doc2)
20062006

2007-
def testSerializeCommentNodeWithDoubleHyphen(self):
2008-
doc = create_doc_without_doctype()
2009-
doc.appendChild(doc.createComment("foo--bar"))
2010-
self.assertRaises(ValueError, doc.toxml)
2007+
def testWriteXMLDoctypeIdentifiers(self):
2008+
impl = getDOMImplementation()
2009+
def serialize(publicId, systemId):
2010+
doctype = impl.createDocumentType("r", publicId, systemId)
2011+
return impl.createDocument(None, "r", doctype).toxml()[22:]
2012+
self.assertEqual(serialize(None, None), '<!DOCTYPE r><r/>')
2013+
self.assertEqual(serialize(None, "s"), "<!DOCTYPE r SYSTEM 's'><r/>")
2014+
self.assertEqual(serialize("p", "s"),
2015+
"<!DOCTYPE r PUBLIC 'p' 's'><r/>")
2016+
# the quote which is not in the literal is used
2017+
self.assertEqual(serialize("it's", "sys'tem"),
2018+
'<!DOCTYPE r PUBLIC "it\'s" "sys\'tem"><r/>')
2019+
# a system literal cannot contain both quotes
2020+
with self.assertRaisesRegex(ValueError, "both quotes"):
2021+
serialize(None, 'a"b\'c')
2022+
# a public identifier can only contain PubidChars
2023+
for publicId in ['pub"lic', 'p>', 'p<', 'p&', 'p[', '\xe9']:
2024+
with self.subTest(publicId=publicId):
2025+
with self.assertRaisesRegex(ValueError,
2026+
"invalid public identifier"):
2027+
serialize(publicId, "s")
2028+
# a public identifier is meaningless without a system identifier
2029+
with self.assertRaisesRegex(ValueError, "requires a system"):
2030+
serialize("p", None)
2031+
2032+
def testSerializeComment(self):
2033+
impl = getDOMImplementation()
2034+
def serialize(data):
2035+
doc = impl.createDocument(None, "r", None)
2036+
doc.documentElement.appendChild(doc.createComment(data))
2037+
return doc.toxml()[22:]
2038+
self.assertEqual(serialize("foo"), "<r><!--foo--></r>")
2039+
self.assertEqual(serialize(""), "<r><!----></r>")
2040+
self.assertEqual(serialize("-foo"), "<r><!---foo--></r>")
2041+
with self.assertRaisesRegex(ValueError, "'--' is not allowed"):
2042+
serialize("foo--bar")
2043+
# a trailing hyphen would be fused with the closing "-->"
2044+
with self.assertRaisesRegex(ValueError, "cannot end with"):
2045+
serialize("foo-")
2046+
2047+
def testSerializeProcessingInstruction(self):
2048+
impl = getDOMImplementation()
2049+
def serialize(target, data):
2050+
doc = impl.createDocument(None, "r", None)
2051+
pi = doc.createProcessingInstruction(target, data)
2052+
doc.documentElement.appendChild(pi)
2053+
return doc.toxml()[22:]
2054+
self.assertEqual(serialize("p", "a"), "<r><?p a?></r>")
2055+
self.assertEqual(serialize("p", ""), "<r><?p ?></r>")
2056+
self.assertEqual(serialize("xml-stylesheet", 'href="a"'),
2057+
'<r><?xml-stylesheet href="a"?></r>')
2058+
# "?>" would close the processing instruction
2059+
with self.assertRaisesRegex(ValueError, "'\\?>' is not allowed"):
2060+
serialize("p", "a?>b")
2061+
# the target "xml" is reserved
2062+
for target in ["xml", "XML", "XmL"]:
2063+
with self.subTest(target=target):
2064+
with self.assertRaisesRegex(ValueError, "reserved"):
2065+
serialize(target, "a")
20112066

20122067

20132068
def testEmptyXMLNSValue(self):

‎Lib/xml/dom/minidom.py‎

Lines changed: 53 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,27 @@ def __exit__(self, et, ev, tb):
285285
defproperty(Node, "localName", doc="Namespace-local name of this node.")
286286

287287

288+
# PubidChar (see XML 1.0, 2.3, [13]).
289+
_PUBID_CHARS = frozenset(
290+
" \r\n-'()+,./:=?;!*#@$_%"
291+
"0123456789"
292+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
293+
"abcdefghijklmnopqrstuvwxyz")
294+
295+
296+
def _quote_literal(text):
297+
"""Quote a system literal or a public identifier.
298+
299+
A literal is delimited with a quote which it does not contain
300+
(see XML 1.0, 2.3, [11] and [12]).
301+
"""
302+
if "'" not in text:
303+
return "'%s'" % text
304+
if '"' not in text:
305+
return '"%s"' % text
306+
raise ValueError("a literal cannot contain both quotes: %r" % (text,))
307+
308+
288309
def _append_child(self, node):
289310
# fast path with less checks; usable by DOM builders if careful
290311
childNodes = self.childNodes
@@ -1026,7 +1047,18 @@ def _set_nodeName(self, value):
10261047
nodeName = property(_get_nodeName, _set_nodeName)
10271048

10281049
def writexml(self, writer, indent="", addindent="", newl=""):
1029-
writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
1050+
target = self.target
1051+
# PITarget cannot match "xml" in any case (see XML 1.0, 2.6, [17]).
1052+
if target.lower() == "xml":
1053+
raise ValueError("%r is a reserved processing instruction target"
1054+
% (target,))
1055+
data = self.data
1056+
# The data cannot contain "?>", which ends the instruction
1057+
# (see XML 1.0, 2.6, [16]).
1058+
if "?>" in data:
1059+
raise ValueError("'?>' is not allowed in a processing "
1060+
"instruction node")
1061+
writer.write("%s<?%s %s?>%s" % (indent, target, data, newl))
10301062

10311063

10321064
class CharacterData(Childless, Node):
@@ -1221,9 +1253,14 @@ def __init__(self, data):
12211253
self._data = data
12221254

12231255
def writexml(self, writer, indent="", addindent="", newl=""):
1224-
if "--" in self.data:
1256+
data = self.data
1257+
# The data cannot contain "--", and cannot end with "-", which
1258+
# would be fused with the closing "-->" (see XML 1.0, 2.5, [15]).
1259+
if "--" in data:
12251260
raise ValueError("'--' is not allowed in a comment node")
1226-
writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1261+
if data.endswith("-"):
1262+
raise ValueError("a comment node cannot end with '-'")
1263+
writer.write("%s<!--%s-->%s" % (indent, data, newl))
12271264

12281265

12291266
class CDATASection(Text):
@@ -1369,10 +1406,20 @@ def writexml(self, writer, indent="", addindent="", newl=""):
13691406
writer.write("<!DOCTYPE ")
13701407
writer.write(self.name)
13711408
if self.publicId:
1372-
writer.write("%s PUBLIC '%s'%s '%s'"
1373-
% (newl, self.publicId, newl, self.systemId))
1409+
if not _PUBID_CHARS.issuperset(self.publicId):
1410+
raise ValueError("invalid public identifier: %r"
1411+
% (self.publicId,))
1412+
# ExternalID with a public identifier always includes
1413+
# a system identifier (see XML 1.0, 4.2.2, [75]).
1414+
if not self.systemId:
1415+
raise ValueError("a public identifier requires "
1416+
"a system identifier")
1417+
writer.write("%s PUBLIC %s%s %s"
1418+
% (newl, _quote_literal(self.publicId),
1419+
newl, _quote_literal(self.systemId)))
13741420
elif self.systemId:
1375-
writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
1421+
writer.write("%s SYSTEM %s" % (newl,
1422+
_quote_literal(self.systemId)))
13761423
if self.internalSubset is not None:
13771424
writer.write(" [")
13781425
writer.write(self.internalSubset)
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
Serializing a document type declaration, a comment or a processing
2+
instruction in :mod:`xml.dom.minidom` now checks the structural rules of XML.
3+
A system literal is now quoted with the quote which it does not contain,
4+
and :exc:`ValueError` is raised for an invalid public identifier,
5+
for a literal containing both quotes,
6+
for a public identifier without a system identifier,
7+
for a comment ending with ``-``,
8+
and for a processing instruction containing ``?>`` in the data
9+
or using the reserved target ``xml``.
10+
The characters are still not checked.

0 commit comments

Comments
 (0)