Turn any technical book PDF into a Claude Code skill — ready to study, reference, and use while you work.
Python agent-skillsai-agentsbook-to-skillcontext-engineeringdocument-processingedtechknowledge-baseknowledge-managementllmpdf-to-markdownragself-studystudy-tools
fix(docx): self-defend the DOCX parsers against XXE regardless of caller (#99)
Chris Browne6521a64b057
diff --git a/book_to_skill/parsers/docx.py b/book_to_skill/parsers/docx.pyindex 879d8d1..49f2962 100644--- a/book_to_skill/parsers/docx.py+++ b/book_to_skill/parsers/docx.py@@ -6,8 +6,21 @@ from book_to_skill.exceptions import ExtractionErrordef extract_docx_with_python_docx(docx_path: str) -> str | None:+ # Called unconditionally (not just via extract_docx()) so this function is+ # self-defending when invoked directly WITH python-docx installed:+ # raises ExtractionError on DOCTYPE/ENTITY declarations before+ # python-docx ever opens the archive. If python-docx is NOT installed,+ # this returns None without validating at all -- a parser that isn't+ # installed parses nothing, so skipping the scan gives up no safety+ # (nothing gets extracted, malicious or not), and it avoids paying the+ # full archive scan on every extract_docx() call in the (default,+ # stdlib-only) case where this parser never even runs. A caller that+ # invokes this function directly and needs a validation guarantee+ # regardless of python-docx's availability should use+ # extract_docx_with_zipfile() or call validate_docx_xml_safety() itself.try:import docx+ validate_docx_xml_safety(docx_path)document = docx.Document(docx_path)parts = [paragraph.text for paragraph in document.paragraphs if paragraph.text]for table in document.tables:@@ -18,12 +31,21 @@ def extract_docx_with_python_docx(docx_path: str) -> str | None:return "\n".join(parts)except ImportError:return None+ except ExtractionError:+ # Without this, the broad `except Exception` below would catch an+ # XXE rejection from validate_docx_xml_safety() too, turning a+ # security refusal into a swallowed [warn] + None.+ raiseexcept Exception as e:print(f" [warn] extract_docx_with_python_docx failed: {type(e).__name__}: {e}", file=sys.stderr)return Nonedef extract_docx_with_zipfile(docx_path: str) -> str | None:+ # Called unconditionally (not just via extract_docx()) so this function is+ # self-defending even when invoked directly: raises ExtractionError on+ # DOCTYPE/ENTITY declarations before the XML ever reaches the parser.+ validate_docx_xml_safety(docx_path)try:import xml.etree.ElementTree as ET@@ -93,7 +115,10 @@ def validate_docx_xml_safety(docx_path: str) -> None:def extract_docx(docx_path: str) -> tuple[str, str]:- validate_docx_xml_safety(docx_path)+ # Validation lives in each leaf parser (extract_docx_with_python_docx,+ # extract_docx_with_zipfile) so it runs exactly once regardless of which+ # parser actually handles the file, instead of once here plus again in+ # whichever parser this falls through to.print("Trying python-docx...", end=" ", flush=True)text = extract_docx_with_python_docx(docx_path)if text and text.strip():diff --git a/tests/test_book_to_skill.py b/tests/test_book_to_skill.pyindex 99e4463..db90eda 100644--- a/tests/test_book_to_skill.py+++ b/tests/test_book_to_skill.py@@ -1067,6 +1067,84 @@ class TestDocxExtraction:assert result["format"] == "docx"assert "DOCX test paragraph" in result["text"]+ def test_extract_docx_zipfile_xxe_rejection_direct_call(self, tmp_path):+ """extract_docx_with_zipfile() must reject malicious XML even when+ called directly, not just via the extract_docx() wrapper — this is+ the bypass the self-defending validate_docx_xml_safety() call closes."""+ ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"+ xml = textwrap.dedent(f"""\+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>+ <!DOCTYPE w:document [+ <!ENTITY xxe SYSTEM "file:///etc/passwd">+ ]>+ <w:document xmlns:w="{ns}">+ <w:body>+ <w:p><w:r><w:t>&xxe;</w:t></w:r></w:p>+ </w:body>+ </w:document>+ """)+ bad_docx = tmp_path / "malicious.docx"+ with zipfile.ZipFile(bad_docx, "w") as zf:+ zf.writestr("word/document.xml", xml)+ zf.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>')++ with pytest.raises(ExtractionError, match="Security validation failed"):+ extract_docx_with_zipfile(str(bad_docx))++ def test_extract_docx_python_docx_xxe_rejection_direct_call(self, tmp_path):+ """extract_docx_with_python_docx() must reject malicious XML even when+ called directly, not just via the extract_docx() wrapper — mirrors the+ zipfile-parser test above. Validation now runs after `import docx`+ succeeds (so an absent python-docx doesn't pay for a scan that never+ protects anything -- see extract_docx_with_python_docx's docstring),+ so `docx` is faked importable here to exercise the guard+ deterministically regardless of whether python-docx is actually+ installed in the environment running this test."""+ from book_to_skill.parsers.docx import extract_docx_with_python_docx++ ns = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"+ xml = textwrap.dedent(f"""\+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>+ <!DOCTYPE w:document [+ <!ENTITY xxe SYSTEM "file:///etc/passwd">+ ]>+ <w:document xmlns:w="{ns}">+ <w:body>+ <w:p><w:r><w:t>&xxe;</w:t></w:r></w:p>+ </w:body>+ </w:document>+ """)+ bad_docx = tmp_path / "malicious.docx"+ with zipfile.ZipFile(bad_docx, "w") as zf:+ zf.writestr("word/document.xml", xml)+ zf.writestr("[Content_Types].xml", '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>')++ with mock.patch.dict(sys.modules, {"docx": mock.MagicMock()}):+ with pytest.raises(ExtractionError, match="Security validation failed"):+ extract_docx_with_python_docx(str(bad_docx))++ def test_extract_docx_python_docx_absent_skips_validation_without_raising(self, tmp_path):+ """Companion to the test above: when python-docx genuinely isn't+ importable, extract_docx_with_python_docx() must return None (not+ raise, not scan the archive) -- it can't parse anything either way,+ malicious or not, so there's no protection to buy by validating."""+ from book_to_skill.parsers.docx import extract_docx_with_python_docx++ real_import = __import__++ def fake_import(name, *args, **kwargs):+ if name == "docx":+ raise ImportError("simulated: python-docx not installed")+ return real_import(name, *args, **kwargs)++ docx_path = tmp_path / "whatever.docx"+ docx_path.write_bytes(b"not even a real docx")++ with mock.patch("builtins.__import__", side_effect=fake_import):+ result = extract_docx_with_python_docx(str(docx_path))++ assert result is None+def test_extract_docx_xxe_rejection(self, tmp_path):"""Verify that a DOCX with malicious DTD or entity declarations is rejected."""from book_to_skill.parsers.docx import extract_docx@@ -1092,6 +1170,37 @@ class TestDocxExtraction:with pytest.raises(ExtractionError, match="Security validation failed"):extract_docx(str(bad_docx))+ def test_extract_docx_validates_once_when_python_docx_unavailable(self, tmp_path):+ """Maintainer-requested regression test: validate_docx_xml_safety()+ must run exactly once through extract_docx() when python-docx isn't+ installed -- once for real in the zipfile fallback, not also+ wastefully in the python-docx path before it ImportErrors out. That+ double-scan (the whole archive, every .xml/.rels member, decoded+ across five candidate encodings) is exactly what the earlier review+ round asked to remove."""+ from book_to_skill.parsers import docx as docx_module++ docx_path = _make_minimal_docx(tmp_path / "test.docx")++ real_import = __import__++ def fake_import(name, *args, **kwargs):+ if name == "docx":+ raise ImportError("simulated: python-docx not installed")+ return real_import(name, *args, **kwargs)++ with mock.patch.object(+ docx_module,+ "validate_docx_xml_safety",+ wraps=docx_module.validate_docx_xml_safety,+ ) as spy:+ with mock.patch("builtins.__import__", side_effect=fake_import):+ text, method = docx_module.extract_docx(str(docx_path))++ assert method == "zipfile-docx"+ assert "DOCX test paragraph" in text+ assert spy.call_count == 1+class TestResolveInputFiles: