From fb3d143e07495ca5e43b648ec962becb583476f0 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Tue, 24 Nov 2026 18:18:38 +0200 Subject: [PATCH] [3.15] 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'. (cherry picked from commit 79494e2b0f7e9e1cc3a39fe035e67cea33c7ef0a) Co-authored-by: Serhiy Storchaka --- Doc/library/xml.dom.minidom.rst | 9 +++ Lib/test/test_minidom.py | 69 +++++++++++++++++-- Lib/xml/dom/minidom.py | 67 ++++++++++++++++-- ...-11-11-20-50-03.gh-issue-156812.nqPw30.rst | 10 +++ 4 files changed, 145 insertions(+), 10 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-11-11-20-50-03.gh-issue-156812.nqPw30.rst diff --git a/Doc/library/xml.dom.minidom.rst b/Doc/library/xml.dom.minidom.rst index ded3859192fd83..11b73e22b57b6e 100644 --- a/Doc/library/xml.dom.minidom.rst +++ b/Doc/library/xml.dom.minidom.rst @@ -147,6 +147,15 @@ module documentation. This section lists the differences between the API and otherwise it is set to ``"no"``. Not stating the argument will omit the declaration from the document. + :exc:`ValueError` is raised if the content of the node cannot be + represented in XML, for example if a comment contains ``"--"`` or + a CDATA section contains ``"]]>"``. + The characters are not checked: + the text, the attribute values and the content of comments, + processing instructions and CDATA sections are written as is. + If they can contain characters which are not allowed in XML, + check them with :func:`xml.is_valid_text` before serialization. + .. versionchanged:: 3.8 The :meth:`writexml` method now preserves the attribute order specified by the user. diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py index 8c4de2e21553c1..9cf64f2c02f2a9 100644 --- a/Lib/test/test_minidom.py +++ b/Lib/test/test_minidom.py @@ -2004,10 +2004,71 @@ def testDeepcopiedDocument(self): doc2 = copy.deepcopy(doc) self.assert_recursive_equal(doc, doc2) - def testSerializeCommentNodeWithDoubleHyphen(self): - doc = create_doc_without_doctype() - doc.appendChild(doc.createComment("foo--bar")) - self.assertRaises(ValueError, doc.toxml) + def testWriteXMLDoctypeIdentifiers(self): + impl = getDOMImplementation() + def serialize(publicId, systemId): + doctype = impl.createDocumentType("r", publicId, systemId) + return impl.createDocument(None, "r", doctype).toxml()[22:] + self.assertEqual(serialize(None, None), '') + self.assertEqual(serialize(None, "s"), "") + self.assertEqual(serialize("p", "s"), + "") + # the quote which is not in the literal is used + self.assertEqual(serialize("it's", "sys'tem"), + '') + # a system literal cannot contain both quotes + with self.assertRaisesRegex(ValueError, "both quotes"): + serialize(None, 'a"b\'c') + # a public identifier can only contain PubidChars + for publicId in ['pub"lic', 'p>', 'p<', 'p&', 'p[', '\xe9']: + with self.subTest(publicId=publicId): + with self.assertRaisesRegex(ValueError, + "invalid public identifier"): + serialize(publicId, "s") + # a public identifier is meaningless without a system identifier + with self.assertRaisesRegex(ValueError, "requires a system"): + serialize("p", None) + + def testSerializeComment(self): + impl = getDOMImplementation() + def serialize(data): + doc = impl.createDocument(None, "r", None) + doc.documentElement.appendChild(doc.createComment(data)) + return doc.toxml()[22:] + self.assertEqual(serialize("foo"), "") + self.assertEqual(serialize(""), "") + self.assertEqual(serialize("-foo"), "") + with self.assertRaisesRegex(ValueError, "'--' is not allowed"): + serialize("foo--bar") + # a trailing hyphen would be fused with the closing "-->" + with self.assertRaisesRegex(ValueError, "cannot end with"): + serialize("foo-") + + def testSerializeProcessingInstruction(self): + impl = getDOMImplementation() + def serialize(target, data): + doc = impl.createDocument(None, "r", None) + pi = doc.createProcessingInstruction(target, data) + doc.documentElement.appendChild(pi) + return doc.toxml()[22:] + self.assertEqual(serialize("p", "a"), "") + self.assertEqual(serialize("p", ""), "") + self.assertEqual(serialize("xml-stylesheet", 'href="a"'), + '') + # "?>" would close the processing instruction + with self.assertRaisesRegex(ValueError, "'\\?>' is not allowed"): + serialize("p", "a?>b") + # the target "xml" is reserved + for target in ["xml", "XML", "XmL"]: + with self.subTest(target=target): + with self.assertRaisesRegex(ValueError, "reserved"): + serialize(target, "a") + # the target is a name + doc = impl.createDocument(None, "r", None) + pi = doc.createProcessingInstruction("p", "a") + doc.documentElement.appendChild(pi) + pi.target = "a b" + self.assertRaises(xml.dom.InvalidCharacterErr, doc.toxml) def testEmptyXMLNSValue(self): diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py index 6762853e91abdd..b5fc4851e7afe5 100644 --- a/Lib/xml/dom/minidom.py +++ b/Lib/xml/dom/minidom.py @@ -285,6 +285,33 @@ def __exit__(self, et, ev, tb): defproperty(Node, "localName", doc="Namespace-local name of this node.") +# PubidChar (see XML 1.0, 2.3, [13]). +_PUBID_CHARS = frozenset( + " \r\n-'()+,./:=?;!*#@$_%" + "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz") + + +def _quote_literal(text): + """Quote a system literal or a public identifier. + + A literal is delimited with a quote which it does not contain + (see XML 1.0, 2.3, [11] and [12]). + """ + if "'" not in text: + return "'%s'" % text + if '"' not in text: + return '"%s"' % text + raise ValueError("a literal cannot contain both quotes: %r" % (text,)) + + +def _check_name(name): + if not xml.is_valid_name(name): + raise xml.dom.InvalidCharacterErr( + "%r is not a valid XML name" % (name,)) + + def _append_child(self, node): # fast path with less checks; usable by DOM builders if careful childNodes = self.childNodes @@ -1026,7 +1053,20 @@ def _set_nodeName(self, value): nodeName = property(_get_nodeName, _set_nodeName) def writexml(self, writer, indent="", addindent="", newl=""): - writer.write("%s%s" % (indent,self.target, self.data, newl)) + target = self.target + # PITarget is a Name, except the names matching "xml" in any case + # (see XML 1.0, 2.6, [17]). + _check_name(target) + if target.lower() == "xml": + raise ValueError("%r is a reserved processing instruction target" + % (target,)) + data = self.data + # The data cannot contain "?>", which ends the instruction + # (see XML 1.0, 2.6, [16]). + if "?>" in data: + raise ValueError("'?>' is not allowed in a processing " + "instruction node") + writer.write("%s%s" % (indent, target, data, newl)) class CharacterData(Childless, Node): @@ -1221,9 +1261,14 @@ def __init__(self, data): self._data = data def writexml(self, writer, indent="", addindent="", newl=""): - if "--" in self.data: + data = self.data + # The data cannot contain "--", and cannot end with "-", which + # would be fused with the closing "-->" (see XML 1.0, 2.5, [15]). + if "--" in data: raise ValueError("'--' is not allowed in a comment node") - writer.write("%s%s" % (indent, self.data, newl)) + if data.endswith("-"): + raise ValueError("a comment node cannot end with '-'") + writer.write("%s%s" % (indent, data, newl)) class CDATASection(Text): @@ -1369,10 +1414,20 @@ def writexml(self, writer, indent="", addindent="", newl=""): writer.write("`` in the data +or using the reserved target ``xml``. +The characters are still not checked.