authentik.lib.xml
XML Utilities
1"""XML Utilities""" 2 3from typing import NoReturn 4from xml.parsers import expat # nosec 5 6from lxml.etree import XMLParser, _Element, fromstring, tostring # nosec 7 8 9class UnsafeXML(ValueError): 10 """A document uses XML features that are not accepted.""" 11 12 13class _RootElement(Exception): 14 """The scan reached the root element. expat offers no other way to stop it.""" 15 16 17class _Doctype(Exception): 18 """The scan reached a document type declaration.""" 19 20 21def _reject_doctype(data: bytes) -> None: 22 """Refuse a document type declaration. 23 24 The check runs on expat rather than on the parser below, and looks for a 25 declaration rather than for its text, because a document may be in any encoding. 26 Parsing stops at the root element, so only the prolog is read.""" 27 parser = expat.ParserCreate() 28 29 def start_doctype( 30 name: str, system_id: str | None, public_id: str | None, has_internal_subset: int 31 ) -> NoReturn: 32 raise _Doctype 33 34 def start_element(name: str, attributes: dict[str, str]) -> NoReturn: 35 raise _RootElement 36 37 parser.StartDoctypeDeclHandler = start_doctype 38 parser.StartElementHandler = start_element 39 try: 40 parser.Parse(data, True) 41 except _RootElement: 42 pass 43 except _Doctype: 44 raise UnsafeXML("XML document contains a DOCTYPE declaration") from None 45 except (expat.ExpatError, LookupError, ValueError) as exc: 46 # An encoding this parser cannot read is reported as any of these three. A 47 # document that cannot be read here is not one to hand to the parser below. 48 raise UnsafeXML("XML document could not be validated") from exc 49 50 51def get_lxml_parser(): 52 """Get XML parser""" 53 return XMLParser(resolve_entities=False) 54 55 56def lxml_from_string(text: str | bytes) -> _Element: 57 """Wrapper around fromstring""" 58 data = text.encode() if isinstance(text, str) else text 59 _reject_doctype(data) 60 return fromstring(data, parser=get_lxml_parser()) # nosec 61 62 63def remove_xml_newlines(parent: _Element, element: _Element): 64 """Remove newlines in a given XML element, required for xmlsec 65 66 https://github.com/xmlsec/python-xmlsec/issues/196""" 67 old_element = element 68 new_node = fromstring(tostring(element, encoding=str).replace("\n", "")) 69 parent.replace(old_element, new_node) 70 return new_node
class
UnsafeXML(builtins.ValueError):
A document uses XML features that are not accepted.
def
get_lxml_parser():
Get XML parser
def
lxml_from_string(text: str | bytes) -> lxml.etree._Element:
57def lxml_from_string(text: str | bytes) -> _Element: 58 """Wrapper around fromstring""" 59 data = text.encode() if isinstance(text, str) else text 60 _reject_doctype(data) 61 return fromstring(data, parser=get_lxml_parser()) # nosec
Wrapper around fromstring
def
remove_xml_newlines(parent: lxml.etree._Element, element: lxml.etree._Element):
64def remove_xml_newlines(parent: _Element, element: _Element): 65 """Remove newlines in a given XML element, required for xmlsec 66 67 https://github.com/xmlsec/python-xmlsec/issues/196""" 68 old_element = element 69 new_node = fromstring(tostring(element, encoding=str).replace("\n", "")) 70 parent.replace(old_element, new_node) 71 return new_node
Remove newlines in a given XML element, required for xmlsec