Skip to content

Commit 79494e2

Browse files
gh-156812: Check structural rules when serializing in xml.dom.minidom (GH-161830)
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'.
1 parent cc056ab commit 79494e2

4 files changed

Lines changed: 139 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
@@ -2334,10 +2334,71 @@ def testDeepcopiedDocument(self):
23342334
doc2 = copy.deepcopy(doc)
23352335
self.assert_recursive_equal(doc, doc2)
23362336

2337-
def testSerializeCommentNodeWithDoubleHyphen(self):
2338-
doc = create_doc_without_doctype()
2339-
doc.appendChild(doc.createComment("foo--bar"))
2340-
self.assertRaises(ValueError, doc.toxml)
2337+
def testWriteXMLDoctypeIdentifiers(self):
2338+
impl = getDOMImplementation()
2339+
def serialize(publicId, systemId):
2340+
doctype = impl.createDocumentType("r", publicId, systemId)
2341+
return impl.createDocument(None, "r", doctype).toxml()[22:]
2342+
self.assertEqual(serialize(None, None), '<!DOCTYPE r><r/>')
2343+
self.assertEqual(serialize(None, "s"), "<!DOCTYPE r SYSTEM 's'><r/>")
2344+
self.assertEqual(serialize("p", "s"),
2345+
"<!DOCTYPE r PUBLIC 'p' 's'><r/>")
2346+
# the quote which is not in the literal is used
2347+
self.assertEqual(serialize("it's", "sys'tem"),
2348+
'<!DOCTYPE r PUBLIC "it\'s" "sys\'tem"><r/>')
2349+
# a system literal cannot contain both quotes
2350+
with self.assertRaisesRegex(ValueError, "both quotes"):
2351+
serialize(None, 'a"b\'c')
2352+
# a public identifier can only contain PubidChars
2353+
for publicId in ['pub"lic', 'p>', 'p<', 'p&', 'p[', '\xe9']:
2354+
with self.subTest(publicId=publicId):
2355+
with self.assertRaisesRegex(ValueError,
2356+
"invalid public identifier"):
2357+
serialize(publicId, "s")
2358+
# a public identifier is meaningless without a system identifier
2359+
with self.assertRaisesRegex(ValueError, "requires a system"):
2360+
serialize("p", None)
2361+
2362+
def testSerializeComment(self):
2363+
impl = getDOMImplementation()
2364+
def serialize(data):
2365+
doc = impl.createDocument(None, "r", None)
2366+
doc.documentElement.appendChild(doc.createComment(data))
2367+
return doc.toxml()[22:]
2368+
self.assertEqual(serialize("foo"), "<r><!--foo--></r>")
2369+
self.assertEqual(serialize(""), "<r><!----></r>")
2370+
self.assertEqual(serialize("-foo"), "<r><!---foo--></r>")
2371+
with self.assertRaisesRegex(ValueError, "'--' is not allowed"):
2372+
serialize("foo--bar")
2373+
# a trailing hyphen would be fused with the closing "-->"
2374+
with self.assertRaisesRegex(ValueError, "cannot end with"):
2375+
serialize("foo-")
2376+
2377+
def testSerializeProcessingInstruction(self):
2378+
impl = getDOMImplementation()
2379+
def serialize(target, data):
2380+
doc = impl.createDocument(None, "r", None)
2381+
pi = doc.createProcessingInstruction(target, data)
2382+
doc.documentElement.appendChild(pi)
2383+
return doc.toxml()[22:]
2384+
self.assertEqual(serialize("p", "a"), "<r><?p a?></r>")
2385+
self.assertEqual(serialize("p", ""), "<r><?p ?></r>")
2386+
self.assertEqual(serialize("xml-stylesheet", 'href="a"'),
2387+
'<r><?xml-stylesheet href="a"?></r>')
2388+
# "?>" would close the processing instruction
2389+
with self.assertRaisesRegex(ValueError, "'\\?>' is not allowed"):
2390+
serialize("p", "a?>b")
2391+
# the target "xml" is reserved
2392+
for target in ["xml", "XML", "XmL"]:
2393+
with self.subTest(target=target):
2394+
with self.assertRaisesRegex(ValueError, "reserved"):
2395+
serialize(target, "a")
2396+
# the target is a name
2397+
doc = impl.createDocument(None, "r", None)
2398+
pi = doc.createProcessingInstruction("p", "a")
2399+
doc.documentElement.appendChild(pi)
2400+
pi.target = "a b"
2401+
self.assertRaises(xml.dom.InvalidCharacterErr, doc.toxml)
23412402

23422403

23432404
def testEmptyXMLNSValue(self):

‎Lib/xml/dom/minidom.py‎

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

302302

303+
# PubidChar (see XML 1.0, 2.3, [13]).
304+
_PUBID_CHARS = frozenset(
305+
" \r\n-'()+,./:=?;!*#@$_%"
306+
"0123456789"
307+
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
308+
"abcdefghijklmnopqrstuvwxyz")
309+
310+
311+
def _quote_literal(text):
312+
"""Quote a system literal or a public identifier.
313+
314+
A literal is delimited with a quote which it does not contain
315+
(see XML 1.0, 2.3, [11] and [12]).
316+
"""
317+
if "'" not in text:
318+
return "'%s'" % text
319+
if '"' not in text:
320+
return '"%s"' % text
321+
raise ValueError("a literal cannot contain both quotes: %r" % (text,))
322+
323+
303324
def _check_name(name):
304325
if not xml.is_valid_name(name):
305326
raise xml.dom.InvalidCharacterErr(
@@ -1228,7 +1249,20 @@ def _set_nodeName(self, value):
12281249
nodeName = property(_get_nodeName, _set_nodeName)
12291250

12301251
def writexml(self, writer, indent="", addindent="", newl=""):
1231-
writer.write("%s<?%s %s?>%s" % (indent,self.target, self.data, newl))
1252+
target = self.target
1253+
# PITarget is a Name, except the names matching "xml" in any case
1254+
# (see XML 1.0, 2.6, [17]).
1255+
_check_name(target)
1256+
if target.lower() == "xml":
1257+
raise ValueError("%r is a reserved processing instruction target"
1258+
% (target,))
1259+
data = self.data
1260+
# The data cannot contain "?>", which ends the instruction
1261+
# (see XML 1.0, 2.6, [16]).
1262+
if "?>" in data:
1263+
raise ValueError("'?>' is not allowed in a processing "
1264+
"instruction node")
1265+
writer.write("%s<?%s %s?>%s" % (indent, target, data, newl))
12321266

12331267

12341268
class CharacterData(Childless, Node):
@@ -1423,9 +1457,14 @@ def __init__(self, data):
14231457
self._data = data
14241458

14251459
def writexml(self, writer, indent="", addindent="", newl=""):
1426-
if "--" in self.data:
1460+
data = self.data
1461+
# The data cannot contain "--", and cannot end with "-", which
1462+
# would be fused with the closing "-->" (see XML 1.0, 2.5, [15]).
1463+
if "--" in data:
14271464
raise ValueError("'--' is not allowed in a comment node")
1428-
writer.write("%s<!--%s-->%s" % (indent, self.data, newl))
1465+
if data.endswith("-"):
1466+
raise ValueError("a comment node cannot end with '-'")
1467+
writer.write("%s<!--%s-->%s" % (indent, data, newl))
14291468

14301469

14311470
class CDATASection(Text):
@@ -1571,10 +1610,20 @@ def writexml(self, writer, indent="", addindent="", newl=""):
15711610
writer.write("<!DOCTYPE ")
15721611
writer.write(self.name)
15731612
if self.publicId:
1574-
writer.write("%s PUBLIC '%s'%s '%s'"
1575-
% (newl, self.publicId, newl, self.systemId))
1613+
if not _PUBID_CHARS.issuperset(self.publicId):
1614+
raise ValueError("invalid public identifier: %r"
1615+
% (self.publicId,))
1616+
# ExternalID with a public identifier always includes
1617+
# a system identifier (see XML 1.0, 4.2.2, [75]).
1618+
if not self.systemId:
1619+
raise ValueError("a public identifier requires "
1620+
"a system identifier")
1621+
writer.write("%s PUBLIC %s%s %s"
1622+
% (newl, _quote_literal(self.publicId),
1623+
newl, _quote_literal(self.systemId)))
15761624
elif self.systemId:
1577-
writer.write("%s SYSTEM '%s'" % (newl, self.systemId))
1625+
writer.write("%s SYSTEM %s" % (newl,
1626+
_quote_literal(self.systemId)))
15781627
if self.internalSubset is not None:
15791628
writer.write(" [")
15801629
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)