Skip to content

Graph-Native Infrastructure for Context and Accountable AI Systems

fix: make defusedxml required, fail closed if missing (reviewer feedback)

Sunil0a113b97021a
diff --git a/semantica/explorer/utils/rdf_parser.py b/semantica/explorer/utils/rdf_parser.py
index e685fb1e..07206410 100644
--- a/semantica/explorer/utils/rdf_parser.py
+++ b/semantica/explorer/utils/rdf_parser.py
@@ -14,42 +14,23 @@ _HAS_DEFUSEDXML = importlib.util.find_spec("defusedxml") is not None
def _safe_parse_rdf(g: rdflib.Graph, data: bytes, rdf_format: str) -> None:
- """Parse RDF bytes into *g*, guarding against XXE for XML-based formats."""
+ """Parse RDF bytes into *g*, guarding against XXE for XML-based formats.
+
+ Raises:
+ ImportError: If ``defusedxml`` is not installed and the format is XML-based.
+ """
xml_formats = {"xml", "rdf", "rdf/xml", "application/rdf+xml"}
if rdf_format.lower() in xml_formats:
- if _HAS_DEFUSEDXML:
- # defusedxml patches xml.etree so rdflib's XML parser inherits the fix
- import defusedxml
- defusedxml.defuse_stdlib()
- else:
- # SECURITY: Strip DOCTYPE declarations and entity definitions from
- # the raw XML to prevent XXE attacks (file disclosure, SSRF, DoS
- # via entity expansion). This is a best-effort defence when
- # defusedxml is not installed.
- import re
- import warnings
- warnings.warn(
- "defusedxml is not installed. Install it (`pip install defusedxml`) "
- "for robust XXE protection. Applying basic DOCTYPE stripping as "
- "a fallback.",
- stacklevel=4,
- )
- text = data.decode("utf-8", errors="replace")
- # Remove <!DOCTYPE ...> blocks (including internal subsets)
- text = re.sub(
- r"<!DOCTYPE\s[^>\[]*(\[[^\]]*\])?\s*>",
- "",
- text,
- flags=re.IGNORECASE | re.DOTALL,
- )
- # Remove any remaining <!ENTITY ...> declarations
- text = re.sub(
- r"<!ENTITY\s[^>]*>",
- "",
- text,
- flags=re.IGNORECASE,
+ if not _HAS_DEFUSEDXML:
+ # Fail closed: refuse to parse untrusted XML without XXE protection.
+ raise ImportError(
+ "defusedxml is required to safely parse RDF/XML content but is "
+ "not installed. Install it with: pip install defusedxml "
+ "(or install semantica with the explorer extra: "
+ "pip install 'semantica[explorer]')"
)
- data = text.encode("utf-8")
+ import defusedxml
+ defusedxml.defuse_stdlib()
g.parse(data=data, format=rdf_format)
def _get_best_label(graph: rdflib.Graph, subject: rdflib.URIRef, predicate: rdflib.URIRef) -> str: