gabriel / muse public
xml_safe.py python
45 lines 1.8 KB
Raw
sha256:08c083095bcaffb4c43ce947668fac93bf5d261e13d321776170c4019dd1d77d fix: migration must never update identity.toml on a failed … Sonnet 5 minor ⚠ breaking 6 hours ago
1 """Typed safe XML parsing adapter.
2
3 Wraps ``defusedxml`` behind a typed interface so the rest of Muse can use
4 ``SafeET.parse()`` with full type information and no suppression comments.
5
6 ``defusedxml`` does not ship type stubs, so importing it directly would
7 require a suppression comment (banned by the project's zero-ignore rule).
8 This module contains the single, justified crossing of the typed/untyped
9 boundary and presents a fully-typed surface to callers.
10
11 Only ``parse()`` is exposed — the sole function we use from defusedxml.
12 All other ElementTree functionality (``Element``, ``iterparse``, etc.) is
13 re-exported from the stdlib ``xml.etree.ElementTree``, which is fully typed.
14 """
15
16 import xml.etree.ElementTree as _StdET
17 from pathlib import Path
18 from xml.etree.ElementTree import Element, ElementTree, ParseError
19
20 def _defuse_parse(source: str | Path) -> ElementTree:
21 """Parse an XML file through defusedxml to block entity expansion attacks.
22
23 defusedxml raises ``defusedxml.DTDForbidden``, ``defusedxml.EntitiesForbidden``,
24 etc. on malicious XML. These are all subclasses of ``xml.etree.ElementTree.ParseError``
25 so callers can catch ``ParseError`` generically.
26 """
27 import defusedxml.ElementTree as _dxml # noqa: PLC0415 (local import intentional)
28
29 return _dxml.parse(str(source))
30
31 class SafeET:
32 """Namespace class — use ``SafeET.parse()`` as a drop-in for ``ET.parse()``."""
33
34 @staticmethod
35 def parse(source: str | Path) -> ElementTree:
36 """Return an :class:`xml.etree.ElementTree.ElementTree` parsed safely."""
37 return _defuse_parse(source)
38
39 # Re-export stdlib types so callers do not need to import xml.etree.ElementTree
40 # separately.
41 ParseError = ParseError
42 Element = Element
43 ElementTree = ElementTree
44
45 __all__ = ["SafeET"]
File History 1 commit
sha256:08c083095bcaffb4c43ce947668fac93bf5d261e13d321776170c4019dd1d77d fix: migration must never update identity.toml on a failed … Sonnet 5 minor 6 hours ago