Graph-Native Infrastructure for Context and Accountable AI Systems
Python agent-memoryaiai-governanceai-infrastructureartificial-intelligencecontext-engineeringcontext-graphsdata-engineeringdecision-intelligencedeveloper-toolsexplainable-aigenerative-aigraph-ragknowledge-graphllmontologyprovenancepythonreasoningsemantic-search
fix(ingest): harden public API xml parsing
luffy22084d64c09ad339
diff --git a/semantica/ingest/methods.py b/semantica/ingest/methods.pyindex 52572365..f8cdcb4d 100644--- a/semantica/ingest/methods.py+++ b/semantica/ingest/methods.py@@ -1193,7 +1193,7 @@ def ingest(source_type: Source type (auto-detected if not specified)- "file": File ingestion- "web": Web ingestion- - "public_api": No-auth public API ingestion+ - "public_api" / "api": No-auth public API ingestion- "feed": Feed ingestion- "stream": Stream ingestion- "repo": Repository ingestiondiff --git a/semantica/ingest/public_api_ingestor.py b/semantica/ingest/public_api_ingestor.pyindex b13aa0de..d1b16429 100644--- a/semantica/ingest/public_api_ingestor.py+++ b/semantica/ingest/public_api_ingestor.py@@ -22,13 +22,25 @@ import copyimport csvimport ioimport time-import xml.etree.ElementTree as ETfrom dataclasses import dataclass, fieldfrom datetime import datetimefrom typing import Any, Dict, List, Optional, Tuplefrom urllib.parse import urlparseimport requests+from lxml import etree as lxml_etree++try:+ from defusedxml import ElementTree as safe_xml_etree+ from defusedxml.common import DefusedXmlException+except ModuleNotFoundError: # pragma: no cover - fallback for minimal installs+ safe_xml_etree = None++ class DefusedXmlException(Exception):+ """Fallback exception placeholder when defusedxml is unavailable."""++ pass+from ..utils.exceptions import ProcessingError, ValidationErrorfrom ..utils.logging import get_logger@@ -58,6 +70,14 @@ AUTH_PARAM_NAMES = {"subscription-key",}+_SAFE_XML_PARSER = lxml_etree.XMLParser(+ resolve_entities=False,+ no_network=True,+ recover=False,+ huge_tree=False,+ load_dtd=False,+)+@dataclassclass PublicAPIExample:@@ -298,7 +318,10 @@ class PublicAPIIngestor(RESTIngestor):self.rate_limit_delay = float(self.config.get("rate_limit_delay", self.config.get("delay", 1.0)) or 0.0)- self.validate_no_auth = bool(self.config.get("validate_no_auth", True))+ self.validate_no_auth = self._coerce_bool(+ self.config.get("validate_no_auth", True),+ default=True,+ )self._last_request_time = 0.0self.logger.debug("Public API ingestor initialized")@@ -673,7 +696,7 @@ class PublicAPIIngestor(RESTIngestor):raise ProcessingError(f"Failed to parse {detected_format.upper()} public API response") from exc- except ET.ParseError as exc:+ except (DefusedXmlException, lxml_etree.XMLSyntaxError) as exc:raise ProcessingError("Failed to parse XML public API response") from excdef _detect_response_format(@@ -711,10 +734,16 @@ class PublicAPIIngestor(RESTIngestor):return [dict(row) for row in reader]def _parse_xml(self, xml_text: str) -> Dict[str, Any]:- root = ET.fromstring(xml_text)+ if safe_xml_etree is not None:+ root = safe_xml_etree.fromstring(xml_text)+ else:+ root = lxml_etree.fromstring(+ xml_text.encode("utf-8"),+ parser=_SAFE_XML_PARSER,+ )return self._element_to_dict(root)- def _element_to_dict(self, element: ET.Element) -> Dict[str, Any]:+ def _element_to_dict(self, element: Any) -> Dict[str, Any]:children = [self._element_to_dict(child) for child in list(element)]return {"tag": self._strip_namespace(element.tag),@@ -731,6 +760,30 @@ class PublicAPIIngestor(RESTIngestor):return value.split("}", 1)[1]return value+ @staticmethod+ def _coerce_bool(value: Any, default: bool = True) -> bool:+ """+ Coerce common boolean config values safely.++ Strings such as "false", "0", "no", and "off" become False, while+ "true", "1", "yes", and "on" become True. Unknown strings are rejected+ so config mistakes fail closed instead of silently enabling behavior.+ """+ if value is None:+ return default+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ normalized = value.strip().lower()+ if normalized in {"1", "true", "yes", "on"}:+ return True+ if normalized in {"0", "false", "no", "off"}:+ return False+ raise ValidationError(+ f"Invalid boolean value for validate_no_auth: {value!r}"+ )+ return bool(value)+def _extract_record_path(self, data: Any, record_path: str) -> Any:current = datafor part in record_path.split("."):diff --git a/semantica/ingest/registry.py b/semantica/ingest/registry.pyindex 9d1a9c0a..87892092 100644--- a/semantica/ingest/registry.py+++ b/semantica/ingest/registry.py@@ -13,6 +13,7 @@ Supported Registration Types:* "repo": Repository ingestion methods* "email": Email ingestion methods* "db": Database ingestion methods+ * "api": Alias for public API ingestion methods* "public_api": Public no-auth API ingestion methods* "parquet": Parquet file and dataset ingestion methods* "ingest": General ingestion methods@@ -74,8 +75,8 @@ class MethodRegistry:Args:task: Task type such as "file", "web", "feed", "stream",- "repo", "email", "db", "public_api", "mcp", "parquet",- "xml", or "ingest"+ "repo", "email", "db", "api", "public_api", "mcp",+ "parquet", "xml", or "ingest"name: Method namemethod_func: Method function"""@@ -90,8 +91,8 @@ class MethodRegistry:Args:task: Task type such as "file", "web", "feed", "stream",- "repo", "email", "db", "public_api", "mcp", "parquet",- "xml", or "ingest"+ "repo", "email", "db", "api", "public_api", "mcp",+ "parquet", "xml", or "ingest"name: Method nameReturns:@@ -121,8 +122,8 @@ class MethodRegistry:Args:task: Task type such as "file", "web", "feed", "stream",- "repo", "email", "db", "public_api", "mcp", "parquet",- "xml", or "ingest"+ "repo", "email", "db", "api", "public_api", "mcp",+ "parquet", "xml", or "ingest"name: Method name"""if task in cls._methods and name in cls._methods[task]:diff --git a/tests/ingest/test_optional_imports.py b/tests/ingest/test_optional_imports.pyindex d040789f..6c70efb8 100644--- a/tests/ingest/test_optional_imports.py+++ b/tests/ingest/test_optional_imports.py@@ -69,6 +69,38 @@ print(PublicAPIIngestor.__name__, RESTIngestor.__name__, callable(ingest_public_assert "PublicAPIIngestor RESTIngestor True" in result.stdout+def test_public_api_ingestion_falls_back_without_defusedxml() -> None:+ result = _run_python_with_blocked_modules(+ """+from unittest.mock import MagicMock, patch+from semantica.ingest import PublicAPIIngestor++response = MagicMock()+response.status_code = 200+response.headers = {"Content-Type": "application/xml"}+response.text = "<items><item id='1'>Ada</item></items>"+response.raise_for_status.return_value = None+response.json.side_effect = ValueError("not json")++with patch("requests.Session") as MockSession:+ mock_session = MockSession.return_value+ mock_session.headers = {}+ mock_session.request.return_value = response++ data = PublicAPIIngestor(rate_limit_delay=0).ingest_public_api(+ "https://example.com/data.xml",+ record_path="children",+ )++print(data.data[0]["tag"], data.metadata["response_format"])+""",+ ("defusedxml",),+ )++ assert result.returncode == 0, result.stderr+ assert "item xml" in result.stdout++def test_repository_ingestion_reports_missing_gitpython_when_used() -> None:result = _run_python_with_blocked_modules("""diff --git a/tests/ingest/test_public_api_ingestor.py b/tests/ingest/test_public_api_ingestor.pyindex d76f1549..60e976b5 100644--- a/tests/ingest/test_public_api_ingestor.py+++ b/tests/ingest/test_public_api_ingestor.py@@ -12,7 +12,7 @@ from semantica.ingest import (ingest_public_api,list_available_methods,)-from semantica.utils.exceptions import ValidationError+from semantica.utils.exceptions import ProcessingError, ValidationErrordef _mock_response(@@ -147,6 +147,30 @@ def test_public_api_ingestor_parses_xml_records_with_record_path() -> None:assert result.data[0]["text"] == "Ada"+def test_public_api_ingestor_rejects_malicious_xml_entities() -> None:+ xml_text = """<?xml version="1.0"?>+<!DOCTYPE items [+<!ENTITY xxe SYSTEM "file:///etc/passwd">+]>+<items><item>&xxe;</item></items>+"""++ with patch("requests.Session") as mock_session_class:+ mock_session = mock_session_class.return_value+ mock_session.headers = {}+ mock_session.request.return_value = _mock_response(+ text=xml_text,+ headers={"Content-Type": "application/xml"},+ )++ with pytest.raises(+ ProcessingError, match="Failed to parse XML public API response"+ ):+ PublicAPIIngestor(rate_limit_delay=0).ingest_public_api(+ "https://example.com/data.xml"+ )++def test_public_api_detection_reports_public_endpoint() -> None:with patch("requests.Session") as mock_session_class:mock_session = mock_session_class.return_value@@ -198,6 +222,31 @@ def test_public_api_ingestor_rejects_authentication_inputs() -> None:mock_session.request.assert_not_called()+def test_public_api_ingestor_parses_string_boolean_config() -> None:+ payload = [{"id": 1, "title": "hello"}]++ with patch("requests.Session") as mock_session_class:+ mock_session = mock_session_class.return_value+ mock_session.headers = {}+ mock_session.request.return_value = _mock_response(+ json_payload=payload,+ text='[{"id": 1, "title": "hello"}]',+ headers={"Content-Type": "application/json"},+ )++ ingestor = PublicAPIIngestor(+ config={"validate_no_auth": "false"},+ rate_limit_delay=0,+ )+ result = ingestor.ingest_public_api(+ "https://api.example.com/data",+ headers={"Authorization": "Bearer token"},+ )++ assert ingestor.validate_no_auth is False+ assert result.data == payload++def test_public_api_convenience_methods_and_registry_dispatch() -> None:payload = [{"id": 1}]