kaxil commented on code in PR #77475:
URL: https://github.com/apache/airflow/pull/77475#discussion_r4689723750
##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -56,6 +60,95 @@
# cells count too. 1M characters is about 6000 rows of 10 columns; longer
tables are skipped.
_DOCX_TABLE_MAX_CHARS = 1_000_000
+# python-docx reads every part of a DOCX whole, and the XML parts it parses
take 13-18x their
+# size in memory (about 50x for a file of empty paragraphs). Word-saved files
hold about 30 bytes
+# of XML per character, so 50 MB is about 1.5M characters. Both limits are on
uncompressed sizes,
+# which can be far larger or smaller than the .docx file itself.
+_DOCX_MAX_XML_BYTES = 50 * 1024 * 1024
+
+# Word does not open files over 512 MB.
+_DOCX_MAX_UNCOMPRESSED_BYTES = 512 * 1024 * 1024
+
+_CONTENT_TYPES_NS =
"{http://schemas.openxmlformats.org/package/2006/content-types}"
+
+
+def _build_docx_size_error(source_hint: str, parts: str, size: int, limit:
int) -> ValueError:
+ return ValueError(
+ f"Cannot load DOCX {source_hint}: {parts} total {size / 2**20:.1f} MB
uncompressed, "
+ f"over the {limit / 2**20:.0f} MB limit."
+ )
+
+
+def _iter_docx_part_chunks(
+ zf: zipfile.ZipFile, info: zipfile.ZipInfo, *, source_hint: str
+) -> Iterator[bytes]:
+ # ZipFile stops reading at the declared size, so read through a copy that
allows one more
+ # byte: a part holding more data then fails the CRC check or yields the
extra byte.
+ probe = copy.copy(info)
+ probe.file_size += 1
+ read_bytes = 0
+ with zf.open(probe) as part:
+ while chunk := part.read(64 * 1024):
+ read_bytes += len(chunk)
+ if read_bytes > info.file_size:
+ raise ValueError(
+ f"Cannot load DOCX {source_hint}: part {info.filename!r}
holds more data than "
+ "its declared size."
+ )
+ yield chunk
+
+
+def _check_docx_part_sizes(stream: BinaryIO, *, source_hint: str) -> None:
+ """
+ Reject a DOCX whose parts are too large to load, before python-docx reads
it.
+
+ The sizes declared in the zip directory are checked first. Every part is
then inflated in
+ small chunks to confirm it holds no more than its declared size:
``ZipFile.read`` inflates up
+ to 1 GiB (2 GiB on Python 3.14) before it cuts the data at the declared
size, so a forged
+ size alone would not bound memory.
+
+ A part counts as XML when its content type ends in "xml" or it is a
``.rels`` file, which
+ python-docx parses whatever its content type. Content types are looked up
the way
+ python-docx does it, so a part cannot escape the XML limit through its
name.
+ """
+ with zipfile.ZipFile(stream) as zf:
+ infos = zf.infolist()
+ total_bytes = sum(info.file_size for info in infos)
+ if total_bytes > _DOCX_MAX_UNCOMPRESSED_BYTES:
+ raise _build_docx_size_error(source_hint, "its parts",
total_bytes, _DOCX_MAX_UNCOMPRESSED_BYTES)
+
+ content_types_info = zf.getinfo("[Content_Types].xml")
+ if content_types_info.file_size > _DOCX_MAX_XML_BYTES:
+ raise _build_docx_size_error(
+ source_hint, "its XML parts", content_types_info.file_size,
_DOCX_MAX_XML_BYTES
+ )
+ types = ElementTree.fromstring(
Review Comment:
`ElementTree` expands entities here and python-docx's parser doesn't
(`resolve_entities=False`), so the two can read different overrides. A
`[Content_Types].xml` with an entity that expands to a second `Override` for
`/word/document.xml` typed `application/octet-stream` makes the loop below skip
the document part, while python-docx still parses it as the main document, so
it gets past the 50 MB XML limit. The expansion also costs memory in the check
itself: 3M references to a 290-char entity (a 9 MB part, about 9 KB deflated)
took this parse from 33 MB to about 1 GB for me. Could this reject a doctype
outright, or parse with `docx.oxml.parser.parse_xml` so both sides read the
same thing?
##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -56,6 +60,95 @@
# cells count too. 1M characters is about 6000 rows of 10 columns; longer
tables are skipped.
_DOCX_TABLE_MAX_CHARS = 1_000_000
+# python-docx reads every part of a DOCX whole, and the XML parts it parses
take 13-18x their
+# size in memory (about 50x for a file of empty paragraphs). Word-saved files
hold about 30 bytes
+# of XML per character, so 50 MB is about 1.5M characters. Both limits are on
uncompressed sizes,
+# which can be far larger or smaller than the .docx file itself.
+_DOCX_MAX_XML_BYTES = 50 * 1024 * 1024
+
+# Word does not open files over 512 MB.
+_DOCX_MAX_UNCOMPRESSED_BYTES = 512 * 1024 * 1024
+
+_CONTENT_TYPES_NS =
"{http://schemas.openxmlformats.org/package/2006/content-types}"
+
+
+def _build_docx_size_error(source_hint: str, parts: str, size: int, limit:
int) -> ValueError:
+ return ValueError(
+ f"Cannot load DOCX {source_hint}: {parts} total {size / 2**20:.1f} MB
uncompressed, "
+ f"over the {limit / 2**20:.0f} MB limit."
+ )
+
+
+def _iter_docx_part_chunks(
+ zf: zipfile.ZipFile, info: zipfile.ZipInfo, *, source_hint: str
+) -> Iterator[bytes]:
+ # ZipFile stops reading at the declared size, so read through a copy that
allows one more
+ # byte: a part holding more data then fails the CRC check or yields the
extra byte.
+ probe = copy.copy(info)
+ probe.file_size += 1
+ read_bytes = 0
+ with zf.open(probe) as part:
+ while chunk := part.read(64 * 1024):
+ read_bytes += len(chunk)
+ if read_bytes > info.file_size:
+ raise ValueError(
+ f"Cannot load DOCX {source_hint}: part {info.filename!r}
holds more data than "
+ "its declared size."
+ )
+ yield chunk
+
+
+def _check_docx_part_sizes(stream: BinaryIO, *, source_hint: str) -> None:
+ """
+ Reject a DOCX whose parts are too large to load, before python-docx reads
it.
+
+ The sizes declared in the zip directory are checked first. Every part is
then inflated in
+ small chunks to confirm it holds no more than its declared size:
``ZipFile.read`` inflates up
+ to 1 GiB (2 GiB on Python 3.14) before it cuts the data at the declared
size, so a forged
+ size alone would not bound memory.
+
+ A part counts as XML when its content type ends in "xml" or it is a
``.rels`` file, which
+ python-docx parses whatever its content type. Content types are looked up
the way
+ python-docx does it, so a part cannot escape the XML limit through its
name.
+ """
+ with zipfile.ZipFile(stream) as zf:
+ infos = zf.infolist()
+ total_bytes = sum(info.file_size for info in infos)
+ if total_bytes > _DOCX_MAX_UNCOMPRESSED_BYTES:
+ raise _build_docx_size_error(source_hint, "its parts",
total_bytes, _DOCX_MAX_UNCOMPRESSED_BYTES)
+
+ content_types_info = zf.getinfo("[Content_Types].xml")
+ if content_types_info.file_size > _DOCX_MAX_XML_BYTES:
+ raise _build_docx_size_error(
+ source_hint, "its XML parts", content_types_info.file_size,
_DOCX_MAX_XML_BYTES
+ )
+ types = ElementTree.fromstring(
+ b"".join(_iter_docx_part_chunks(zf, content_types_info,
source_hint=source_hint))
+ )
+ defaults = {
+ e.get("Extension", "").lower(): e.get("ContentType", "")
+ for e in types.findall(f"{_CONTENT_TYPES_NS}Default")
+ }
+ overrides = {
+ e.get("PartName", "").lower(): e.get("ContentType", "")
+ for e in types.findall(f"{_CONTENT_TYPES_NS}Override")
+ }
+
+ xml_bytes = 0
+ for info in infos:
+ name = info.filename.lower()
+ content_type = overrides.get(f"/{name}") or
defaults.get(posixpath.splitext(name)[1][1:], "")
+ if info is content_types_info or name.endswith(".rels") or
content_type.endswith("xml"):
Review Comment:
This counts XML-typed parts that python-docx never parses too.
`image/svg+xml` media loads as an `ImagePart` blob, and customXml items aren't
parsed either. A file with a lot of SVG can hit the 50 MB limit while the parts
that do get parsed are small. Is that intended?
##########
providers/common/ai/src/airflow/providers/common/ai/operators/document_loader.py:
##########
@@ -56,6 +60,95 @@
# cells count too. 1M characters is about 6000 rows of 10 columns; longer
tables are skipped.
_DOCX_TABLE_MAX_CHARS = 1_000_000
+# python-docx reads every part of a DOCX whole, and the XML parts it parses
take 13-18x their
+# size in memory (about 50x for a file of empty paragraphs). Word-saved files
hold about 30 bytes
+# of XML per character, so 50 MB is about 1.5M characters. Both limits are on
uncompressed sizes,
+# which can be far larger or smaller than the .docx file itself.
+_DOCX_MAX_XML_BYTES = 50 * 1024 * 1024
+
+# Word does not open files over 512 MB.
+_DOCX_MAX_UNCOMPRESSED_BYTES = 512 * 1024 * 1024
+
+_CONTENT_TYPES_NS =
"{http://schemas.openxmlformats.org/package/2006/content-types}"
+
+
+def _build_docx_size_error(source_hint: str, parts: str, size: int, limit:
int) -> ValueError:
+ return ValueError(
+ f"Cannot load DOCX {source_hint}: {parts} total {size / 2**20:.1f} MB
uncompressed, "
+ f"over the {limit / 2**20:.0f} MB limit."
+ )
+
+
+def _iter_docx_part_chunks(
+ zf: zipfile.ZipFile, info: zipfile.ZipInfo, *, source_hint: str
+) -> Iterator[bytes]:
+ # ZipFile stops reading at the declared size, so read through a copy that
allows one more
+ # byte: a part holding more data then fails the CRC check or yields the
extra byte.
+ probe = copy.copy(info)
+ probe.file_size += 1
+ read_bytes = 0
+ with zf.open(probe) as part:
+ while chunk := part.read(64 * 1024):
Review Comment:
The 64 KB read doesn't bound memory for bzip2 parts on older Python patch
releases. On 3.12.3 and 3.11.9, a 534-byte zip with a bzip2 part of 512 MiB of
zeros declared as 100 bytes took this loop from 23 MB to about 1 GB before the
CRC error (3.12.15 and 3.13.18 stay flat). Word only writes stored and deflated
parts afaik, so could we reject any other `compress_type` before opening the
part?
##########
providers/common/ai/tests/unit/common/ai/operators/test_document_loader.py:
##########
@@ -759,6 +807,77 @@ def test_docx_nested_table_flattened_into_its_cell(self):
assert _load_docx_text(_get_docx_bytes(doc)) == "| Outer n1 / n2; n3 /
n4 | Right |"
+ # The python-docx template already hold about 820 KB of XML, so the limits
sit above of it
+
@patch("airflow.providers.common.ai.operators.document_loader._DOCX_MAX_XML_BYTES",
1_000_000)
+
@patch("airflow.providers.common.ai.operators.document_loader._DOCX_MAX_UNCOMPRESSED_BYTES",
2_000_000)
+ @pytest.mark.parametrize(
+ ("build", "match"),
+ [
+ pytest.param(
+ lambda raw: _edit_docx_part(
+ raw, "word/document.xml", b"<w:body>", b"<w:body>" +
b"<w:p/>" * 50_000
+ ),
+ "XML parts total",
+ id="xml-parts-over-limit-together",
+ ),
+ pytest.param(
+ lambda raw: _rewrite_docx_parts(
+ _edit_docx_part(raw, _CONTENT_TYPES, b"</Types>",
_HEADER_OVERRIDE + b"</Types>"),
+ add={"word/media/a.png": b" " * 300_000},
+ ),
+ "XML parts total",
+ id="xml-content-type-under-image-name",
+ ),
+ pytest.param(
+ lambda raw: _rewrite_docx_parts(
+ _edit_docx_part(raw, _CONTENT_TYPES, _RELS_DEFAULT, b""),
+ add={"word/_rels/padding.xml.rels": b" " * 300_000},
+ ),
+ "XML parts total",
+ id="rels-part-without-content-type",
+ ),
+ pytest.param(
+ lambda raw: _edit_docx_part(raw, _CONTENT_TYPES, b"</Types>",
b"</Types>" + b"x" * 1_100_000),
+ "XML parts total",
+ id="content-types-over-limit-not-parsed",
+ ),
+ pytest.param(
+ lambda raw: _rewrite_docx_parts(raw,
add={"word/media/padding.bin": bytes(1_300_000)}),
Review Comment:
Every case here checks that a part is counted as XML, none that a non-XML
part is left out: replacing the condition in `_check_docx_part_sizes` with `if
True:` still passes the whole suite. Can you add a case where something like a
500 KB `word/media/padding.bin` still loads under these patched limits?
##########
providers/common/ai/tests/unit/common/ai/operators/test_document_loader.py:
##########
@@ -759,6 +807,77 @@ def test_docx_nested_table_flattened_into_its_cell(self):
assert _load_docx_text(_get_docx_bytes(doc)) == "| Outer n1 / n2; n3 /
n4 | Right |"
+ # The python-docx template already hold about 820 KB of XML, so the limits
sit above of it
+
@patch("airflow.providers.common.ai.operators.document_loader._DOCX_MAX_XML_BYTES",
1_000_000)
+
@patch("airflow.providers.common.ai.operators.document_loader._DOCX_MAX_UNCOMPRESSED_BYTES",
2_000_000)
+ @pytest.mark.parametrize(
+ ("build", "match"),
+ [
+ pytest.param(
+ lambda raw: _edit_docx_part(
+ raw, "word/document.xml", b"<w:body>", b"<w:body>" +
b"<w:p/>" * 50_000
+ ),
+ "XML parts total",
+ id="xml-parts-over-limit-together",
+ ),
+ pytest.param(
+ lambda raw: _rewrite_docx_parts(
+ _edit_docx_part(raw, _CONTENT_TYPES, b"</Types>",
_HEADER_OVERRIDE + b"</Types>"),
+ add={"word/media/a.png": b" " * 300_000},
Review Comment:
The part name and the override use the same case here, so the
case-insensitive lookup isn't tested (dropping the three `.lower()` calls still
passes). Worth a case with the part named `word/media/A.png`?
##########
providers/common/ai/tests/unit/common/ai/operators/test_document_loader.py:
##########
@@ -759,6 +807,77 @@ def test_docx_nested_table_flattened_into_its_cell(self):
assert _load_docx_text(_get_docx_bytes(doc)) == "| Outer n1 / n2; n3 /
n4 | Right |"
+ # The python-docx template already hold about 820 KB of XML, so the limits
sit above of it
Review Comment:
```suggestion
# The python-docx template already holds about 820 KB of XML, so the
limits sit above it
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]