xml_safe.py
python
sha256:e8214e0062ef8ef0af999937df2731655b6082781fc22bc563f58db2f42b1de9
Merge 'bump/muse-v0.2.1' into 'dev' — proposal: chore: bump…
Human
9 days 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
4 commits
sha256:e8214e0062ef8ef0af999937df2731655b6082781fc22bc563f58db2f42b1de9
Merge 'bump/muse-v0.2.1' into 'dev' — proposal: chore: bump…
Human
9 days ago
sha256:8de4334a98c945aace420969d389ad678aa926d4ab4e886b2ac4c4241cb3bf2b
revert: keep pyproject.toml in canonical PEP 440 form
Sonnet 4.6
patch
67 days ago
sha256:a317886dc0496c4af7b285b3e41c86c4c34ea2e79afc63b8829aadb1ada7903f
chore: bump version to 0.2.0rc15 to match musehub#113 fix release
Sonnet 4.6
patch
67 days ago
sha256:f3b726b50f0aee3622bba751e0a67aa7ae4cf75a798477dbce581940b6a9cf70
feat: migrate invariants cache to .muse/cache/invariants.ms…
Sonnet 4.6
patch
134 days ago