Skip to content

Commit 541cbc9

Browse files
[3.15] gh-156812: Check structural rules when serializing in xml.dom.minidom (GH-161830) (GH-162680)
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 0317d3e commit 541cbc9

4 files changed

Lines changed: 145 additions & 10 deletions

File tree

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

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,15 @@ module documentation. This section lists the differences between the API and
147147
otherwise it is set to ``"no"``.
148148
Not stating the argument will omit the declaration from the document.
149149

150+
:exc:`ValueError` is raised if the content of the node cannot be
151+
represented in XML, for example if a comment contains ``"--"`` or
152+
a CDATA section contains ``"]]>"``.
153+
The characters are not checked:
154+
the text, the attribute values and the content of comments,
155+
processing instructions and CDATA sections are written as is.
156+
If they can contain characters which are not allowed in XML,
157+
check them with :func:`xml.is_valid_text` before serialization.
158+
150159
.. versionchanged:: 3.8
151160
The :meth:`writexml` method now preserves the attribute order specified
152161
by the user.

‎Lib/test/test_minidom.py‎

Lines changed: 65 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2004,10 +2004,71 @@ 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")
2066+
# the target is a name
2067+
doc = impl.createDocument(None, "r", None)
2068+
pi = doc.createProcessingInstruction("p", "a")
2069+
doc.documentElement.appendChild(pi)
2070+
pi.target = "a b"
2071+
self.assertRaises(xml.dom.InvalidCharacterErr, doc.toxml)
20112072

20122073

20132074
def testEmptyXMLNSValue(self):

‎Lib/xml/dom/minidom.py‎

Lines changed: 61 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,33 @@ 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+
309+
def _check_name(name):
310+
if not xml.is_valid_name(name):
311+
raise xml.dom.InvalidCharacterErr(
312+
"%r is not a valid XML name" % (name,))
313+
314+
288315
def _append_child(self, node):
289316
# fast path with less checks; usable by DOM builders if careful
290317
childNodes = self.childNodes
@@ -1026,7 +1053,20 @@ def _set_nodeName(self, value):
10261053
nodeName = property(_get_nodeName, _set_nodeName)
10271054

10281055
def writexml(self, writer, indent="", addindent="", newl=""):
1029-
writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
1056+
target = self.target
1057+
# PITarget is a Name, except the names matching "xml" in any case
1058+
# (see XML 1.0, 2.6, [17]).
1059+
_check_name(target)
1060+
if target.lower() == "xml":
1061+
raise ValueError("%r is a reserved processing instruction target"
1062+
% (target,))
1063+
data = self.data
1064+
# The data cannot contain "?>", which ends the instruction
1065+
# (see XML 1.0, 2.6, [16]).
1066+
if "?>" in data:
1067+
raise ValueError("'?>' is not allowed in a processing "
1068+
"instruction node")
1069+
writer.write("%s<?%s %s?>%s" % (indent, target, data, newl))
10301070

10311071

10321072
class CharacterData(Childless, Node):
@@ -1221,9 +1261,14 @@ def __init__(self, data):
12211261
self._data = data
12221262

12231263
def writexml(self, writer, indent="", addindent="", newl=""):
1224-
if "--" in self.data:
1264+
data = self.data
1265+
# The data cannot contain "--", and cannot end with "-", which
1266+
# would be fused with the closing "-->" (see XML 1.0, 2.5, [15]).
1267+
if "--" in data:
12251268
raise ValueError("'--' is not allowed in a comment node")
1226-
writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1269+
if data.endswith("-"):
1270+
raise ValueError("a comment node cannot end with '-'")
1271+
writer.write("%s<!--%s-->%s" % (indent, data, newl))
12271272

12281273

12291274
class CDATASection(Text):
@@ -1369,10 +1414,20 @@ def writexml(self, writer, indent="", addindent="", newl=""):
13691414
writer.write("<!DOCTYPE ")
13701415
writer.write(self.name)
13711416
if self.publicId:
1372-
writer.write("%s PUBLIC '%s'%s '%s'"
1373-
% (newl, self.publicId, newl, self.systemId))
1417+
if not _PUBID_CHARS.issuperset(self.publicId):
1418+
raise ValueError("invalid public identifier: %r"
1419+
% (self.publicId,))
1420+
# ExternalID with a public identifier always includes
1421+
# a system identifier (see XML 1.0, 4.2.2, [75]).
1422+
if not self.systemId:
1423+
raise ValueError("a public identifier requires "
1424+
"a system identifier")
1425+
writer.write("%s PUBLIC %s%s %s"
1426+
% (newl, _quote_literal(self.publicId),
1427+
newl, _quote_literal(self.systemId)))
13741428
elif self.systemId:
1375-
writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
1429+
writer.write("%s SYSTEM %s" % (newl,
1430+
_quote_literal(self.systemId)))
13761431
if self.internalSubset is not None:
13771432
writer.write(" [")
13781433
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)