Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(security): bound upload document conversion and zip-container parsing (#6515)

LearningCircuitd3698a7a1084
diff --git a/changelog.d/6515.security.md b/changelog.d/6515.security.md
new file mode 100644
index 0000000000..f7ef89be27
--- /dev/null
+++ b/changelog.d/6515.security.md
@@ -0,0 +1 @@
+Uploaded documents are now checked and converted through bounded guards before any parser runs. Zip-container uploads (.docx/.xlsx/.pptx/.odt/.epub) are refused when the archive cannot be read; when it does not start at byte 0 (the file must begin with a zip local-header or empty-archive signature and its first entry must sit at offset 0, so a legacy OLE .doc/.ppt with a zip appended, uploaded as .docx/.pptx, can no longer pass the guard and be routed by unstructured to its own unbounded soffice conversion); when a .docx/.pptx/.xlsx has a root `mimetype` member or member names from which unstructured's zip sniffer would infer another type, when a .docx/.pptx lacks the main document part python-docx/python-pptx resolve through the package relationships, or when an .xlsx has no `xl/workbook.xml` (langchain's Word and PowerPoint loaders ask unstructured's `detect_filetype` for the type whenever python-magic imports and send a file it calls DOC or PPT to `partition_doc`/`partition_ppt`, which run soffice with no timeout and partition its output without this guard; a zip whose member names match none of the OOXML patterns is typed from its `mimetype` member, so a 134-byte .docx holding only a `mimetype` of `application/msword` was accepted and went there; pandas likewise picks its Excel engine from the member names); when an .odt/.epub `mimetype` member names another type; when its declared central-directory byte span exceeds the entry-count-scaled bound (10 MiB, read before zipfile walks the records from the end-of-central-directory or ZIP64 end record that zipfile's own end-record lookup selects, so a layout that would show the guard one record and zipfile another cannot slip past, and an archive whose end records zipfile cannot read is refused there: zipfile materialises every central-directory record before the entry count can be counted, and the end record's own entry count wraps at 65,535 and is ignored by zipfile, so a hand-packed record flood a fraction of the upload cap in size bought hundreds of MiB of resident memory before any refusal fired); when it has more than 10,000 entries, encrypted entries, entries sharing one local header, non-canonical or duplicate member names (empty, `.` or `..` path segments, a leading `/`, backslashes), or entries compressed with anything but STORED or DEFLATE; when an entry's compressed size is inconsistent with its declared size; when an entry declares more than the largest per-entry ceiling; when an entry's local header disagrees with its central-directory record (compression method, flags, CRC, sizes or name, or a data descriptor that does not repeat the central CRC and sizes), since pandoc's zip reader takes an entry's method and compressed size from the local header while the guard and zipfile use the central directory; when a DEFLATE entry does not inflate to exactly its declared size with its declared CRC, its stream ending exactly at the end of its compressed range (every DEFLATE entry is inflated once, in bounded steps, to check; a STORED entry's size is fixed by its equality check and its CRC is checked as well); or when the verified sizes exceed the ceilings: 128 MiB for a parsed (XML/text) part, 512 MiB of parsed parts in total, 512 MiB for a binary media entry in .docx/.pptx/.xlsx (recognised by an anchored binary signature in its leading bytes that no XML parser the in-process loaders use, lxml or expat, accepts as a document start, never by its name; every EPUB/ODT entry stays under the parsed-part ceilings), and 1 GiB across all entries. Each parser read of an entry is therefore bounded by its verified size; parser memory and parser time are not bounded in general (an XML parse tree alone costs roughly 10-20x the XML, and what a loader builds from it can cost far more). python-pptx and python-docx load each media part once, however often it is referenced; .xlsx extraction no longer lets openpyxl read chartsheet drawings (images and charts), which it otherwise re-read once per reference; and an .xlsx workbook whose sheet entries resolve to the same sheet part more than once (which openpyxl would convert once per entry) is refused, as is one whose sheets share a relationships part, with both computed by openpyxl's own workbook reader so the check and the loader cannot disagree (the workbook skeleton parts it parses are held to 16 MiB); a workbook openpyxl cannot resolve is refused as malformed, as is one listing more than 2,000 sheets (openpyxl checks every sheet's target against a list of the members and pandas looks every sheet up in a list of all their names: 10,000 empty sheets took 40 s in `pandas.read_excel`, and 100,000 sheets without parts next to 9,000 members 7.6 s in openpyxl alone; 2,000 one-cell sheets take about 5 s to partition), and so is one whose `xl/styles.xml`, which openpyxl loads on every read, has a number format code over 1,024 characters (Excel's own limit is 255), more than 65,490 entries in a cell-format list (Excel's limit on cell formats and styles), or would cost openpyxl more than 4 billion units in the date tests it runs over the format code of every cell format (each counted at the code's length times 50 plus its `[` characters, about 0.5 ns per unit, since one scan restarts at every unclosed `[`: a 3.3 KB workbook with one 1,000,000-character code under 2,000 cell formats took 53 s to load, and 3,600 formats of a 1,024-bracket code, at the ceiling, take 2.1 s) or more than 20 million in the work it repeats once per named style (each named style counted at 600 units, plus the custom formats, whose list openpyxl rebuilds per named style, plus 16 per element and one per 256 characters of the largest font, fill and border, which openpyxl hashes and compares as it binds each named style; a unit is about 130 ns; named styles are counted as the distinct style-format ids they name, up to twice the style formats since openpyxl reads a negative id from the end: 8,800 named styles over 4,400 style formats and 4,400 custom formats took 5.3 s to load, and 1,000 named styles of a 1,000-stop gradient fill, a 13 KB file, about 3 s, while 20,000 named styles of a minimal font, fill and border, at 0.66 of the ceiling, load in 1.8 s, and 15,000 of Excel's default font, fills and border with 300 custom formats, at 0.84, in 2 s). A gradient fill of more than 256 stops (Excel's cell gradients have two or three) is refused too, as is a styles part giving a number format's code or id, a cell format's ids or a named style's fields as child elements, which openpyxl reads in place of the attributes (a 1,881-byte workbook whose 1,000,000-character code was given that way, under 2,000 cell formats, took 52 s to load; 100,000 characters, 5 s); the styles part is streamed once for this, with its lists matched by local name in any namespace as openpyxl matches them. A comment or processing instruction anywhere below the top level of the styles part (inside a list such as `fonts` or `cellXfs`, or inside an entry), or of `[Content_Types].xml`, the workbook part or its relationships, is refused too: openpyxl parses these parts with lxml, which keeps such nodes, and builds a default entry from every child node of the lists `fonts`, `borders`, `dxfs` and `mruColors` and of the workbook's `bookViews` (it fails to load one among `fills`, `indexedColors` or `sheets`), while the guard counts elements, so 2,000,000 empty comments after one font, a 25 KB file, were accepted and took openpyxl 37 s and 960 MB to load as 2,000,001 fonts, and 2,390,000 among the `bookViews` of a 16 MiB workbook part took the guard's own parse of it 19.6 s and 1.1 GB; Excel writes none there. Comments and processing instructions directly under the root element, or outside it, which openpyxl skips, are still accepted, but the .xlsx styles part, .pptx slides, slide layouts and slide masters, and .docx `document.xml`, headers and footers are refused with more than 64 outside the root element: the guard streams these with comment events, and lxml emits each such event before the root in time linear in the ones before it (60,000 empty comments before a slide's root, a 420 KB part, kept the guard busy for 16.7 s); a .docx with a comment before its `document.xml` root, which the guard used to refuse as malformed, is accepted. openpyxl also builds an object from every entry of every list of the styles and workbook parts and from every child it knows of every other element, keeping only the last of a repeated one, and nothing bounded most of them: 500,000 `<font/>` in one differential format, a 10 KB file, took 7.4 s to load, 1,000 fills of 256 gradient stops (a 14 MB part) 4.5 s to load and 8 s in the guard, and 1,800,000 `<calcPr/>` in a 16 MiB workbook part 17 s in openpyxl and as long again in the guard's own parse. So a styles part is now also refused with more than 256 elements under its root, 8,192 custom number formats (Excel documents 200 to 250), 65,490 differential formats (`dxfs`, held to Excel's cell-format limit) or 500,000 elements under them, 1,024 custom table styles or 32 elements in one, 1,024 indexed or 1,024 recently used colours, 131,072 extensions (`<ext>`) in all, or 65,536 gradient stops in all, with every child element of a list counting as an entry and each kind counted over every such list in the part; a workbook part with more than 256 elements under its root, 8,192 entries in any of its view, external reference, pivot cache, smart tag, function group or web publish lists, more than 2,000 entries under `sheets` (with or without a relationship id) or 131,072 extensions is refused too (the number of defined names stays bounded by the part's 16 MiB ceiling: 250,000 beside every other list at its cap, a 16.4 MB part, take 4.8 s in the guard and 4 s to load); and in both parts an element that is not a list may not repeat a child's local name (Excel never does; the content of an extension, which openpyxl does not read, is exempt, but an `extLst` that is itself an entry of a list such as `fills`, or a fill's first child, is read by openpyxl as that entry or as a gradient fill and is counted as one, its stops included), and a styles part with a font, fill, border or cell-format entry of more than 1,024 elements is refused (the guard holds such an entry whole to rebuild it, and lxml takes time quadratic in its nodes to drop it: one fill of 160,000 elements took the guard 6.5 s to drop; a gradient at the 256-stop ceiling has 514). A defined name whose value is longer than 8,192 characters (Excel's formula limit) is refused, the value measured at the longest of the entry's attribute values, its text and its children's text, since openpyxl's `from_tree` also takes the value from an `attr_text` or `attr-text` attribute (a 4.9 KB workbook giving a `_xlnm.Print_Area` value of 10,000 `#` that way was accepted and took openpyxl 9.2 s to load), as is a workbook whose print titles and print areas would cost openpyxl more than 67,110,912 units, each counted at its value's length squared plus 2,048: on every load openpyxl parses every sheet-local defined name starting with `_xlnm.Print_Titles` or `_xlnm.Print_Area` (a prefix match, so a sheet can hold any number of them) with regular expressions that scan for a sheet name from every position of the value, so 40,000 `#` characters in one, a file under 2 KB, took 14 to 37 s and a 1 MB value would take hours; one value at the length ceiling, or 31,776 of 8 characters, now takes about 0.9 to 2.9 s. A workbook is also refused when a sheet name is longer than 255 characters (Excel allows 31, Google Sheets 100) or two sheet names are equal once lowercased (Excel forbids it, and openpyxl renames such a chartsheet after joining and searching every sheet name): pandas looks every sheet up by name in lists of all of them, so 2,000 sheets of 8,000-character names, a 554 KB file, took 6.4 s to read; and when an XML part openpyxl's load parses declares a namespace URI longer than 1,024 characters or a DTD: lxml copies the URI into the name of every element under it, which openpyxl reads for every element it parses, so 2,000 empty elements under a 1,000,000-character URI in a worksheet, a 5.9 KB file, took 3.8 s to read. Each part openpyxl's read-only load parses, found as openpyxl finds it (`[Content_Types].xml`, the workbook part and its relationships, the shared strings the manifest names, the core and custom document properties, the styles part, and every sheet's resolved part and relationships part), is now streamed once before anything parses it, without building a tree, through the parser that load uses for it: lxml for the skeleton, styles, properties, chartsheets and relationships, expat for worksheets and shared strings, and both for `[Content_Types].xml`, which msoffcrypto reads with minidom. Members nothing parses, such as images, are not read, so a workbook holding an SVG image with the SVG 1.1 DOCTYPE (as Illustrator and icon exports carry) is no longer refused. An expat part is read to its first syntax error, where the loader stops too (libxml2 stops at a name over 50,000 characters, or an attribute value or comment over 10 MB, that expat reads on: a worksheet with a 50,001-character element name before a 1,000,000-character URI used by 5,000 elements, a 5.9 KB file, was accepted by an lxml-only scan and took pandas 4.6 s to read), and an lxml part that lxml fails to parse is refused, since openpyxl's load fails on it too. Such a part is also refused when it is encoded in anything but UTF-8 (an optional UTF-8 byte-order mark, no NUL byte in its first 64 KiB, and no XML declaration or one naming UTF-8): the guard counts a part's `<` and `=` in bytes, and the parsers detect UTF-16 differently (expat reads a part whose first or second byte is zero as UTF-16 without a byte-order mark, where libxml2 fails, and libxml2 switches to UTF-16 after an ASCII declaration naming `UTF-16LE`, which expat rejects), so attribute names whose UTF-16 low byte is `<` slipped a start tag of 8.66 million attributes past the count and took the guard to 2.25 GB. OPC also allows UTF-16, but every producer surveyed (Excel, Word and PowerPoint, LibreOffice, openpyxl, XlsxWriter, python-docx, python-pptx, SheetJS) writes UTF-8, as do all 2,238 XML members of 88 local Office files, so a UTF-16 part, which openpyxl reads, is now refused too. openpyxl's lxml parse of a buffer also reads UTF-32, which lxml's push parser and expat reject at the first byte, so a UTF-32 `docProps/core.xml` with a 1,000,000-character URI over 20,000 elements, a 10 KB file, was accepted and took openpyxl 13 s or more to load; when its elements nest more than 256 deep (expat keeps about 145 bytes per open element and lxml's push parser about 36, and neither sets a limit as the scan drives them, so 1,000,000 levels of `<a>`, an 8 KB file, held 180 MB in the scan, and a 128 MiB part would hold about 8 GB; openpyxl's lxml tree parse stops at 256 itself); when a start tag may carry more than 65,536 attributes (counted as the `=` between two `<` before either parser sees the tag; one tag of 1,000,000 attributes, 11 MB, held about 175 MB); or when it uses more than 10,000 distinct element names, attribute names and namespace prefixes, which both parsers keep for the whole parse (1,000,000 distinct element names, 8.9 MB, held about 140 MB). The scan costs the guard about 6.5 s per 100 MB of worksheet XML, a Python call per element for the depth ceiling included (about 4 s before; pandas takes about 20 s to read such a sheet). With every styles list at its ceiling at once (a 51 MB part, 582 KB uploaded) the guard takes 14.5 s and openpyxl 14.6 s and 1.1 GB to load it. A styles part is also refused when it lists more than 8,192 fonts, fills or borders (Excel itself allows 512 fonts per workbook and 256 fill and line styles), when a number openpyxl reads from it is outside 32 bits (an integer below -2,147,483,648 or above 4,294,967,295, or a float of magnitude above 2^32, NaN or infinite; given as an attribute or as the text of a child element of the field's name, which openpyxl reads in place of the attribute even when that child has children of its own), or when more than two distinct style objects of one hash would land in one of the indexed lists openpyxl builds on load (fonts, fills, borders, alignments, protections, cell formats, format codes and named-style names), each entry being rebuilt with openpyxl's own classes to compute it: Python hashes numbers modulo 2^61 - 1, so fonts differing only in a charset of 1 + k(2^61 - 1), or in sizes x and x times 2^-61, are distinct objects of one hash that openpyxl compares with each other on every insertion and again as each named style binds them (4,000 such fonts, a 51 KB part, took 6.6 s to load, and 8,000 under 8,000 named styles 81 s). A 16 MB styles part with every list at these ceilings and 65,490 cell formats, each with its own alignment and protection, loads in about 5 s, and the guard's check of it takes about 10 s. A .pptx listing one slide part under several slide entries (python-pptx yields, and unstructured extracts, a slide once per entry) is refused, as is a .docx with more than 1,000 sections (`w:sectPr` elements anywhere in `document.xml`; Word writes one per section break), more than 20,000 rendered page breaks (`w:lastRenderedPageBreak` elements anywhere in `document.xml`: unstructured asks once per document whether there are any, with a four-branch union over the body's paragraphs and table cells whose libxml2 merge compares every break with every break of the branches before it, so 96,000 breaks in each of the two table-cell branches, about one text-extraction unit each, were accepted at ~0.9 of the text-extraction ceiling and would take ~18 s for the union alone (extrapolated from 0.77 s for 20,000 each); Word writes one per page in each flow of text a page boundary cuts, so a 1,000-page document of ten-column tables has about 10,000; the pairs are also priced in the text extraction, at 30 ns each, and so is the union's sort, which once a later branch's break precedes an earlier branch's walks the shared parent's children after the breaks: 1,000 breaks of each of two branches in table rows before 160,000 empty table children, a 42 KB file, took 2.2-2.6 s per evaluation and before 640,000, 10.5 s, counted at 0.02 of the text-extraction ceiling before; each element's union breaks times its child nodes, the breaks weighted for libxml2's binary-insertion runs (below 64 nodes, and for a branch's run shorter than its minimum run, it compares each node about log2(n) times: 62 breaks of one branch before one of another walked the filler 12 times per break), is now priced at 150 ns per step, covering siblings that lie a cache miss apart in memory, as filler elements with 16 or more attributes do (35-45 ns per sibling against 3-9 ns for plain ones; 1,000 breaks of each branch before 600,000 such elements, a 386 KB file, were accepted at 0.83 of the text-extraction ceiling at 30 ns per step, and one evaluation took 50 s), with the worst shapes measured at 70-95 ns per weighted step, so the sort costs about 30 s at the ceiling), any relationships part (`*.rels` member, whether or not the guard follows it to its part: the libraries parse the relationships part of every part they reach) with more than 10,000 entries (comments and processing instructions included) or over 16 MiB, or with an entry that has child elements or an element with more than 64 attributes (the OPC schema gives a relationship four attributes and no child elements; every relationships part, and every other part the guard streams or parses from a .docx or .pptx, is first held to UTF-8 and to start tags of at most 65,536 attributes, counted in its bytes before lxml reads it, since lxml's `iterparse` builds a start tag in full before any per-element ceiling sees it: one of 2,000,000 attributes in `document.xml`, 23 MB, held 404 MB in the guard, and a slide's was not refused at all; one entry holding 4 million empty children, a part no library reads that deflates to 16 KB, cost the guard 3.1 s and ~550 MB, and 30 such parts in a 499 KB file 92 s; each part is now streamed holding at most one entry), relationships parts with more than 50,000 entries together, more than 200 million steps of python-docx's relationship walk (internal relationships times members, each member a step plus one per 256 bytes of its name as Python stores it, one, two or four bytes per character by its widest character, since comparing two names reads them that way (names of four-byte characters were counted per character before, a quarter of their cost: 2,000 parts named by 2,000 emoji counted at 0.89 of the ceiling took 9.5 s to open): python-docx scans a list of the parts it has visited once per relationship as it opens a package, so 9,000 parts and one unread part with 200,000 relationships to the last of them, a 1.66 MB file, took 41 s to open; 9,000 parts with 19,000 internal relationships, counted at 0.91 of this ceiling, open in 3 s, and a document with 10,000 images counts about 110 million), or a settings or styles part (each found through the document's relationship of that type, as python-docx finds it) over 16 MiB or with more than 5,000 top-level entries (python-docx and unstructured repeat work once per section and once per paragraph, such as two scans of every document relationship and two searches of the settings part per section, and about four scans of the relationships and of the styles part per non-empty paragraph; rather than model each, these caps keep every such factor small). A .pptx is also refused when its slide placeholders would cost python-pptx's uncached layout and master lookups more than 90,000 units: unstructured reads the top and left of every slide shape up to three times each, and a placeholder without a position of its own inherits it, each read rebuilding the slide's relationships by type and building a proxy for every placeholder of the slide layout up to the matching one (and, when that one has no position either, for the slide master's), so the work is each slide's placeholders times its layout's and master's shapes, plus their shapes' children and grandchildren per 256 and the slide's and layout's relationships per 32 (100 placeholders over a 100-placeholder layout, a 30 KB file, took 5.2 s to partition and 200 over 200 took 18.6 s, quadrupling per doubling, and nothing counted them; a unit costs ~400-430 us, so about 40 s at the ceiling, and Office's default theme costs 34 units per title-and-content slide, so about 2,600 such slides fit); each slide, and each layout and master a slide's placeholders inherit from, is streamed once for this (a DTD in one is refused), and every relationships part of the presentation is held to 10,000 entries, and all of them to 50,000 together. A .docx is also refused when a table cell spans, or a row skips, more than 1,000 grid columns (`w:gridSpan`, `w:gridBefore`, `w:gridAfter`; Word's tables are at most 63 columns wide), or carries such a value python-docx cannot read: python-docx yields a cell once per spanned column and unstructured re-reads it per yield, so a 950-byte file with one cell spanning 400,000 columns took 53 s, and at 2^31 - 1 python-docx would build a ~17 GB tuple. It is refused outright when an element of `document.xml` carries more than 256 attributes or sees more than 256 namespace declarations in scope (its own and its ancestors'): writers put at most a few dozen attributes on an element (the most found in Word, LibreOffice and python-docx output was twelve) and Word declares about 35 namespaces, while lxml reads attribute values in time quadratic in their number (one paragraph of 50,000 empty attributes, a 145 KB file, kept the guard itself busy for 40 s before; the attributes are now counted before any is read) and libxml2 resolves every copied element's namespace by walking the declarations in scope (8,000 of them used by 8,000 elements took 0.6 s per copy, quadrupling per doubling). It is also refused outright when a namespace declaration's URI is longer than 1,024 characters or its prefix longer than 64 (checked where it is declared, before any name under it is read; Office namespaces are under 100 characters): lxml rebuilds every element and attribute name as "{URI}local" on each read, so one 8 MB URI used through a short prefix by 3,000 elements, a 44 KB file, ran the guard itself out of a 3 GB address space, and a 1 MB URI on 1,024 attribute names grew it by ~0.5 GB (the guard now also keeps only the URIs a paragraph uses, not every name); when a body-level paragraph holds more than 1,024 namespace declarations (Word declares up to five per inline picture, python-docx two): lxml's remove(), which python-docx calls on a paragraph copy per rendered page break, costs the square of the declarations in the removed subtree (40,000 one-declaration elements took 0.4-0.8 s per removal, and six page breaks before them, a 142 KB file, took 5 s to partition and were accepted); and when a table row has more than 256 cells (four times Word's 63-column maximum) or spans more than 2,048 grid columns: python-docx resolves a cell continuing a vertical merge by reading the span of every earlier cell in its row and searching the row above, recursively up the merge, so a merged row costs its width squared (two rows of 1,000 cells, the second all continuing, a 37 KB file, took 6-7 s per read of the cells, and unstructured reads them twice per table); and when a table row python-docx reads has more than 256 children that are not cells, or a table more than 256 children before or between two of its rows (elements, comments and processing instructions, `w:tblPr` and `w:tblGrid` included): every step up a vertical merge looks up its row's `grid_before` by scanning the row's children and finds the row above by walking every sibling between the two, so a row padded with 200,000 empty elements after its cell, a 1.6 KB file, took 7.6 s per read of the cells, and 64 merged columns with 200,000 empty elements between each two of 26 rows, an 81 KB file, took 58 s per read, accepted at 0.09 and 0.90 of the run-work ceiling. Word's rows carry `w:trPr`, `w:tblPrEx`, bookmark, comment, permission and proofing markers and at most one content-control or custom-XML wrapper per cell, and its tables nothing between rows but such markers and wrappers of row groups; the content of a wrapper, and anything after a table's last row, is not walked and not capped. It is also refused when the repeated work python-docx and unstructured would do, estimated by streaming document.xml once without building a tree (document.xml itself is bounded by the 128 MiB parsed-part ceiling), exceeds one of seven ceilings, each holding one known fan-out (one bounded part or element turned into many times its work or memory) to a measured order of magnitude, about 45 s or a few hundred MB at the slowest layout found: the section lookup (python-docx finds each section's paragraphs and tables with a reverse-axis XPath whose result libxml2 sorts by walking sibling links, costing up to (paragraphs and tables up to the section's end) x (body nodes) steps per section at ~5 ns while the body fits in cache and up to ~100 ns for a large body of attribute-heavy nodes, so the sum of that product over sections is held to 450 million; before, 1,240 paragraphs and 2 million three-attribute bookmarks, a 234 KiB file, were accepted and took 121 s); the section count times each section's linear work (body nodes, plus the nodes python-docx's `_sectPrs` XPath visits and the pairs its union compares, weighted), held to 10 million units; the header/footer references, each counted at the referenced part's size, held to 12 MiB (a read costs up to ~3.5 us per byte: 20 references to a 1.2 MB header of empty runs took ~73 s), plus the union steps each read evaluates in the part, at 29 steps per byte (a header holding a table before 8,000 empty paragraphs and 40,000 empty elements, referenced by ten sections, a 37 KB file, took 35 s and was counted at 0.23 of the ceiling before; the referenced parts are now streamed for this, once each); the style lookups, the non-empty paragraphs (and page-break fragments) times the styles part's entries (at least the 6 of python-docx's default styles part, which it creates when there is none) plus one per 32 of their attributes and one per 32 document relationships, held to 3 million (50 paragraphs beside 300,000 styles, an 805 KB file, took 132 s before); the page-break splitting, K x (K + 3) x S squared summed over paragraphs with K rendered page breaks and S the widest child list in them, held to 9 billion (one run with 600 page breaks, a 37 KB file, ran for over 180 s before); the text extraction, about five reads of every run and a walk of every table row and cell per paragraph fragment, with a table cell counted once per grid column it spans (multiplied through nested tables), its content other than runs included at one unit per 256 nodes (unstructured walks a cell's children once per yield: 30 rows of one cell spanning 1,000 columns with 60,000 empty elements, a 54 KB file, were accepted at 0.10 of the ceiling, and three such rows took 5 s to partition), its paragraphs and tables at one unit each per yield (an empty paragraph costs ~20 us per yield: 32,000 of them in one cell spanning 1,000 columns would take ~10 minutes and were counted at 0.09 of the ceiling), and the node-set unions python-docx evaluates over a cell's paragraphs and tables, a paragraph's runs and hyperlinks (for a body-level paragraph, with unstructured's third branch, the runs inside an inline drawing of each of its runs, whose nodes are not the paragraph's children, so the union is counted at (nodes selected) x max(child nodes, nodes selected): one run whose inline drawing holds a run, before 10,000 plain runs, a 37 KB file, was accepted at 0.04 of the ceiling and took 0.37 s per evaluation, and before 40,000, 8.9 s; the nodes inside those drawings are counted too, once per node selected, since sorting two runs of one drawing walks the drawing's nodes after them: a run and a hyperlink around a drawing holding 1,000 runs before 100,000 empty elements, a 38 KB file, took 0.31-0.39 s per evaluation at 0.04 of the ceiling) and a run's text elements (and, in a document with no sections, over the body's paragraphs and tables): libxml2 merges each union's branches and sorts the result in up to (nodes selected) x (child nodes) steps once a later branch's node precedes an earlier one's, up to ~115 ns per step and read measured end to end, so each step is priced at 120 ns and every cell's, paragraph's and run's union counted six times, multiplied like the rest of its work (one cell spanning 1,000 columns holding 16,000 empty paragraphs and 16,000 empty tables, a 37 KB file, was accepted at 0.09 of the ceiling and took ~1.5 s per yield, about 25 minutes; a hyperlink before 8,000 runs and 40,000 empty elements in one paragraph, 38 KB, was accepted at 0.03 and took 15 s, and 8,000 `w:t` before a `w:br` and 40,000 empty elements in one run 14 s, each quadrupling per doubling), a cell continuing a vertical merge also counting the largest earlier cell of its table (a cell continues exactly as python-docx and unstructured read it: the first `w:vMerge` of its first `w:tcPr`, with no `w:val` or `continue`; a cell carrying any other `w:vMerge`, even beside or after one that continues, is counted once per spanned column, and an encoding the guard read differently, such as `w:val="x"` on a cell spanning 1,000 columns, used to go uncounted), and a row its `gridBefore`/`gridAfter` columns and python-docx's steps up the vertical merges its cells continue (one step per row of the merge, each priced at the cells whose spans it reads and the nodes it walks: the two rows' nodes, the continuing row's children up to its first `w:trPr` and that `w:trPr`'s content wherever it sits (one after 256 continuing cells holding 100,000 children, a 38 KB file, added ~0.3 s per read at 0.04 of the ceiling), and the table's children between the two rows; from the spans and `gridBefore` as python-docx reads them: one column merged down 300 rows takes ~45,000 steps and 8 s to partition, and 64 columns merged down 50 rows took 42 s per read of the cells while the guard counted ~32,000 units of the 1.5 million before), held to 1.5 million units (120 paragraphs of 2,479 one-character runs, a 76 KB file, took 40 s, and the cost was bounded only by the 128 MiB part ceiling before); and the bytes copied beyond one read, held to 128 MiB: two copies of a paragraph per rendered page break (python-docx builds a preceding and a following fragment per break, each a deep copy of the rest of the paragraph, and unstructured keeps them until the paragraph is done; 80 breaks before 3 MB of text, a 40 KB file, kept ~230 MB more, and 250 breaks before 90 MB of text would keep ~22 GB), its text, attribute values, namespace declarations, 128 bytes per node and per declaration and 288 per attribute counted (a copied empty attribute keeps ~275 bytes: 20 breaks before 200 elements of 256 empty attributes, a 40 KB file, kept ~310 MB, and such attributes counted nothing before), plus the text after the paragraph and the declarations on the document and body elements of the namespaces it uses, which every copy carries (8 breaks before a 2 MB namespace URI, a 39 KB file, kept ~29 MB, and such declarations went uncounted before; a URI that long is now refused outright), and the text of a spanned cell once per extra column or of a merged cell once per continued row, at 64 bytes per byte of text, since unstructured keeps every copy as a string and twice more HTML-escaped in its row's and its table's HTML, where a `"` becomes `&quot;` and one emoji makes a string four bytes per character (up to 52 bytes per byte: 20 extra copies of a 1 MB cell of quotes and one emoji, a 38 KB file, kept ~1 GB and were counted as 20 MB before; 300 continued rows under a 1 MB cell, a 38 KB file, kept ~930 MB and took 21 s). A continued row is counted as a copy of the largest earlier cell of its table, so a table whose continued rows times that cell exceed about 2 MiB of text (200 continued rows beside a 10 KB cell) is refused even when the merged cells are small. The ceiling is a count, not a measurement: each item is priced at about the most its copy was measured to keep, and the shapes measured kept less than they were counted. The seven share one budget: a document whose works' shares of their ceilings sum to more than 1 is refused, so one near several ceilings at once costs no more than one at a single ceiling. These ceilings bound the fan-outs above, not a document's total parse time or memory, which stay linear in its elements and text with a large per-element cost (see the known gaps below). Because they price every step at the slowest layout measured and share one budget, they also refuse long ordinary documents that python-docx would partition in under a minute; measured on documents python-docx writes: a single section of more than about 11,300 one-run paragraphs, a Word-like document (300 styles, five sections, a table) of more than about 5,250-5,850 paragraphs of 5-10 formatted runs, or more than about 580 one-paragraph sections (about 180 ten-paragraph ones), as a mail merge to individual documents writes; likewise one table column merged down more than about 545 rows, or every cell of a 64-column table continuing down 27 rows (26 with cell widths set). Long theses and books can exceed these. A slide entry or header/footer reference that does not resolve is refused too, and so is a .docx/.pptx without `[Content_Types].xml` or whose main part, slides, priced slide layouts and masters, or styles, settings, header and footer parts do not carry the content type python-pptx/python-docx build that kind of part from (resolved from `[Content_Types].xml` as they resolve it: the part's `Override`, matched without regard to case, else the `Default` of its extension, a later entry winning): both libraries pick a part's class by its content type, not by the relationship that reaches it, so a slide's layout relationship pointing at another slide made python-pptx read that slide's own layout, which the guard never priced (300 placeholders over a 300-placeholder layout reached that way, a 33 KB file, were counted at 1,200 units instead of about 90,000), and a styles or settings relationship pointing at a second document part made python-docx read that part's styles or settings, past the 5,000-entry caps. Every XML part the guard parses or streams (package and part relationships, `presentation.xml`, `document.xml`, the `.docx` settings part and the header/footer parts its sections reference, and, in an `.xlsx`, every part openpyxl's load parses) is refused if it carries a document type declaration, with or without an internal subset: python-docx parses without resolving entities, so each entity reference stays in its tree as a node its per-section lookup walks, which the streaming count of `document.xml` cannot see; OPC (ECMA-376 Part 2) forbids DTDs in the parts it defines (content types, relationships, core properties), and Office writes none in the XML parts it generates; an SVG image it stores may keep one, but no loader parses images. The declaration is refused in the part's bytes, before any parser the guard drives reads it: any `<!` before the root element that does not open a comment is refused, while this check passes comments and processing instructions before the root, and comments, CDATA sections and processing instructions inside it (a CDATA section before the root is refused, and the part walkers refuse more than 64 comments and processing instructions outside the root, and the .xlsx checks refuse one nested deeper than directly under the root of the styles or a workbook skeleton part) (none of the 4,770 XML members of 257 local Office files, leaving out one attack file made for this change, has a declaration, a comment or a CDATA section). The check had run at the root element's first event, by which libxml2 has read the whole internal subset, and declarations need no `=` for the start-tag count to see: a 17.9 MB `document.xml` (or slide) of one million attribute declarations held 424 MB in the guard (a 128 MiB part about 3 GB; 6.8 million, 122 MiB deflating from 16 MiB, were reported at 2.5 GB and 12 s), a relationships, header or skeleton part of 9-15 MB held 190-280 MB, and attribute-list defaults for `xmlns:` names added namespace declarations to the root that its bytes did not show; an `.xlsx` part was refused at the parsers' doctype callbacks, but lxml's push parser had first buffered the whole subset. Each is now refused before its parser receives more than the `<!` of the declaration, at no measurable memory. Legacy .doc/.ppt uploads are converted only when they start with the OLE compound-file signature (anything else, such as a zip container renamed .doc, is refused before soffice runs), via a soffice wrapper with a 120 s process-group timeout, per-call profile isolation and a 512 MiB ceiling on the converted file it reads back (checked after soffice exits, so it limits what is read, not what soffice writes to the per-call temporary directory within the timeout); soffice's memory is not capped, so the timeout is its only resource bound. RTF/EPUB/RST/Org/ODT uploads convert to HTML via a sandboxed pandoc wrapper (`--sandbox` needs pandoc 2.15 or newer: the bundled pypandoc-binary ships pandoc 3, and with an older pandoc every such conversion fails rather than running unsandboxed) with a 90 s process-group timeout, a 2 GiB pandoc heap cap (on Linux, an address-space limit of heap plus 512 MiB when the pandoc build rejects RTS options), and an output file that is size-checked before it is read; ODT text is now extracted from pandoc's HTML rather than from an intermediate .docx, and .odt is offered whenever the ODT loader and the pandoc bridge are installed (python-docx is no longer needed for it). The wrapper locates pandoc the same way pypandoc does, so the bundled pypandoc-binary copy is used. Email (.eml) uploads now index the message body only: attachments are no longer partitioned, since unstructured otherwise hands each one to its own auto-partitioner outside these guards (a .doc/.ppt attachment to soffice and an .rtf/.rst/.org/.odt/.epub attachment to pandoc with no timeout or memory cap, a .docx/.pptx/.xlsx attachment to its parser without the zip-container checks); the same applies to an Outlook .msg uploaded as .eml. Previously these converters ran with no timeout (and pandoc with no memory cap) and the parsers read container entries of any size, so a hostile or pathological file could exhaust memory or pin an indexing worker indefinitely. Documents beyond these bounds, ordinary long or complex ones included, are now rejected instead of indexed (the upload reports "Could not extract text from docx file", or the file's type, and the server logs "Refused document: it exceeds the parsing limits for its format", with no file or entry name), for example a worksheet with more than 128 MiB of XML, a container over 1 GiB uncompressed, an archive using BZIP2/LZMA/ZSTD compression, a workbook listing one worksheet part under several sheet entries, a workbook with a number format code over 1,024 characters or more than 65,490 cell formats, a presentation listing one slide under several slide entries, a presentation of more than about 2,600 title-and-content slides under Office's default theme (fewer under templates with more shapes per layout and master), a .docx with more than 1,000 sections or 20,000 rendered page breaks, a .docx of more than about 5,000-11,000 paragraphs (see above), a table cell spanning more than 1,000 columns, a table row of more than 256 cells or 256 other children, an element with more than 256 attributes, a namespace URI of more than 1,024 characters, a paragraph with more than 1,024 namespace declarations, a paragraph whose rendered page breaks would copy more than 128 MiB, a styles part of more than 5,000 entries, or header/footer references totalling more than 12 MiB, a .doc that is really a zip container, a .docx/.pptx/.xlsx with a `mimetype` member or without its main part, or a pandoc-backed document with on the order of 10 MB of text or more, which needs more than 90 s or 2 GiB to convert with the bundled pandoc. Images and charts in .xlsx chartsheets were never indexed and are now not loaded either. Known gaps, not addressed here: .xlsx memory follows cell references rather than XML size, because pandas pads every row to the widest row (a few-KB workbook with cells XFD1 and A300 materialises 300 x 16384 cells, and XFD1 with A1048576 would need hundreds of GiB), and a shared string, stored once, is written out once per referencing cell by unstructured's `to_html`, so a long string referenced by many cells multiplies; repeated references inside pandoc's own readers (such as an EPUB spine listing one chapter many times) are not counted, leaving pandoc bounded by its heap cap and timeout only; the total parse time and memory of an accepted .docx are not bounded: they stay linear in its elements and text with a large per-element cost (about 0.6-2 ms for a trivial paragraph, 3-9 ms for an ordinary python-docx-written one: 11,300 one-run paragraphs took 31 s, 5,600 paragraphs of seven formatted runs beside 300 styles 49 s; 35-65 ms for text that triggers unstructured's per-element classification, where a US city/state/ZIP regex backtracks for ~40 ms on text starting with 80 or more letters without a space or comma and langdetect runs per element at ~25 ms when the document as a whole is not one language, so an accepted document of a few thousand such paragraphs runs for minutes; one 3 MB paragraph took 43 s and ~300 MB), which only a wall-clock and memory limit on the in-process parse would bound; and the in-process parsers (python-docx, python-pptx, openpyxl, pandas, unstructured) run with no timeout.
diff --git a/docs/library-and-rag.md b/docs/library-and-rag.md
index efdf34828d..42c2978c7b 100644
--- a/docs/library-and-rag.md
+++ b/docs/library-and-rag.md
@@ -37,7 +37,7 @@ Access the library at: `http://localhost:5000/library`
| Markdown | `.md`, `.markdown` | Rendered as text |
| HTML | `.html`, `.htm` | Tags stripped, text extracted |
| Word | `.docx` (and `.doc`*) | Text extracted via `unstructured` |
-| OpenDocument Text | `.odt` | Text extracted via `unstructured` |
+| OpenDocument Text | `.odt` | Converted to HTML with pandoc, then text extracted |
| PowerPoint | `.pptx` (and `.ppt`*) | Slide text extracted |
| Excel | `.xlsx`, `.xls` | Cell text extracted |
| Rich Text | `.rtf` | Text extracted |
@@ -52,12 +52,47 @@ server can actually parse (`GET /library/api/config/supported-formats`), so it
only offers formats whose parser dependencies are installed.
\* The legacy binary formats `.doc` and `.ppt` are offered **only** when
-LibreOffice (`soffice`) is installed, because `unstructured` converts them to
-the modern format with it. Image formats (`.png`, `.jpg`, …) are offered
-**only** when the optional OCR extras (`pytesseract` plus the `tesseract`
+LibreOffice (`soffice`) is installed: Local Deep Research converts each one to
+`.docx`/`.pptx` with `soffice` itself (with a 120-second timeout) and then
+extracts the converted file like any other upload. Only a genuine legacy file
+is converted: one that does not start with the OLE compound-file signature
+(for example a `.docx` renamed to `.doc`) is refused. Image formats (`.png`,
+`.jpg`, …) are offered **only** when the optional OCR extras (`pytesseract` plus the `tesseract`
system binary) are installed. The default Docker image ships neither, so those
formats are not offered there.
+Office, OpenDocument and EPUB uploads are size- and structure-checked before
+they are parsed, and long or complex documents are refused instead of indexed,
+not only hostile ones. In particular, a `.docx` of more than roughly 5,000 to
+11,000 paragraphs (about 5,250 for a Word-like document of paragraphs of 5-10
+formatted runs, about 11,300 for plain one-run paragraphs), with more
+than about 580 sections of one paragraph each (as a mail merge to individual
+documents writes; never more than 1,000 sections) or more than 20,000
+rendered page breaks, with a table column
+merged down more than about 545 rows, a `.pptx` of more than about 2,600
+title-and-content slides (fewer under templates with many shapes per layout),
+or an `.xlsx` of more than 2,000 sheets (or with more cell formats, or a
+longer number format code, than Excel itself writes, with more than
+8,192 fonts, fills or borders or 8,192 custom number formats, or with more than roughly 17,000 to
+30,000 named styles, fewer with many custom number formats, or with a sheet
+name over 255 characters, two sheets of the same name, a defined name over
+8,192 characters, or a part openpyxl reads that is encoded in anything but
+UTF-8 or nests elements more than 256 deep) is refused, as is a `.docx` or
+`.pptx` with a part the checks read that is not UTF-8 (Office, LibreOffice and
+the Python libraries write UTF-8; UTF-16, which OPC also allows, is refused).
+The upload then reports "Could not extract text from docx file"
+(or `pptx`, and so on) for that file, and the server log records "Refused
+document: it exceeds the parsing limits for its format". Splitting can help
+with size and complexity limits; for a package with UTF-16 XML parts, resave
+the document in Office or LibreOffice to produce UTF-8 parts. The release
+notes list every limit.
+
+`.rtf`, `.epub`, `.rst`, `.org` and `.odt` uploads are converted with pandoc
+run with `--sandbox`, which needs pandoc 2.15 or newer: the bundled
+`pypandoc-binary` ships a pandoc 3 build, but if an older pandoc is found
+instead, every such conversion fails (the file is refused, never converted
+without the sandbox).
+
### Uploading Documents
1. Navigate to **Library** in the sidebar
diff --git a/src/local_deep_research/document_loaders/bytes_loader.py b/src/local_deep_research/document_loaders/bytes_loader.py
index 7446a84029..f6e8d37771 100644
--- a/src/local_deep_research/document_loaders/bytes_loader.py
+++ b/src/local_deep_research/document_loaders/bytes_loader.py
@@ -14,10 +14,27 @@ from loguru import logger
from local_deep_research.security.filename_sanitizer import sanitize_filename
+from .openpyxl_hardening import disable_openpyxl_drawing_reads
+from .zip_container_guard import (
+ DecompressionBombError,
+ validate_zip_container,
+)
+
from .loader_registry import (
get_loader_class_for_extension,
is_extension_supported,
)
+from ..utilities.office_conversion import (
+ OfficeConversionError,
+ convert_legacy_office_bytes,
+ converted_extension,
+ is_legacy_office_extension,
+)
+from ..utilities.pandoc_conversion import (
+ PandocConversionError,
+ is_pandoc_backed_extension,
+ pandoc_convert_bytes_to_html,
+)
def load_from_bytes(
@@ -62,6 +79,41 @@ def load_from_bytes(
if not is_extension_supported(ext):
raise ValueError(f"Unsupported file extension: {ext}")
+ # Legacy OLE binaries (.doc/.ppt) convert through a bounded soffice
+ # subprocess FIRST: the raw bytes are not zip containers, and the
+ # converted output then flows through the same zip guard as any
+ # other container below. The converter refuses input without the
+ # OLE signature, so a zip renamed .doc/.ppt never reaches soffice.
+ if is_legacy_office_extension(ext):
+ content = convert_legacy_office_bytes(content, ext)
+ ext = converted_extension(ext)
+
+ # Zip-container documents (.docx/.xlsx/.odt) decompress inside the
+ # parsers, whose reads are bounded only by the archive's declared
+ # entry sizes — the request-body cap never sees the expanded side.
+ # Refuse hostile declarations before any parser runs. This bounds
+ # archive reads and specific fan-outs, not parser memory or time in
+ # general (see "Known gaps" in zip_container_guard). This runs
+ # BEFORE the pandoc conversion below so an .epub container is
+ # guarded as the original archive.
+ validate_zip_container(content, ext)
+
+ # openpyxl re-reads an image once per drawing reference and keeps
+ # every copy, which no per-entry ceiling bounds; drawings carry no
+ # text, so the .xlsx path never reads them.
+ if ext == ".xlsx" and not disable_openpyxl_drawing_reads():
+ raise DecompressionBombError(
+ "Cannot safely read .xlsx: openpyxl drawing guard unavailable"
+ )
+
+ # Pandoc-backed formats (.rtf/.epub/.rst/.org/.odt) convert to HTML
+ # through a bounded subprocess (timeout, heap cap, output ceiling)
+ # before the HTML loader parses them; their registered unstructured
+ # loaders would otherwise run pandoc with no bounds at all.
+ if is_pandoc_backed_extension(ext):
+ content = pandoc_convert_bytes_to_html(content, ext)
+ ext = ".html"
+
# Get the loader class for this extension
loader_info = get_loader_class_for_extension(ext)
if loader_info is None:
@@ -142,6 +194,32 @@ def extract_text_from_bytes(
doc.page_content for doc in documents if doc.page_content
)
return None
+ except DecompressionBombError:
+ # Every refusal of the zip-container guard lands here, ordinary
+ # documents over its size, structure or parsing-work limits as
+ # well as hostile ones, so the log names no cause; it is logged
+ # without the user-controlled filename, entry names or the
+ # exception's message (which can carry an entry name), and
+ # surfaces to the upload route as a per-file error entry.
+ logger.warning(
+ "Refused document: it exceeds the parsing limits for its "
+ "format (size, structure or estimated parsing work)"
+ )
+ return None
+ except OfficeConversionError:
+ # Timed-out, failed, or oversized legacy conversion: scrubbed
+ # message only, no user-controlled content.
+ logger.warning(
+ "Rejected legacy office document: conversion failed, timed "
+ "out, or produced an oversized result"
+ )
+ return None
+ except PandocConversionError:
+ logger.warning(
+ "Rejected pandoc-backed document: conversion failed, timed "
+ "out, or produced an oversized result"
+ )
+ return None
except ValueError:
logger.warning(
f"No text extracted from {filename}: unsupported format or "
diff --git a/src/local_deep_research/document_loaders/loader_registry.py b/src/local_deep_research/document_loaders/loader_registry.py
index 3bd844039e..e9cc61b4c2 100644
--- a/src/local_deep_research/document_loaders/loader_registry.py
+++ b/src/local_deep_research/document_loaders/loader_registry.py
@@ -112,7 +112,7 @@ def _module_available(module_name: str) -> bool:
# advertises formats that will really extract text. Missing deps mean the
# format is omitted and the upload path returns a clear "Unsupported format"
# instead of a swallowed extraction failure.
-HAS_DOCX_DEP = _module_available("docx") # python-docx: .docx/.odt
+HAS_DOCX_DEP = _module_available("docx") # python-docx: .docx
HAS_PPTX_DEP = _module_available("pptx") # python-pptx: .pptx
# Legacy OLE binary office formats (.doc/.ppt) are NOT read by python-docx/
# python-pptx; unstructured converts them to the modern format by shelling out
@@ -131,7 +131,7 @@ HAS_XLSX_DEP = _module_available("openpyxl") and _module_available(
HAS_XLS_DEP = _module_available("xlrd") # xlrd: .xls
HAS_PANDOC_DEP = _module_available(
"pypandoc"
-) # pandoc bridge: epub/rtf/rst/org
+) # pandoc bridge: epub/rtf/rst/org/odt
HAS_OCR_DEP = _module_available("pytesseract") or _module_available(
"unstructured.pytesseract"
) # tesseract OCR for image formats (also needs the tesseract binary)
@@ -205,8 +205,12 @@ if HAS_XLS_DEP:
"loader_kwargs": {},
}
-# ODT - the unstructured ODT partitioner imports python-docx internally
-if HAS_ODT_LOADER and HAS_DOCX_DEP:
+# ODT - uploads convert odt -> HTML through the bounded pandoc wrapper
+# (utilities/pandoc_conversion), exactly like EPUB/RTF/RST/Org below, so
+# ODT is gated on the same pandoc bridge. python-docx is no longer on
+# the ODT path (unstructured's partition_odt, which needed it, is not
+# used for uploads).
+if HAS_ODT_LOADER and HAS_PANDOC_DEP:
LOADER_REGISTRY[".odt"] = {
"loader_class": UnstructuredODTLoader,
"loader_kwargs": {},
@@ -259,10 +263,17 @@ if HAS_ORG_LOADER and HAS_PANDOC_DEP:
"loader_kwargs": {},
}
-# Email files
+# Email files. Attachments are NOT partitioned: unstructured's partition_email
+# (and partition_msg, which UnstructuredEmailLoader dispatches to when the
+# content sniffs as an Outlook .msg) default to process_attachments=True and
+# hand every attachment to unstructured.partition.auto.partition. That path
+# bypasses load_from_bytes and its guards: .doc/.ppt attachments reach soffice
+# with no timeout, .rtf/.rst/.org/.odt/.epub reach pypandoc with no timeout or
+# heap cap, and .docx/.pptx/.xlsx reach their parsers without the zip-container
+# guard. Only the message body is indexed.
LOADER_REGISTRY[".eml"] = {
"loader_class": UnstructuredEmailLoader,
- "loader_kwargs": {},
+ "loader_kwargs": {"process_attachments": False},
}
# TSV (Tab-Separated Values) - the CSV loader with a tab delimiter
@@ -351,6 +362,15 @@ def get_loader_for_path(file_path: str | Path) -> Optional[BaseLoader]:
Returns:
A LangChain BaseLoader instance, or None if the extension is not supported
+
+ Warning:
+ This returns the raw registered loader and bypasses every bound
+ that ``bytes_loader.load_from_bytes`` applies: the zip-container
+ decompression guard, the bounded soffice conversion for
+ ``.doc``/``.ppt``, and the bounded pandoc conversion for
+ ``.rtf``/``.epub``/``.rst``/``.org``/``.odt`` (whose unstructured
+ loaders run pandoc with no timeout or memory cap). Never use it
+ on untrusted files; route those through ``load_from_bytes``.
"""
file_path = Path(file_path)
extension = file_path.suffix.lower()
diff --git a/src/local_deep_research/document_loaders/openpyxl_hardening.py b/src/local_deep_research/document_loaders/openpyxl_hardening.py
new file mode 100644
index 0000000000..b167905af1
--- /dev/null
+++ b/src/local_deep_research/document_loaders/openpyxl_hardening.py
@@ -0,0 +1,58 @@
+"""Stop openpyxl from reading chartsheet drawings (images and charts).
+
+``.xlsx`` text extraction goes unstructured ``partition_xlsx`` ->
+``pandas.read_excel`` -> ``openpyxl.load_workbook(read_only=True)``.
+Even in read-only mode openpyxl loads every chartsheet's drawing via
+``openpyxl.reader.drawings.find_images``, which calls
+``archive.read(target)`` once **per image reference** and keeps every
+copy (and parses a chart part once per chart reference). One image
+entry referenced N times therefore costs N times its size: a ~100 KB
+upload can pin gigabytes, which no per-entry ceiling can bound.
+
+Images and charts contribute no text, and this application uses
+openpyxl only to extract text, so the reader's drawing hook is replaced
+with one that returns nothing. That removes the per-reference reads at
+their source instead of trying to count references in attacker-written
+XML. (Worksheet drawings are only read outside read-only mode, which
+this path never uses.)
+
+The patch is **process-wide and permanent**: once the first ``.xlsx``
+upload is processed, every openpyxl workbook loaded anywhere in this
+process has no images or charts. Nothing else in the application reads
+workbooks with openpyxl; anything added later that needs drawings must
+load them some other way.
+"""
+
+from __future__ import annotations
+
+from loguru import logger
+
+
+def _no_drawings(archive, path): # noqa: ARG001 - signature of find_images
+ """Stand-in for ``openpyxl.reader.drawings.find_images``."""
+ return [], []
+
+
+def disable_openpyxl_drawing_reads() -> bool:
+ """Replace openpyxl's drawing reader with a no-op (idempotent).
+
+ Returns True when the hook is in place. Returns False, with a
+ warning, when openpyxl is missing or no longer exposes the hook.
+ The upload caller refuses .xlsx files in that case.
+ """
+ try:
+ import openpyxl.reader.excel as excel_reader
+ except ImportError:
+ return False
+ # Checked by identity rather than a flag, so a reload of openpyxl
+ # (which restores the original hook) is patched again.
+ if getattr(excel_reader, "find_images", None) is _no_drawings:
+ return True
+ if not hasattr(excel_reader, "find_images"):
+ logger.warning(
+ "openpyxl no longer exposes reader.excel.find_images; "
+ ".xlsx drawings are read on load again"
+ )
+ return False
+ excel_reader.find_images = _no_drawings
+ return True
diff --git a/src/local_deep_research/document_loaders/zip_container_guard.py b/src/local_deep_research/document_loaders/zip_container_guard.py
new file mode 100644
index 0000000000..690dcb1a91
--- /dev/null
+++ b/src/local_deep_research/document_loaders/zip_container_guard.py
@@ -0,0 +1,5831 @@
+"""Decompression-bomb guard for zip-container document uploads.
+
+``.docx``/``.xlsx``/``.pptx``/``.odt``/``.epub`` files are zip
+containers of XML parts, while the upload route's caps bound only the
+*compressed* request body. A modest container can therefore declare —
+or, with lying headers, secretly contain — gigabytes of XML and OOM
+the indexing worker: the same class as the OpenAlex partition caps and
+the PDF extraction ceilings.
+
+What the guard checks, before any parser sees the bytes:
+
+0. **Anchoring**: the upload starts with a zip local file header (or,
+ for an empty archive, the end-of-central-directory record) and the
+ first entry's local header sits at offset 0. zipfile locates the
+ central directory from the *end* of the file and tolerates data in
+ front of the archive, so without this a legacy OLE ``.doc``/``.ppt``
+ with a small zip appended would pass as ``.docx``/``.pptx`` — and
+ unstructured, which sniffs the leading bytes, would then route it to
+ its own unbounded soffice conversion.
+1. **Declarations** (central directory only, no decompression): a
+ declared central-directory byte span of at most ``max_entries``
+ kibibytes, read from the end-of-central-directory (and ZIP64)
+ records before ``zipfile`` walks them — zipfile materialises every
+ record before the entry ceiling can count them, and the EOCD's
+ record count wraps at 65,535 and is ignored by zipfile, so only
+ the declared span bounds the walk up front; at
+ most ``MAX_ENTRIES`` entries; only STORED or DEFLATE compression
+ (CPython's zipfile decompresses BZIP2/LZMA/ZSTD chunks with no
+ output limit); no encrypted entries; a STORED entry's compressed
+ size equals its declared size and a DEFLATE entry's is within a
+ small slack of it (a full read copies the whole compressed range);
+ no two entries share a local header; every member name is
+ canonical (no empty, ``.`` or ``..`` segments, so no ``//``, ``/./``
+ or leading ``/``; no backslash) and unique, because readers
+ normalise such names onto one path (zipfile itself truncates a name
+ at NUL, so NUL-truncated names that collide are caught as
+ duplicates); no entry declares more than
+ the largest per-entry ceiling; and at most ``MAX_CONTAINER_BYTES``
+ declared across all entries.
+2. **Honesty of the declarations**: every entry's local header must
+ agree with its central-directory record (method, flags, CRC, both
+ sizes, name; with a data descriptor, the descriptor must repeat the
+ central CRC and sizes), because pandoc's zip reader follows the
+ local header where zipfile follows the central directory. Every
+ DEFLATE entry is then inflated once, in bounded steps (a few MiB of
+ memory, at most the declared total of work), and refused unless the
+ stream ends exactly at the end of its compressed range having
+ produced exactly the declared size with the declared CRC; a STORED
+ entry's size is fixed by its equality check in step 1 and its CRC is
+ checked too. zipfile only
+ truncates to the declared size *after* inflating a chunk, and a
+ full ``read()`` inflates an entry's whole compressed range in one
+ step, so without this a DEFLATE entry declaring 100 bytes could
+ still materialize gigabytes inside a parser.
+3. **Per-kind ceilings** on the verified sizes: a parsed part (XML or
+ any non-media entry) at most ``MAX_ENTRY_BYTES`` and parsed parts at
+ most ``MAX_TOTAL_BYTES`` in total; a binary media entry at most
+ ``MAX_MEDIA_ENTRY_BYTES`` — media ceilings apply to
+ ``.docx``/``.pptx``/``.xlsx`` only (``MEDIA_CEILING_EXTENSIONS``).
+ Media classification is described below.
+4. **Sheet fan-out** (``.xlsx`` only): openpyxl converts a sheet part
+ once per ``<sheet>`` that resolves to it, so a workbook whose sheets
+ resolve to the same part more than once is refused. The sheet list
+ comes from openpyxl's own ``ExcelReader`` / ``WorkbookParser`` (the
+ steps and options ``load_workbook`` uses under pandas), not from a
+ re-implementation, so the guard cannot disagree with the loader
+ about tags, attributes, the workbook's location, relationship
+ resolution (including ``TargetMode="External"`` targets, which
+ openpyxl keeps unresolved) or XML decoding. Sheets must also have
+ distinct relationships parts as computed by openpyxl's
+ ``get_rels_path``, which openpyxl parses once per sheet. Only
+ ``[Content_Types].xml``, the workbook part and its relationships are
+ parsed, each first held to ``MAX_XLSX_SKELETON_PART_BYTES`` so this
+ extra full-tree parse stays cheap; any openpyxl failure there is
+ refused as malformed. A comment or processing instruction below the
+ root's children of one of these parts or of ``xl/styles.xml`` is
+ refused (``_refuse_xlsx_nested_node``): openpyxl builds every child
+ node of a list such as ``fonts`` or ``bookViews`` into an entry, while
+ the guard counts elements. openpyxl also builds an object from every
+ entry of every list of the styles and workbook parts and from every
+ child it knows of every other element (keeping the last of a
+ repeated one), so each list of the two parts is capped
+ (``_xlsx_list_cap``; the workbook's defined names as
+ ``_check_xlsx_defined_names`` holds them), as are the elements under
+ each root (``MAX_XLSX_TOP_LEVEL_ELEMENTS``), the elements under
+ ``dxfs``, the gradient stops in all and the elements of one font,
+ fill, border or cell-format entry (``MAX_XLSX_STYLE_ENTRY_ELEMENTS``),
+ and an element that is not a list may not repeat a child's local
+ name (``_refuse_xlsx_repeated_child``). openpyxl parses the print
+ titles and print areas among the defined names with regular
+ expressions in time quadratic in their length, on every load, so
+ each defined name is held to ``MAX_XLSX_DEFINED_NAME_CHARS`` and
+ the print names together to ``MAX_XLSX_PRINT_NAME_WORK``. A workbook
+ listing more than ``MAX_XLSX_SHEETS`` sheets is refused: openpyxl
+ and pandas do work per sheet that grows with the members and with
+ the sheets; so is one with a sheet name over
+ ``MAX_XLSX_SHEET_NAME_CHARS`` characters or two sheets of one name
+ (lowercased). Before openpyxl parses any part, and before any part
+ the guard parses, each part openpyxl's read-only load parses (found
+ as it finds them: ``[Content_Types].xml``, the workbook part and its
+ relationships, then the shared strings the manifest names, the core
+ and custom document properties, the styles part, and every sheet's
+ resolved part and relationships part; ``_xlsx_loaded_parts``) is
+ streamed once with the parser that load uses for it, lxml or expat
+ (``[Content_Types].xml`` with both, for msoffcrypto's minidom), and
+ no other member is (``_check_xlsx_namespaces``): an encoding other
+ than UTF-8 (``_require_utf8_xml``; the parsers detect and decode
+ others differently, and the guard counts bytes), a namespace URI over ``MAX_XLSX_NAMESPACE_URI_CHARS`` characters,
+ which lxml and expat copy into the name of every element under it,
+ a DTD, nesting deeper than ``MAX_XLSX_XML_DEPTH``, a start tag of
+ more than ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` attributes or more than
+ ``MAX_XLSX_PART_NAMES`` distinct names (state both parsers keep per
+ open element, attribute and name) is refused, as is an lxml part
+ that lxml fails to parse (openpyxl's load fails on it too); an expat
+ part is read up to its first syntax error, where the loader's parse
+ ends. The
+ styles part ``xl/styles.xml``, which openpyxl loads on every read,
+ is streamed once (``_check_xlsx_styles``): a number format code over
+ ``MAX_XLSX_NUMBER_FORMAT_CHARS`` characters, a cell-format list of
+ more than ``MAX_XLSX_CELL_FORMATS`` entries, a gradient fill of more
+ than ``MAX_XLSX_GRADIENT_STOPS`` stops, more than
+ ``MAX_XLSX_STYLE_LIST_ENTRIES`` fonts, fills or borders, a numeric
+ field outside 32 bits, more than ``MAX_XLSX_STYLE_HASH_CHAIN``
+ distinct style objects of one hash in an indexed list openpyxl
+ builds (each entry is rebuilt with openpyxl's classes to compute
+ it), or a format code, cell-format
+ id or named-style field given as a child element (which openpyxl
+ reads in place of the attribute) is refused, as is a stylesheet
+ whose date tests over the cell formats' codes exceed
+ ``MAX_XLSX_NUMBER_FORMAT_WORK`` or whose named styles, each priced
+ at a fixed cost plus the custom formats and the largest font, fill
+ and border it can bind, exceed ``MAX_XLSX_NAMED_STYLE_WORK``
+ (openpyxl repeats both per cell format or named style).
+5. **Slide and section fan-out** (``.pptx``/``.docx``): a presentation
+ listing one slide part under several ``<p:sldId>`` entries is
+ refused, as is one whose slide placeholders would cost python-pptx's
+ uncached layout and master lookups more than
+ ``MAX_PPTX_PLACEHOLDER_WORK`` (each slide's placeholders times the
+ shapes, nodes and relationships one inherited position read walks;
+ every slide is streamed once for this, as is every slide layout and
+ slide master a slide with placeholders inherits from). Every
+ relationships part of a presentation or document is streamed and,
+ like every other part the guard streams or parses from a
+ presentation or document, first held to UTF-8 and to start tags of
+ at most ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` attributes, counted in its
+ bytes before lxml reads them (``_CountedXmlStream``; lxml's
+ ``iterparse`` builds a start tag's element in full, with no limit,
+ before any per-element ceiling sees it), then held to ``MAX_PART_RELATIONSHIPS`` entries (comments and processing
+ instructions included; an entry with child elements, or any element
+ with more than ``MAX_RELS_ELEMENT_ATTRIBUTES`` attributes, is
+ refused) and all of them together to
+ ``MAX_PACKAGE_RELATIONSHIPS``, and a document's internal
+ relationships times its members to ``MAX_DOCX_RELATIONSHIP_WALK``
+ (python-docx scans a list of the parts it has visited once per
+ relationship as it opens the package). The parts the guard reaches through
+ relationships (the main part; a presentation's slides and the
+ layouts and masters it prices; a document's styles, settings,
+ header and footer parts) must carry the content type, resolved from
+ ``[Content_Types].xml`` as the libraries resolve it, that the
+ library builds such a part from: python-pptx and python-docx pick a
+ part's class by content type, and a slide or document part standing
+ in for a layout, styles or settings part makes the library follow
+ that part's own relationship to one the guard never priced (see
+ ``_require_content_type``). A document is refused when it has more than
+ ``MAX_DOCX_SECTIONS`` ``w:sectPr`` elements or more than
+ ``MAX_DOCX_PAGE_BREAKS`` ``w:lastRenderedPageBreak`` elements, when its
+ settings or styles part is over
+ ``MAX_OPC_SKELETON_PART_BYTES`` or has more than
+ ``MAX_DOCX_SETTINGS_CHILDREN`` or ``MAX_DOCX_STYLES`` top-level
+ children, when a table cell spans, or a row skips, more than
+ ``MAX_DOCX_GRID_SPAN`` grid columns, when a table row has more than
+ ``MAX_DOCX_ROW_CELLS`` cells or spans more than
+ ``MAX_DOCX_ROW_GRID_COLUMNS`` columns, when a table row has more
+ than ``MAX_DOCX_ROW_OTHER_CHILDREN`` other children or a table more
+ than ``MAX_DOCX_TABLE_ROW_GAP`` children between (or before) two of
+ its rows, when an element of
+ ``document.xml`` carries more than ``MAX_DOCX_ELEMENT_ATTRIBUTES``
+ attributes or sees more than ``MAX_DOCX_NAMESPACES_IN_SCOPE``
+ namespace declarations in scope, when a body-level paragraph holds
+ more than ``MAX_DOCX_PARAGRAPH_NAMESPACES`` declarations, or when a
+ declaration's URI or prefix is longer than
+ ``MAX_DOCX_NAMESPACE_URI_CHARS`` or ``MAX_DOCX_NAMESPACE_PREFIX_CHARS``
+ (abnormal input no writer produces, refused outright rather than
+ priced), or when python-docx's and
+ unstructured's repeated work, estimated from one streaming pass over
+ ``document.xml``, exceeds a ceiling: the section lookup over the
+ body (``MAX_DOCX_SECTION_BLOCK_WORK``, ``MAX_DOCX_SECTION_WORK``),
+ the header/footer parts its sections reference, counted per
+ reference with the node-set unions each read evaluates
+ (``MAX_DOCX_HEADER_FOOTER_BYTES``), the style lookups per
+ paragraph (``MAX_DOCX_STYLE_WORK``), the splitting of paragraphs at
+ rendered page breaks (``MAX_DOCX_PAGE_BREAK_WORK``), the text
+ extraction from runs and table cells, once per spanned column, with
+ each cell's paragraphs and tables, the node-set unions python-docx
+ evaluates over a cell's, a paragraph's and a run's children (and,
+ in a document with no sections, the body's; and unstructured's
+ page-break union over the whole body and its paragraph-text union,
+ whose third branch reaches runs in inline drawings) and
+ python-docx's steps up vertical merges (``MAX_DOCX_RUN_WORK``), and
+ the bytes copied per page break,
+ spanned column and continued merged cell
+ (``MAX_DOCX_COPIED_BYTES``). These are the fan-outs that turn one
+ bounded part or element into many times its work or memory; each
+ ceiling holds its fan-out to a measured order of magnitude (about
+ 45 s, or a few hundred MB, at the slowest layout found), and the
+ seven share one budget: the work's shares of their ceilings may sum
+ to at most 1 (see ``_check_pptx_slide_fan_out`` and
+ ``_check_docx_section_fan_out``). They do not bound a document's
+ total parse time or memory (see "Known gaps").
+6. **Package type** (``.docx``/``.pptx``/``.xlsx``, and the
+ ``mimetype`` of ``.odt``/``.epub``): langchain's Word and PowerPoint
+ loaders ask unstructured's ``detect_filetype`` for the type (when
+ python-magic imports) and send a file it calls DOC or PPT to soffice
+ with no timeout, whatever the extension. An OOXML package is
+ therefore refused when it has a root ``mimetype`` member, when its
+ member names would not make the detector name its extension, when
+ an ``.xlsx`` has no ``xl/workbook.xml`` (pandas would pick another
+ engine), or when a ``.docx``/``.pptx`` has no main document part as
+ python-docx/python-pptx resolve it; an ``.odt``/``.epub`` whose
+ ``mimetype`` member names another type is refused too (see
+ ``_check_package_type``).
+
+Containers the stdlib cannot list or read, and spreadsheet packages
+openpyxl cannot resolve, are refused as ``DecompressionBombError``
+(fail closed) for the failure types caught in
+``validate_zip_container`` and ``_check_xlsx_sheet_fan_out``.
+
+What this bounds, and what it does not:
+
+- **In-process Python parsers** (python-docx, python-pptx, openpyxl,
+ unstructured for ``.docx``/``.xlsx``/``.pptx``): each *read* of an
+ entry now yields at most its (verified) declared size. It does not
+ bound parser memory or parser time. For an XML parse tree alone the
+ cost is a multiple of the XML size (around 10x measured for
+ text-heavy ``.docx``, more for many small elements), which is why the
+ parsed-part ceilings sit well under a worker's memory; but what the
+ loaders build *from* that tree can be far larger than the XML and is
+ not bounded here (see "Known gaps" below). python-docx/-pptx parse
+ with lxml ``resolve_entities=False``, openpyxl uses its safe parser,
+ and libxml2/expat enforce their own amplification limits, so entities
+ are not expanded; but an unexpanded entity reference stays in
+ python-docx's tree as a node its per-section XPath walks, and the
+ streaming count of that work (step 5) sees no event for it. Every XML
+ part the guard parses or streams (OPC relationships,
+ ``presentation.xml``, the slides and the slide layouts and masters
+ their placeholders inherit from, ``document.xml``, the ``.docx`` settings part
+ and the header/footer parts its sections reference, and the ``.xlsx`` parts
+ openpyxl's reader parses for the sheet check and ``xl/styles.xml``) is
+ therefore refused if it carries a
+ document type declaration, which is the only way to declare an
+ entity; OPC (ECMA-376 Part 2) forbids DTDs in the parts it defines
+ (content types, relationships, core properties), and Office writes
+ none in the XML parts it generates (an SVG image it stores may carry
+ one, but no loader parses images). The declaration is refused in the
+ part's bytes, before any parser the guard drives receives it
+ (``_XmlProlog``): libxml2 reads a whole internal subset before the
+ root element's first event, and the attribute defaults it declares
+ add attributes to start tags whose bytes show none. Parts the guard
+ does not read are not checked. How *often* a parser reads an entry is bounded only
+ where a fan-out is known and closed: shared sheet parts and
+ per-format stylesheet work in ``.xlsx`` (step 4), repeated slides and per-section, per-paragraph, per-page-
+ break and per-spanned-column work and header/footer repeats in
+ ``.pptx``/``.docx`` (step 5), and openpyxl's per-reference drawing
+ reads (below).
+- **Binary media** (images, audio/video, fonts, embedded packages):
+ python-pptx and python-docx load each package part once, however
+ many times it is referenced, and keep it as an opaque blob — about
+ 1x its size (measured for one and for eight references to the same
+ image). openpyxl would instead re-read a chartsheet drawing's image
+ once per reference and keep every copy; the ``.xlsx`` path disables
+ openpyxl's drawing reader (see ``openpyxl_hardening``; in the
+ read-only mode pandas uses, chartsheet drawings are the only
+ drawings openpyxl reads), so ``.xlsx`` media is not read at all.
+ Only an entry of an OOXML container whose first bytes carry a known
+ binary signature earns the media ceiling — never a name: part names
+ are attacker-chosen and packages dispatch parts by content type.
+ Each signature is anchored so that no XML parser the in-process
+ loaders use (lxml/expat) accepts it as a document start. EPUB and
+ ODT entries never earn it: pandoc reads an EPUB chapter by its
+ declared media type, not its bytes. All but two
+ (ISO BMFF and EMF) are fixed prefixes that start with neither
+ ``<``, whitespace nor a complete BOM (JPEG's ``FF D8`` shares only
+ its first byte with the ``FF FE`` UTF-16/32 BOM). ISO BMFF requires
+ two leading zero bytes, a big-endian box size of at least 8 and
+ ``ftyp`` (unparseable as XML in any encoding: ``ftyp`` read as UCS-4
+ is above U+10FFFF); EMF requires record type 1 (``01 00 00 00``) and
+ `` EMF`` at offset 40. As a second line, any other entry whose head
+ decodes to markup (``<`` after an optional BOM and whitespace, in
+ UTF-8/16/32 with or without a BOM) stays a parsed part whatever else
+ it matches. A
+ markup-looking name also always keeps an entry under the parsed-part
+ ceilings.
+- **pandoc** (``.odt``/``.epub``, see ``utilities/pandoc_conversion``)
+ has its own zip reader, which locates entries through the central
+ directory but takes each entry's method and compressed size from its
+ local header; step 2's header agreement makes it inflate the streams
+ verified here. Reference fan-out inside pandoc's readers is not
+ checked; the pandoc child is bounded by its own heap cap and timeout.
+
+Known gaps: pre-existing parser behaviour this guard does **not**
+bound. It bounds container and entry sizes, compression, the honesty
+of the declarations, and only the specific fan-outs listed above.
+
+- **.xlsx grid padding.** Memory follows the *cell references*, not the
+ XML size. pandas' openpyxl reader (``_OpenpyxlReader.get_sheet_data``,
+ which unstructured's ``partition_xlsx`` reaches through
+ ``pd.read_excel``) pads every row to the widest row
+ (``data_row + (max_width - len(data_row)) * empty_cell``), so a
+ few-KB sheet with cells ``XFD1`` and ``A300`` materialises
+ 300 x 16384 cells (about +121 MiB RSS measured), and ``XFD1`` with
+ ``A1048576`` would need hundreds of GiB. The per-part ceilings do
+ not limit this. Likewise, a shared string is stored once in the
+ package but referenced by index from any number of cells, and
+ unstructured renders each sheet with ``DataFrame.to_html``, which
+ writes the string out once per referencing cell, so a long shared
+ string referenced by many cells multiplies into the HTML.
+- **Repeated references inside pandoc's readers** (for example an EPUB
+ spine listing one chapter many times) are not counted; pandoc is
+ bounded only by its heap cap and timeout.
+- **.docx total parse time and memory.** The ceilings in step 5
+ bound the known fan-outs, not the document: python-docx's and
+ unstructured's cost stays linear in the element count and in the
+ text, with a large constant. A trivial paragraph costs about
+ 0.6-2 ms (5,000 one-letter paragraphs under python-docx's template
+ took 11 s); python-docx-built paragraphs of ordinary text 3-9 ms
+ (11,300 one-run paragraphs in one section took 31 s; 5,600
+ paragraphs of seven formatted runs beside 300 styles, 49 s); text
+ that triggers unstructured's per-element classification 35-65 ms
+ (a US city/state/ZIP regex backtracks for ~40 ms on text starting
+ with 80 or more letters without a space or comma, and langdetect
+ runs once per element at ~25 ms when the whole text is not one
+ language), so an accepted document of a few thousand such
+ paragraphs runs for minutes; and one 3 MB paragraph took 43 s and
+ ~300 MB. Nothing here bounds that; only a wall-clock and memory
+ limit on the in-process parse would.
+- **.docx length refusals.** The ceilings share one budget and price
+ each step at the slowest layout measured, so they also refuse long
+ ordinary documents that would partition in under a minute. Measured
+ on documents python-docx writes: a single section of more than
+ about 11,300 one-run paragraphs; a Word-like document (300 styles,
+ five sections, a table) of more than about 5,250-5,850 paragraphs of
+ 5-10 formatted runs; more than about 580 one-paragraph sections, or
+ 180 ten-paragraph ones (a mail merge to "individual documents").
+ Long theses and books can exceed these. Vertical merges are priced
+ the same way: one column merged down more than about 545 rows is
+ refused (300 such rows took 8 s to partition), as is every cell of
+ a 64-column table continuing down 27 rows (26 such rows took 22 s),
+ or down 26 with cell widths set.
+- **.pptx length refusals.** ``MAX_PPTX_PLACEHOLDER_WORK`` counts every
+ slide placeholder as inheriting its position and prices each read at
+ the slowest layout measured, so it also refuses long ordinary decks:
+ about 2,600 title-and-content slides under Office's default theme,
+ fewer under templates with more shapes per layout and master.
+- **Parse-tree memory of an accepted part.** The guard's own lxml
+ walks hold every open element with its attributes, and its parses of
+ the skeleton parts (``_skeleton_xml``) the whole tree, about 200
+ bytes per attribute, as the loaders' own parses of the same part do.
+ ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` bounds one start tag, not how many
+ such tags are open at once: a slide, header or footer of nested
+ elements each carrying close to that many attributes costs about
+ 14 MB per open level (eight levels, a 5.1 MB slide, held 118 MB in
+ the guard and 122 MB in python-pptx's load; a 128 MiB slide about
+ 3 GB). ``document.xml`` and relationships parts are not affected: an
+ element over ``MAX_DOCX_ELEMENT_ATTRIBUTES`` or
+ ``MAX_RELS_ELEMENT_ATTRIBUTES`` attributes is refused as it starts.
+- **In-process parsers have no timeout.** python-docx, python-pptx,
+ openpyxl, pandas and unstructured run inside the indexing worker with
+ no wall clock, so super-linear behaviour other than the fan-outs
+ listed above can pin a worker; only the soffice and pandoc
+ subprocesses carry timeouts.
+"""
+
+from __future__ import annotations
+
+import functools
+import hashlib
+import io
+import posixpath
+import re
+import struct
+import zipfile
+import zlib
+from typing import Any, Callable, NamedTuple, Optional, cast
+
+from loguru import logger
+
+#: Extensions whose loaders parse zip containers of XML parts.
+#: (.doc/.ppt arrive as legacy OLE binaries and are converted to
+#: containers by the loader, so the guard does not apply to their
+#: raw upload bytes.)
+ZIP_CONTAINER_EXTENSIONS = frozenset(
+ {".docx", ".xlsx", ".odt", ".pptx", ".epub"}
+)
+
+#: Per-entry uncompressed ceiling. A text-heavy 200-page .docx keeps
+#: its main XML part in single-digit MB; an XML part near this ceiling
+#: already costs the in-process parsers on the order of 1-2+ GB of
+#: memory (XML parse trees run ~10-20x the XML size), so larger parts
+#: are refused rather than risk an OOM of the worker. This ceiling does
+#: not bound what a loader builds from the tree (for example pandas'
+#: .xlsx grid padding; see "Known gaps" in the module docstring).
+MAX_ENTRY_BYTES = 128 * 1024 * 1024
+
+#: Total uncompressed ceiling across all *parsed* (non-media) entries.
+#: Parsers that walk every part (openpyxl across worksheets,
+#: python-pptx across slides) pay the parse-tree multiplier on the
+#: total, so the total is kept to a few entry ceilings.
+MAX_TOTAL_BYTES = 512 * 1024 * 1024
+
+#: Per-entry ceiling for binary media entries (see module docstring).
+#: The packages that read media load each part once at ~1x, so a
+#: single large video or high-resolution image in a deck stays
+#: accepted, while a media "bomb" is still bounded.
+MAX_MEDIA_ENTRY_BYTES = 512 * 1024 * 1024
+
+#: Ceiling across *all* entries, media included. python-docx and
+#: python-pptx hold every part's blob at once, so this bounds the
+#: resident media (at ~1x) plus the parsed parts' raw bytes; it admits
+#: a media-heavy deck of several hundred MB. It also bounds the
+#: guard's own verification work (every DEFLATE entry is inflated
+#: once; a STORED entry's size is fixed by its equality check).
+MAX_CONTAINER_BYTES = 1024 * 1024 * 1024
+
+#: Entry-count ceiling: bounds central-directory walks and per-part
+#: parser work; real containers carry dozens of parts.
+MAX_ENTRIES = 10_000
+
+
+#: Names that are parsed as markup whatever their leading bytes say.
+_MARKUP_SUFFIXES = (
+ ".xml",
+ ".rels",
+ ".xhtml",
+ ".html",
+ ".htm",
+ ".opf",
+ ".ncx",
+ ".svg",
+)
+
+#: Leading-byte signatures of binary media no document parser reads as
+#: markup (none of them starts with ``<``).
+_MEDIA_SIGNATURES = (
+ b"\x89PNG\r\n\x1a\n", # PNG
+ b"\xff\xd8\xff", # JPEG
+ b"GIF87a",
+ b"GIF89a",
+ b"II*\x00", # TIFF little-endian
+ b"MM\x00*", # TIFF big-endian
+ b"BM", # BMP
+ b"RIFF", # WAV / AVI / WebP
+ b"\xd7\xcd\xc6\x9a", # placeable WMF
+ b"\x1f\x8b\x08", # gzip (EMZ/WMZ)
+ b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", # OLE compound file
+ b"PK\x03\x04", # embedded package
+ b"%PDF-",
+ b"\x30\x26\xb2\x75\x8e\x66\xcf\x11", # ASF (WMV/WMA)
+ b"OggS",
+ b"fLaC",
+ b"ID3", # MP3
+ b"\x1a\x45\xdf\xa3", # Matroska / WebM
+ b"wOFF",
+ b"wOF2",
+ b"OTTO",
+ b"\x00\x01\x00\x00", # TrueType
+)
+
+
+class DecompressionBombError(ValueError):
+ """A zip-container document declares an unreasonable uncompressed size."""
+
+
+#: zipfile's local file header layout (``zipfile.structFileHeader``).
+_LOCAL_HEADER = struct.Struct("<4s2B4HL2L2H")
+_LOCAL_HEADER_MAGIC = b"PK\x03\x04"
+#: End-of-central-directory signature: the first bytes of an empty
+#: archive (which zipfile, and so the guard, accepts).
+_EMPTY_ARCHIVE_MAGIC = b"PK\x05\x06"
+#: A central-directory record is 46 fixed bytes plus its name and
+#: extra fields (both bounded by other checks once read); 1 KiB per
+#: allowed entry is a generous honest ceiling for the walk.
+_CENTRAL_DIR_BYTES_PER_ENTRY = 1024
+#: The function ``ZipFile._RealGetContents`` itself calls to pick the
+#: end records (``endrec = _EndRecData(fp)``), then walks
+#: ``endrec[_ECD_SIZE]`` bytes of central directory. Calling the
+#: running interpreter's own copy, rather than a re-implementation,
+#: is what makes the guard bound the very span zipfile then walks:
+#: the selection is subtle (the fixed 22-byte record at the end is
+#: taken before any backwards search, the ZIP64 record is followed
+#: through its locator's offset and may sit behind "extensible data",
+#: and that ZIP64 logic changed across 3.12 patch releases), and any
+#: divergence lets a writer show the guard one record and zipfile
+#: another. Private but present unchanged in name and return shape in
+#: every CPython the project supports (``requires-python`` < 3.15).
+_zipfile_end_record = zipfile._EndRecData # type: ignore[attr-defined]
+#: Index of the central-directory size in that record
+#: (``zipfile._ECD_SIZE``).
+_ECD_SIZE = 5
+
+#: General-purpose flag bits the local/central agreement check reads.
+_FLAG_DEFLATE_LEVEL_BITS = 0x0006 # compression-level hint, ignored
+_FLAG_DATA_DESCRIPTOR = 0x0008
+_FLAG_UTF8 = 0x0800
+#: Data-descriptor signature (optional before the descriptor fields).
+_DATA_DESCRIPTOR_MAGIC = b"PK\x07\x08"
+#: A 32-bit size of this value defers to the ZIP64 extra field.
+_ZIP64_LIMIT = 0xFFFFFFFF
+
+#: The only compression methods accepted: those the bounded inflation
+#: below can verify (zlib takes an output limit per step). zipfile
+#: decompresses BZIP2/LZMA/ZSTD chunks with no output limit at all, so
+#: a tiny entry of those methods can materialize gigabytes in any
+#: reader, this guard included. Office/ODF/EPUB writers only emit
+#: STORED and DEFLATE.
+_ALLOWED_METHODS = frozenset({zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED})
+
+
+def _max_compress_size(file_size: int) -> int:
+ """Largest compressed size accepted for a DEFLATE entry.
+
+ Incompressible data costs ~5 bytes per 64 KiB stored block plus
+ framing. A full read copies an entry's whole compressed range into
+ memory, so that range must not exceed the declared size by more
+ than this slack.
+ """
+ return file_size + (file_size >> 10) + 1024
+
+
+#: Inflation step sizes for the verification pass (memory stays at a
+#: few MiB whatever the entry size).
+_INFLATE_INPUT_CHUNK = 64 * 1024
+_INFLATE_OUTPUT_CHUNK = 1024 * 1024
+
+
+def _local_entry_range(
+ content: memoryview, info: zipfile.ZipInfo
+) -> tuple[int, int]:
+ """Byte range of *info*'s compressed data, after requiring the
+ entry's local header to agree with its central-directory record.
+
+ zipfile reads an entry through the central directory (offset,
+ method, sizes) and only takes the name/extra lengths from the
+ local header, but pandoc's zip reader takes the method and
+ compressed size from the *local* header. An entry whose two
+ headers disagree would therefore be verified here as one stream
+ and inflated by pandoc as another — for instance a small honest
+ central record over a local header declaring a much larger
+ stream. So the method, the general-purpose flags (bits 1-2, the
+ DEFLATE level hint, excepted), the CRC, both sizes and the name
+ must agree. With a data descriptor (flag bit 3), the local CRC and
+ sizes may each be zero (the usual streaming form) or the central
+ value, and the descriptor that follows the data must repeat the
+ central CRC and sizes exactly; the local data range is then the
+ central one by construction.
+ """
+ start = info.header_offset
+ header = bytes(content[start : start + _LOCAL_HEADER.size])
+ if len(header) != _LOCAL_HEADER.size:
+ raise zipfile.BadZipFile("truncated local header")
+ (
+ magic,
+ _version,
+ _os,
+ flags,
+ method,
+ _time,
+ _date,
+ crc,
+ compress_size,
+ file_size,
+ name_len,
+ extra_len,
+ ) = _LOCAL_HEADER.unpack(header)
+ if magic != _LOCAL_HEADER_MAGIC:
+ raise zipfile.BadZipFile("bad local header magic")
+ name_start = start + _LOCAL_HEADER.size
+ name = bytes(content[name_start : name_start + name_len])
+ extra = bytes(
+ content[name_start + name_len : name_start + name_len + extra_len]
+ )
+ if len(name) != name_len or len(extra) != extra_len:
+ raise zipfile.BadZipFile("truncated local header")
+
+ zip64 = _ZIP64_LIMIT in (compress_size, file_size)
+ if zip64:
+ compress_size, file_size = _local_zip64_sizes(extra)
+
+ if method != info.compress_type:
+ raise DecompressionBombError(
+ "zip entry's local header disagrees with the central directory"
+ )
+ if (flags ^ info.flag_bits) & ~_FLAG_DEFLATE_LEVEL_BITS:
+ raise DecompressionBombError(
+ "zip entry's local header disagrees with the central directory"
+ )
+ encoding = "utf-8" if flags & _FLAG_UTF8 else "cp437"
+ if name != info.orig_filename.encode(encoding):
+ raise DecompressionBombError(
+ "zip entry's local header disagrees with the central directory"
+ )
+ declared = (crc, compress_size, file_size)
+ central = (info.CRC, info.compress_size, info.file_size)
+ if flags & _FLAG_DATA_DESCRIPTOR:
+ agrees = all(
+ local in (0, value) for local, value in zip(declared, central)
+ )
+ else:
+ agrees = declared == central
+ if not agrees:
+ raise DecompressionBombError(
+ "zip entry's local header disagrees with the central directory"
+ )
+
+ data_start = name_start + name_len + extra_len
+ data_end = data_start + info.compress_size
+ if data_end > len(content):
+ raise zipfile.BadZipFile("entry data runs past the archive")
+ if flags & _FLAG_DATA_DESCRIPTOR:
+ _check_data_descriptor(content, data_end, info, zip64=zip64)
+ return data_start, data_end
+
+
+def _local_zip64_sizes(extra: bytes) -> tuple[int, int]:
+ """(compressed, uncompressed) sizes from a local ZIP64 extra field.
+
+ A local header that sets either 32-bit size to 0xFFFFFFFF must
+ carry both 64-bit sizes (uncompressed first) in its ZIP64 field.
+ """
+ pos = 0
+ while pos + 4 <= len(extra):
+ tag, size = struct.unpack_from("<2H", extra, pos)
+ body = extra[pos + 4 : pos + 4 + size]
+ if tag == 0x0001:
+ if len(body) < 16:
+ break
+ file_size, compress_size = struct.unpack_from("<2Q", body)
+ return compress_size, file_size
+ pos += 4 + size
+ raise zipfile.BadZipFile("local header lacks its ZIP64 sizes")
+
+
+def _check_data_descriptor(
+ content: memoryview, offset: int, info: zipfile.ZipInfo, *, zip64: bool
+) -> None:
+ """Require the data descriptor at *offset* to repeat the central
+ CRC and sizes (signature optional; 8-byte sizes after a ZIP64
+ local header, 4-byte otherwise)."""
+ size_format = "<L2Q" if zip64 else "<3L"
+ record = struct.Struct(size_format)
+ tail = bytes(content[offset : offset + 4 + record.size])
+ candidates = [tail[: record.size]]
+ if tail[:4] == _DATA_DESCRIPTOR_MAGIC:
+ candidates.append(tail[4:])
+ expected = (info.CRC, info.compress_size, info.file_size)
+ if not any(
+ len(fields) == record.size and record.unpack(fields) == expected
+ for fields in candidates
+ ):
+ raise DecompressionBombError(
+ "zip entry's data descriptor disagrees with the central directory"
+ )
+
+
+def _inflate_head(content: memoryview, info: zipfile.ZipInfo) -> bytes:
+ """Verify *info*'s data is exactly what it declares, and return its
+ first 64 bytes.
+
+ CPython's zipfile truncates an entry to its declared size only
+ *after* inflating each read chunk, and a full ``read()`` inflates
+ the entry's whole compressed range in one step, so a DEFLATE entry
+ that declares 100 bytes can still materialize gigabytes inside a
+ parser. Inflating here in bounded steps, and refusing any entry
+ whose real output exceeds its declaration, is what makes the
+ declared sizes an actual bound on parser reads.
+
+ The stream must also *end* exactly where it is declared to: the
+ inflater has to reach the end of the DEFLATE stream at the last
+ byte of the compressed range (no truncation, no trailing bytes),
+ having produced exactly the declared size with the declared CRC.
+ A reader that does not stop at the central directory's compressed
+ size (pandoc's, which follows the local header) would otherwise
+ keep inflating past the range this check saw.
+ """
+ data_start, data_end = _local_entry_range(content, info)
+ if info.compress_type == zipfile.ZIP_STORED:
+ crc = 0
+ for pos in range(data_start, data_end, _INFLATE_OUTPUT_CHUNK):
+ crc = zlib.crc32(
+ content[pos : min(pos + _INFLATE_OUTPUT_CHUNK, data_end)], crc
+ )
+ if crc != info.CRC:
+ raise DecompressionBombError("zip entry fails its CRC check")
+ return bytes(content[data_start : min(data_end, data_start + 64)])
+
+ if data_start == data_end and info.file_size == 0 and info.CRC == 0:
+ return b"" # an empty DEFLATE entry some writers emit bare
+
+ inflater = zlib.decompressobj(-zlib.MAX_WBITS)
+ produced = 0
+ crc = 0
+ head = b""
+ pos = data_start
+ pending = b""
+ while not inflater.eof:
+ if not pending and pos < data_end:
+ pending = bytes(
+ content[pos : min(pos + _INFLATE_INPUT_CHUNK, data_end)]
+ )
+ pos += len(pending)
+ # Once the range is consumed, ``pending`` is b"" and this drains
+ # output zlib still holds: a step that hit its output cap can
+ # consume the last input byte before emitting all its output
+ # (and before reaching the end of the stream).
+ out = inflater.decompress(pending, _INFLATE_OUTPUT_CHUNK)
+ pending = inflater.unconsumed_tail
+ if not out and not pending and pos >= data_end and not inflater.eof:
+ break # range consumed and drained before the stream ended
+ produced += len(out)
+ if produced > info.file_size:
+ raise DecompressionBombError(
+ "zip entry inflates past its declared size"
+ )
+ crc = zlib.crc32(out, crc)
+ if len(head) < 64:
+ head += out[: 64 - len(head)]
+ if not inflater.eof:
+ raise DecompressionBombError("zip entry's DEFLATE stream is truncated")
+ if pending or inflater.unused_data or pos != data_end:
+ raise DecompressionBombError(
+ "zip entry's DEFLATE stream ends before its compressed range"
+ )
+ if produced != info.file_size:
+ raise DecompressionBombError(
+ "zip entry inflates to less than its declared size"
+ )
+ if crc != info.CRC:
+ raise DecompressionBombError("zip entry fails its CRC check")
+ return head
+
+
+#: Containers whose entries may earn the media ceiling. Their parsers
+#: (python-docx/-pptx over lxml, openpyxl over lxml/expat) never parse
+#: a signature-headed media part as XML. EPUB/ODT go to pandoc, whose
+#: readers may still parse such an entry (an EPUB chapter is read by
+#: its manifest media type, not its bytes), so every EPUB/ODT entry
+#: stays under the parsed-part ceilings.
+MEDIA_CEILING_EXTENSIONS = frozenset({".docx", ".pptx", ".xlsx"})
+
+
+def _is_canonical_member_name(name: str) -> bool:
+ """True for a plain relative member name.
+
+ Refuses empty, ``.`` and ``..`` segments (so ``//``, ``/./``, a
+ leading ``/`` and traversal) and backslashes. Such names make
+ distinct members that readers normalise onto one path — openpyxl's
+ ``get_rels_path`` collapses ``a//b.xml`` and ``a/b.xml`` onto one
+ ``_rels`` part, for instance — and no Office/ODF/EPUB writer emits
+ them. A single trailing ``/`` (a directory entry) is allowed. NUL
+ never reaches here: zipfile truncates names at NUL when it reads
+ the central directory, and names that then collide are refused by
+ the duplicate-name check.
+ """
+ if not name or "\\" in name:
+ return False
+ body = name[:-1] if name.endswith("/") else name
+ return all(segment not in ("", ".", "..") for segment in body.split("/"))
+
+
+def _is_media_head(info: zipfile.ZipInfo, head: bytes) -> bool:
+ """True when *info* is binary media by content (see module docstring)."""
+ if info.is_dir():
+ return False
+ if info.filename.lower().endswith(_MARKUP_SUFFIXES):
+ return False
+ # ISO BMFF (MP4 / MOV / M4A / HEIC): a big-endian box size of at
+ # least 8 (so the head starts with two zero bytes) then "ftyp".
+ # Checked before the markup sniff: such a head cannot parse as XML
+ # in any encoding ("ftyp" read as UCS-4 is above U+10FFFF, and two
+ # leading zero bytes are a NUL in UTF-16), while a real MP4 whose
+ # ftyp box is 60 bytes long starts 00 00 00 3C, which the UTF-32BE
+ # decode below would otherwise read as "<".
+ if (
+ head[:2] == b"\x00\x00"
+ and head[4:8] == b"ftyp"
+ and int.from_bytes(head[:4], "big") >= 8
+ ):
+ return True
+ if _looks_like_markup(head):
+ return False
+ if head.startswith(_MEDIA_SIGNATURES):
+ return True
+ # EMF: EMR_HEADER record type 1 with the " EMF" signature at 40.
+ return head[:4] == b"\x01\x00\x00\x00" and head[40:44] == b" EMF"
+
+
+#: Encodings an XML parser can auto-detect a document start in.
+_MARKUP_ENCODINGS = (
+ "utf-8",
+ "utf-16-le",
+ "utf-16-be",
+ "utf-32-le",
+ "utf-32-be",
+)
+
+
+def _looks_like_markup(head: bytes) -> bool:
+ """True when *head* could begin an XML document.
+
+ Conservative: a match only ever keeps an entry under the parsed-part
+ ceilings. Undecodable bytes become U+FFFD, never ``<``.
+ """
+ for encoding in _MARKUP_ENCODINGS:
+ text = head.decode(encoding, errors="replace")
+ if text.lstrip("\ufeff \t\r\n").startswith("<"):
+ return True
+ return False
+
+
+#: unstructured's ``_ZipFileDetector`` rules, in its order: the first
+#: member-name pattern any member matches (``re.match``) names the
+#: package type; with no match it reads a root ``mimetype`` member as
+#: the type.
+_SNIFFED_ZIP_TYPES = (
+ (".docx", re.compile(r"word/document.*\.xml$")),
+ (".xlsx", re.compile(r"xl/workbook.*\.xml$")),
+ (".pptx", re.compile(r"ppt/presentation.*\.xml$")),
+)
+
+#: The member pandas' ``inspect_excel_format`` needs (names lowercased)
+#: to read a workbook with openpyxl rather than another engine.
+_PANDAS_XLSX_MEMBER = "xl/workbook.xml"
+
+#: The root ``mimetype`` member of an ODF or EPUB package, and the media
+#: type it must name for each extension when present.
+_MIMETYPE_MEMBER = "mimetype"
+_PACKAGE_MIMETYPES = {
+ ".odt": "application/vnd.oasis.opendocument.text",
+ ".epub": "application/epub+zip",
+}
+
+#: Longest ``mimetype`` member read (the media types above are at most
+#: 39 bytes).
+_MAX_MIMETYPE_MEMBER_BYTES = 256
+
+
+def _check_package_type(archive: zipfile.ZipFile, ext: str) -> None:
+ """Refuse a package whose member layout makes a content sniffer pick
+ a different parser than its extension does.
+
+ langchain's Word and PowerPoint loaders call unstructured's
+ ``detect_filetype`` (whenever python-magic imports) and route a file
+ it calls DOC or PPT to ``partition_doc``/``partition_ppt``, which run
+ soffice with no timeout and partition its output without this
+ guard. For a zip the detector returns DOCX, XLSX or PPTX from the
+ first of its member-name patterns that matches
+ (``_SNIFFED_ZIP_TYPES``), and otherwise trusts a root ``mimetype``
+ member's content: a ``.docx`` with no ``word/document*.xml`` and a
+ ``mimetype`` of ``application/msword`` went to soffice. An OOXML
+ package (``.docx``/``.xlsx``/``.pptx``) is therefore refused when it
+ has a ``mimetype`` member (OPC packages have none) or when the
+ detector's patterns would not name its own extension, and an
+ ``.xlsx`` also when pandas would not pick openpyxl for it (no
+ ``xl/workbook.xml``; pandas would pick pyxlsb or odfpy instead). An
+ ``.odt`` or ``.epub`` (converted by pandoc with an explicit input
+ format, never sniffed on the upload path) is refused when its
+ ``mimetype`` member, if present, names another type. Called after
+ the entries are verified, so the ``mimetype`` read is bounded."""
+ names = archive.namelist()
+ if ext in _PACKAGE_MIMETYPES:
+ if _MIMETYPE_MEMBER not in names:
+ return
+ info = archive.getinfo(_MIMETYPE_MEMBER)
+ if info.file_size > _MAX_MIMETYPE_MEMBER_BYTES:
+ raise DecompressionBombError("package mimetype member is too long")
+ try:
+ declared: Optional[str] = archive.read(info).decode("utf-8").strip()
+ except UnicodeDecodeError:
+ declared = None
+ if declared != _PACKAGE_MIMETYPES[ext]:
+ raise DecompressionBombError(
+ "package mimetype does not match its extension"
+ )
+ return
+ if _MIMETYPE_MEMBER in names:
+ raise DecompressionBombError(
+ "office package has a mimetype member, which a content sniffer "
+ "reads as its type"
+ )
+ sniffed = next(
+ (
+ kind
+ for kind, pattern in _SNIFFED_ZIP_TYPES
+ if any(pattern.match(name) for name in names)
+ ),
+ None,
+ )
+ if sniffed != ext:
+ raise DecompressionBombError(
+ "office package's part names do not match its extension"
+ )
+ if ext == ".xlsx" and _PANDAS_XLSX_MEMBER not in {
+ name.lower() for name in names
+ }:
+ raise DecompressionBombError(
+ "spreadsheet package has no xl/workbook.xml part"
+ )
+
+
+def _declared_central_directory_size(content: bytes) -> int:
+ """Read the central-directory size zipfile will walk, before
+ ``zipfile`` is asked to walk the records.
+
+ The end records are selected by zipfile's own ``_EndRecData`` — the
+ same call ``ZipFile`` makes — so the size returned is exactly the
+ one zipfile then reads (``endrec[_ECD_SIZE]``, which the ZIP64
+ record overrides whenever zipfile accepts one). It reads only the
+ end records and walks none. Fails closed: when zipfile would find
+ no usable end record, or rejects the one it finds, the container
+ is refused here rather than the bound standing aside.
+ """
+ try:
+ endrec = _zipfile_end_record(io.BytesIO(content))
+ except (zipfile.BadZipFile, OSError, struct.error) as exc:
+ raise DecompressionBombError("malformed zip container") from exc
+ if not endrec:
+ raise DecompressionBombError("malformed zip container")
+ return int(endrec[_ECD_SIZE])
+
+
+def _check_central_directory_span(content: bytes, *, max_entries: int) -> None:
+ """Refuse a central directory whose declared byte span alone
+ exceeds the entry-count-scaled bound.
+
+ ``zipfile`` materialises every central-directory record before the
+ entry-count ceiling can count them (a hand-packed record flood a
+ fraction of the upload cap in size buys hundreds of MiB of RSS),
+ and the EOCD's record count wraps at 65,535 — zipfile ignores it —
+ so only the declared byte span bounds that walk up front. A
+ container whose end records zipfile cannot read is refused too.
+ """
+ cd_size = _declared_central_directory_size(content)
+ limit = max_entries * _CENTRAL_DIR_BYTES_PER_ENTRY
+ if cd_size > limit:
+ raise DecompressionBombError(
+ f"zip container's central directory spans {cd_size} bytes, "
+ f"exceeding the {limit}-byte guard limit"
+ )
+
+
+def validate_zip_container(
+ content: bytes,
+ extension: str,
+ *,
+ max_entry_bytes: int = MAX_ENTRY_BYTES,
+ max_total_bytes: int = MAX_TOTAL_BYTES,
+ max_media_entry_bytes: int = MAX_MEDIA_ENTRY_BYTES,
+ max_container_bytes: int = MAX_CONTAINER_BYTES,
+ max_entries: int = MAX_ENTRIES,
+ zip_extensions: frozenset[str] = ZIP_CONTAINER_EXTENSIONS,
+) -> None:
+ """Refuse zip-container documents whose declared expansion is hostile.
+
+ Raises ``DecompressionBombError`` (a ``ValueError``) when the
+ container declares a central-directory byte span over
+ ``max_entries`` kibibytes (checked before ``zipfile`` materialises
+ the records); declares more entries than ``max_entries``; a parsed
+ part over ``max_entry_bytes`` or parsed parts over
+ ``max_total_bytes`` in total; a binary media entry over
+ ``max_media_entry_bytes``; more than ``max_container_bytes``
+ across all entries; or when it is not a readable zip at all; or
+ when its layout lets a content sniffer pick another parser than
+ the extension does (``_check_package_type``). Non-container
+ extensions are returned untouched, and rejection happens before
+ any parser sees the bytes.
+ """
+ ext = (
+ extension.lower()
+ if extension.startswith(".")
+ else f".{extension.lower()}"
+ )
+ if ext not in zip_extensions:
+ return
+
+ # zipfile finds the archive from the end of the file, so anything
+ # may precede it; content sniffers (unstructured) read the start.
+ if not content.startswith((_LOCAL_HEADER_MAGIC, _EMPTY_ARCHIVE_MAGIC)):
+ raise DecompressionBombError(
+ "zip container does not start with a zip signature"
+ )
+
+ # zipfile materialises every central-directory record before the
+ # entry-count ceiling can refuse them, so the span the end records
+ # declare is bounded first — whatever their (wrapped, ignored)
+ # record counts claim.
+ _check_central_directory_span(content, max_entries=max_entries)
+
+ try:
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
+ parsed_total, container_total, entries = _check_entries(
+ archive,
+ memoryview(content),
+ max_entry_bytes=max_entry_bytes,
+ max_total_bytes=max_total_bytes,
+ max_media_entry_bytes=max_media_entry_bytes,
+ max_container_bytes=max_container_bytes,
+ max_entries=max_entries,
+ media_allowed=ext in MEDIA_CEILING_EXTENSIONS,
+ )
+ _check_package_type(archive, ext)
+ if ext == ".xlsx":
+ _check_xlsx_sheet_fan_out(content)
+ elif ext == ".pptx":
+ _check_pptx_slide_fan_out(content)
+ elif ext == ".docx":
+ _check_docx_section_fan_out(content)
+ except DecompressionBombError:
+ raise
+ except (
+ zipfile.BadZipFile,
+ # A container the stdlib cannot even list or open (undecodable
+ # UTF-8-flagged names, unsupported versions or compression,
+ # encrypted entries, truncated records, corrupt deflate data)
+ # is refused too: fail closed, never pass it on.
+ ValueError,
+ NotImplementedError,
+ RuntimeError,
+ EOFError,
+ OSError,
+ struct.error,
+ zlib.error,
+ ) as exc:
+ raise DecompressionBombError("malformed zip container") from exc
+
+ # Deliberately logs no user-controlled content: entry count and
+ # declared sizes only.
+ logger.debug(
+ "zip container accepted: {} entries, {} parsed / {} total "
+ "declared bytes",
+ entries,
+ parsed_total,
+ container_total,
+ )
+
+
+def _check_entries(
+ archive: zipfile.ZipFile,
+ content: memoryview,
+ *,
+ max_entry_bytes: int,
+ max_total_bytes: int,
+ max_media_entry_bytes: int,
+ max_container_bytes: int,
+ max_entries: int,
+ media_allowed: bool,
+) -> tuple[int, int, int]:
+ infos = archive.infolist()
+ if len(infos) > max_entries:
+ raise DecompressionBombError(
+ f"zip container declares {len(infos)} entries "
+ f"(ceiling {max_entries})"
+ )
+
+ # Data in front of the archive shifts every header offset (zipfile
+ # compensates); a genuine container's first entry starts at 0.
+ if infos and min(info.header_offset for info in infos) != 0:
+ raise DecompressionBombError(
+ "zip container has data before its first entry"
+ )
+
+ # Pass 1: declaration-only checks, before any entry data is touched.
+ largest_entry_ceiling = max(max_entry_bytes, max_media_entry_bytes)
+ header_offsets: set[int] = set()
+ names: set[str] = set()
+ container_total = 0
+ for info in infos:
+ if not _is_canonical_member_name(info.filename):
+ raise DecompressionBombError(
+ "zip container has a non-canonical member name"
+ )
+ if info.filename in names:
+ raise DecompressionBombError(
+ "zip container has two members with the same name"
+ )
+ names.add(info.filename)
+ if info.header_offset in header_offsets:
+ raise DecompressionBombError(
+ "zip container has entries sharing one local header"
+ )
+ header_offsets.add(info.header_offset)
+ if info.file_size > largest_entry_ceiling:
+ raise DecompressionBombError(
+ f"zip entry declares {info.file_size} bytes "
+ f"(ceiling {largest_entry_ceiling})"
+ )
+ if info.compress_type not in _ALLOWED_METHODS:
+ raise DecompressionBombError(
+ "zip container uses an unsupported compression method"
+ )
+ if info.flag_bits & 0x1:
+ raise DecompressionBombError("zip container has encrypted entries")
+ if info.compress_size > _max_compress_size(info.file_size) or (
+ info.compress_type == zipfile.ZIP_STORED
+ and info.compress_size != info.file_size
+ ):
+ raise DecompressionBombError(
+ "zip entry's compressed size does not match its declared size"
+ )
+ container_total += info.file_size
+ if container_total > max_container_bytes:
+ raise DecompressionBombError(
+ f"zip container declares over {max_container_bytes} bytes "
+ "total uncompressed"
+ )
+
+ # Pass 2: verify each declaration by bounded inflation (total work
+ # bounded by pass 1's container total), then classify and apply the
+ # per-kind ceilings.
+ parsed_total = 0
+ for info in infos:
+ head = _inflate_head(content, info)
+ if media_allowed and _is_media_head(info, head):
+ # Binary media is held to its own per-entry ceiling and
+ # counts only toward the whole-container total.
+ if info.file_size > max_media_entry_bytes:
+ raise DecompressionBombError(
+ f"zip media entry {info.filename!r} declares "
+ f"{info.file_size} bytes "
+ f"(ceiling {max_media_entry_bytes})"
+ )
+ continue
+ if info.file_size > max_entry_bytes:
+ raise DecompressionBombError(
+ f"zip entry {info.filename!r} declares "
+ f"{info.file_size} bytes (ceiling {max_entry_bytes})"
+ )
+ parsed_total += info.file_size
+ if parsed_total > max_total_bytes:
+ raise DecompressionBombError(
+ f"zip container declares over {max_total_bytes} bytes "
+ "of parsed parts uncompressed"
+ )
+ return parsed_total, container_total, len(infos)
+
+
+#: The parser families openpyxl's read path (and msoffcrypto, which
+#: unstructured runs first) parses ``.xlsx`` parts with: lxml
+#: (``openpyxl.xml.functions.fromstring``) for the package skeleton, the
+#: styles, the document properties, chartsheets and every relationships
+#: part, and expat (``xml.etree``/defusedxml ``iterparse``) for
+#: worksheets and shared strings; msoffcrypto reads
+#: ``[Content_Types].xml`` with minidom, expat too.
+_LXML = "lxml"
+_EXPAT = "expat"
+
+
+class _XlsxScanTarget:
+ """What one parser of ``_scan_xlsx_part`` reports to: an lxml parser
+ target, or the handlers of an expat parser (``expat_start``), whose
+ element and attribute names pyexpat interns in *interned*, so they
+ are counted from there, after each chunk. It refuses a namespace URI
+ over ``MAX_XLSX_NAMESPACE_URI_CHARS`` characters, a DTD, nesting
+ deeper than ``MAX_XLSX_XML_DEPTH`` and more than
+ ``MAX_XLSX_PART_NAMES`` distinct names, and builds nothing."""
+
+ def __init__(self, interned: Optional[dict] = None):
+ self.depth = 0
+ self.names: set[str] = set()
+ self.interned = interned
+
+ def start_ns(self, prefix: Optional[str], uri: Optional[str]) -> None:
+ if uri is not None and len(uri) > MAX_XLSX_NAMESPACE_URI_CHARS:
+ raise DecompressionBombError(
+ "spreadsheet part declares a namespace URI of more "
+ f"than {MAX_XLSX_NAMESPACE_URI_CHARS} characters"
+ )
+ self.names.add(f"xmlns:{prefix or ''}")
+ self._count_names()
+
+ def doctype(self, *_declaration) -> None:
+ raise DecompressionBombError("document package part declares a DTD")
+
+ def start(self, tag: str, attributes: dict) -> None:
+ self.names.add(tag)
+ if attributes:
+ self.names.update(attributes)
+ self._count_names()
+ self.expat_start(tag, attributes)
+
+ def expat_start(self, _tag: str, _attributes) -> None:
+ self.depth += 1
+ if self.depth > MAX_XLSX_XML_DEPTH:
+ raise DecompressionBombError(
+ "spreadsheet part nests elements more than "
+ f"{MAX_XLSX_XML_DEPTH} deep"
+ )
+
+ def _count_names(self) -> None:
+ interned = len(self.interned) if self.interned is not None else 0
+ if len(self.names) + interned > MAX_XLSX_PART_NAMES:
+ raise DecompressionBombError(
+ "spreadsheet part uses more than "
+ f"{MAX_XLSX_PART_NAMES} distinct names"
+ )
+
+ def end(self, _tag) -> None:
+ self.depth -= 1
+
+ def close(self) -> None:
+ return None
+
+
+def _check_xlsx_namespaces(
+ archive: zipfile.ZipFile,
+ parts: dict[str, frozenset[str]],
+ scanned: set[tuple[str, str]],
+) -> None:
+ """Stream each of *parts* (member name -> parser families) once,
+ with the parsers of the families the loaders parse it with, before
+ any of them parses it (pairs in *scanned* are skipped and new ones
+ added). A missing member is skipped: openpyxl skips it too or fails
+ to load.
+
+ Refused, in every member scanned: an encoding other than UTF-8
+ (``_require_utf8_xml``), a start tag that may carry more than
+ ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` attributes (``_XmlTagSigns``) and a
+ DTD (``_XmlProlog``; see ``_refuse_dtd``: it could spell a
+ declaration through an entity), all checked before either parser
+ sees the bytes (``_CountedXmlStream``; the lxml push parser buffered
+ a whole internal subset before its doctype callback ran); then, as
+ ``_XlsxScanTarget`` receives them, a namespace URI over
+ ``MAX_XLSX_NAMESPACE_URI_CHARS`` characters (lxml and expat copy it
+ into the name of every element under it), a DTD again (a second
+ line), nesting deeper than ``MAX_XLSX_XML_DEPTH`` and more than
+ ``MAX_XLSX_PART_NAMES`` distinct names: both parsers keep state for
+ every open element (expat about 145 bytes) and every distinct name
+ for the whole parse, and neither, as the scan drives it, sets a
+ limit. No tree is built. An lxml member is fed to an lxml parser
+ with the options of openpyxl's parser and is refused when that
+ parse fails: openpyxl's load of a part libxml2 rejects fails too,
+ and its parse from a bytes buffer decodes UTF-32 with a byte-order
+ mark, which this push parser rejects at the first byte (the
+ encoding check before it refuses it first). An expat member is fed to an expat parser
+ with namespace processing, as ``xml.etree`` creates it, until its
+ first syntax error, where the loader's parse ends too. Python runs
+ once per chunk, per declaration and per element start and end."""
+ for name, families in parts.items():
+ todo = frozenset(f for f in families if (name, f) not in scanned)
+ if not todo:
+ continue
+ scanned.update((name, family) for family in todo)
+ try:
+ info = archive.getinfo(name)
+ except KeyError:
+ continue
+ _scan_xlsx_part(archive, info, todo)
+
+
+def _scan_xlsx_part(
+ archive: zipfile.ZipFile, info: zipfile.ZipInfo, families: frozenset[str]
+) -> None:
+ """Scan one member for ``_check_xlsx_namespaces``."""
+ from lxml import etree
+
+ # nosemgrep: python.lang.security.use-defused-xml.use-defused-xml, reason: bounded OOXML scan refuses DTD and entity declarations
+ from xml.parsers import expat
+
+ # Each live parser: (feed, finish, the errors that end its parse,
+ # whether such an error refuses the member).
+ live: list[
+ tuple[
+ Callable[..., Any],
+ Callable[..., Any],
+ tuple[type[Exception], ...],
+ bool,
+ ]
+ ] = []
+ if _LXML in families:
+ # openpyxl's parser: XMLParser(resolve_entities=False), whose
+ # other options (no network, no huge tree) are lxml's defaults.
+ lxml_parser = etree.XMLParser(
+ target=_XlsxScanTarget(), resolve_entities=False, no_network=True
+ )
+ live.append(
+ (lxml_parser.feed, lxml_parser.close, (etree.XMLSyntaxError,), True)
+ )
+ if _EXPAT in families:
+ # The separator xml.etree uses; any turns namespace processing
+ # on, which decides what expat rejects (an unbound prefix).
+ # pyexpat interns every element and attribute name it passes
+ # the handlers in this dict (as expat keeps its own entry for
+ # each), so its size is the distinct names read so far.
+ interned: dict = {}
+ expat_parser = expat.ParserCreate(
+ namespace_separator="}", intern=interned
+ )
+ expat_target = _XlsxScanTarget(interned)
+ expat_parser.StartNamespaceDeclHandler = expat_target.start_ns
+ expat_parser.StartDoctypeDeclHandler = expat_target.doctype
+ expat_parser.ordered_attributes = True # a list costs less
+ expat_parser.StartElementHandler = expat_target.expat_start
+ expat_parser.EndElementHandler = expat_target.end
+
+ # pyexpat reports an encoding it cannot decode as a LookupError
+ # or ValueError, where xml.etree's parse fails too.
+ def expat_feed(chunk: bytes, final: bool = False) -> None:
+ try:
+ expat_parser.Parse(chunk, final)
+ finally:
+ # At most one chunk's names past the ceiling.
+ expat_target._count_names()
+
+ live.append(
+ (
+ expat_feed,
+ functools.partial(expat_feed, b"", True),
+ (expat.ExpatError, LookupError, ValueError),
+ False,
+ )
+ )
+ with archive.open(info) as member:
+ stream = _CountedXmlStream(member)
+ while live and (chunk := stream.read(_XML_SCAN_CHUNK)):
+ for parser in list(live):
+ feed, _finish, errors, refuse = parser
+ if not _xlsx_scan_step(
+ functools.partial(feed, chunk), errors, refuse
+ ):
+ live.remove(parser)
+ for _feed, finish, errors, refuse in live:
+ _xlsx_scan_step(finish, errors, refuse)
+
+
+def _xlsx_scan_step(step, errors: tuple, refuse: bool) -> bool:
+ """Run ``step()`` for ``_scan_xlsx_part``; False when it raises one
+ of *errors*, where that parser's parse of the member ends, or a
+ refusal when *refuse* is set. A refusal (a ``ValueError`` too)
+ propagates."""
+ try:
+ step()
+ except DecompressionBombError:
+ raise
+ except errors as exc:
+ if refuse:
+ raise DecompressionBombError(
+ "malformed spreadsheet package: a part openpyxl parses "
+ "with lxml is not XML lxml reads"
+ ) from exc
+ return False
+ return True
+
+
+#: Chunk size of the namespace scan and of ``_CountedXmlStream``; at
+#: most ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` bytes (see ``_XmlTagSigns``).
+_XML_SCAN_CHUNK = 64 * 1024
+
+#: Ceiling on the element nesting depth of a scanned ``.xlsx`` part.
+#: expat, which openpyxl streams worksheets and shared strings with
+#: (and msoffcrypto's minidom ``[Content_Types].xml``), keeps about 145
+#: bytes per open element and sets no limit, so 128 MiB of ``<a>``, a
+#: 130 KB file, would hold about 6 GB in expat alone (and
+#: xml.etree builds a tree element per level); libxml2's push parser
+#: driving a target, as the scan drives it, keeps about 36 bytes per
+#: level and sets no limit either. libxml2 building a tree, as
+#: openpyxl's parse of the other parts does, refuses more than 256
+#: levels; this is the same ceiling. Office writers nest worksheet
+#: elements about ten deep.
+MAX_XLSX_XML_DEPTH = 256
+
+#: Ceiling on the distinct names (element names, attribute names and
+#: declared namespace prefixes, an element or attribute name counted
+#: with its namespace URI) in a scanned ``.xlsx`` part. expat keeps an
+#: entry for every distinct element and attribute name and every
+#: prefix for the whole parse (about 140 bytes per element name), as
+#: libxml2 keeps its name dictionary, so 1,000,000 distinct element
+#: names, 8.9 MB of a worksheet, held about 140 MB in the scan (a
+#: 128 MiB part about 2 GB). SpreadsheetML, its extensions and the
+#: package parts define a few hundred names.
+MAX_XLSX_PART_NAMES = 10_000
+
+#: Ceiling on the ``=`` characters between two ``<`` in an XML part
+#: the guard streams or counts (every ``.xlsx`` part the namespace scan
+#: covers, and each ``.docx``/``.pptx`` part and relationships part the
+#: guard parses): an upper bound on the attributes of a start tag,
+#: since an attribute value cannot hold a ``<``. It is counted in the
+#: part's bytes, which ``_require_utf8_xml`` holds to UTF-8 (no
+#: multi-byte UTF-8 sequence holds either byte), before any parser
+#: receives them. An attribute without ``=`` is a syntax error, and the
+#: only other source of attributes, the defaults of a DTD's
+#: attribute-list declarations (``xmlns:`` ones included), is refused
+#: in the same bytes before then (``_XmlProlog``), so no parser builds
+#: a start tag of more attributes.
+#: expat keeps about 108 bytes per attribute of the tag it is parsing
+#: and sets no limit (one tag of 1,000,000 attributes, 11 MB, held
+#: about 175 MB in the scan). libxml2 refuses a start tag over 10 MB
+#: up front only when it parses from a buffer (``fromstring``): its
+#: push parser, as the scan drives it, buffers the whole tag and
+#: reports that limit only once the tag is complete (4,000,000
+#: attributes, 47 MB, held 551 MB first), and lxml's ``iterparse``,
+#: which the ``.docx``/``.pptx`` walkers and the relationships check
+#: use, builds such an element in full (2,000,000 attributes, 23 MB,
+#: held 406 MB; one of 1,000,000 cost the guard about 200 MB in a
+#: ``.docx``, ``.pptx`` or relationships part). Office writers put a
+#: few dozen attributes on an element; this also admits a text node of
+#: 32,767 ``=``, the most a cell holds in Excel.
+MAX_XML_TAG_ATTRIBUTE_SIGNS = 65_536
+
+#: An XML declaration as XML 1.0 (section 2.8) spells it, in bytes: the
+#: version, then optionally the encoding name (group 1 or 2) and the
+#: standalone flag, separated by XML whitespace.
+_XML_DECLARATION = re.compile(
+ rb"<\?xml[ \t\r\n]+version[ \t\r\n]*=[ \t\r\n]*"
+ rb"(?:\"1\.[0-9]+\"|'1\.[0-9]+')"
+ rb"(?:[ \t\r\n]+encoding[ \t\r\n]*=[ \t\r\n]*"
+ rb"(?:\"([A-Za-z][A-Za-z0-9._-]*)\"|'([A-Za-z][A-Za-z0-9._-]*)'))?"
+ rb"(?:[ \t\r\n]+standalone[ \t\r\n]*=[ \t\r\n]*"
+ rb"(?:\"(?:yes|no)\"|'(?:yes|no)'))?"
+ rb"[ \t\r\n]*\?>"
+)
+
+
+def _require_utf8_xml(head: bytes) -> None:
+ """Refuse an XML part starting with *head* (its first
+ ``_XML_SCAN_CHUNK`` bytes, or all of a shorter part) unless both
+ parsers read it as UTF-8: an optional UTF-8 byte-order mark, then
+ ``<`` or XML whitespace, no NUL byte anywhere in *head*, and either
+ no XML declaration or one, complete within *head*, that names no
+ encoding or names UTF-8 (in any case).
+
+ The guard counts a part's ``<`` and ``=`` in bytes
+ (``_XmlTagSigns``), which holds only for an ASCII-compatible
+ encoding both parsers agree on, and they do not agree on UTF-16:
+ expat reads a part whose first or second byte is zero as UTF-16
+ without a byte-order mark (`` \\x00<\\x00`` as UTF-16LE), where
+ libxml2 sees UTF-8 and fails, and libxml2 switches to UTF-16 after
+ an ASCII declaration naming ``UTF-16LE``, which expat rejects. In
+ UTF-16 a character whose low byte is ``3C`` (U+013C) is a ``<`` to
+ a byte count, so a start tag of millions of attributes passed it.
+ OPC (ECMA-376 Part 2) allows XML parts in UTF-8 or UTF-16, but
+ every producer surveyed writes UTF-8 (Excel, Word and PowerPoint;
+ LibreOffice's serializer, which writes nothing else; openpyxl,
+ XlsxWriter, python-docx, python-pptx and SheetJS), as do all 2,238
+ XML members of the 88 local Office files checked; the only UTF-16
+ package found is a reader's test fixture (PhpSpreadsheet's). The NUL and
+ first-byte tests also refuse UTF-32 and EBCDIC (``4C 6F A7 94``),
+ which libxml2 detects and expat does not, and the declaration test
+ every other declared encoding."""
+ body = head[3:] if head.startswith(b"\xef\xbb\xbf") else head
+ if b"\x00" in head or (body and body[:1] not in b"< \t\r\n"):
+ raise DecompressionBombError(
+ "document package part is not encoded in UTF-8"
+ )
+ if body.startswith(b"<?xml") and body[5:6] in (b" ", b"\t", b"\r", b"\n"):
+ declaration = _XML_DECLARATION.match(body)
+ if declaration is None:
+ raise DecompressionBombError(
+ "document package part's XML declaration is malformed "
+ "or too long"
+ )
+ name = declaration.group(1) or declaration.group(2)
+ if name is not None and name.lower() != b"utf-8":
+ raise DecompressionBombError(
+ "document package part is not encoded in UTF-8"
+ )
+
+
+class _XmlTagSigns:
+ """Count the ``=`` between two ``<`` of a UTF-8 part
+ (``_require_utf8_xml``) streamed in chunks of at most
+ ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` bytes, and refuse more than that.
+ Bytes are counted: no multi-byte UTF-8 sequence holds either byte.
+ Only the run open at a chunk's end is carried: a run inside one
+ chunk is shorter than the ceiling."""
+
+ def __init__(self) -> None:
+ self._open = 0
+
+ def feed(self, chunk: bytes) -> None:
+ first = chunk.find(b"<")
+ if first < 0:
+ self._open += chunk.count(b"=")
+ else:
+ self._open += chunk.count(b"=", 0, first)
+ self._check()
+ self._open = chunk.count(b"=", chunk.rfind(b"<"))
+ self._check()
+
+ def _check(self) -> None:
+ if self._open > MAX_XML_TAG_ATTRIBUTE_SIGNS:
+ raise DecompressionBombError(
+ "document package part has a start tag that may carry "
+ f"more than {MAX_XML_TAG_ATTRIBUTE_SIGNS} attributes"
+ )
+
+
+class _XmlProlog:
+ """Refuse a markup declaration in the prolog of a UTF-8 part
+ (``_require_utf8_xml``) streamed in chunks: any ``<!`` before the
+ root element's start tag that does not open a comment (``<!--``).
+
+ A document type declaration, the only place an ``<!ENTITY``,
+ ``<!ATTLIST``, ``<!ELEMENT`` or ``<!NOTATION`` can stand, is legal
+ only there; in content, or before the root with no ``<!DOCTYPE``,
+ lxml and expat fail on ``<!`` that opens neither a comment nor a
+ CDATA section without reading a declaration. Refusing it in the
+ bytes keeps the internal subset from every parser: libxml2 reads
+ (and its push parser first buffers) the whole subset before the
+ root's first event, where ``_refuse_dtd`` looks, building every
+ declaration (one million attribute declarations, a 17.9 MB part,
+ held 424 MB), and attribute defaults it declares, ``xmlns:`` ones
+ included, are added to the start tags they name, attributes the
+ ``=`` count (``_XmlTagSigns``) never sees. Comments and processing
+ instructions before the root are skipped as the parsers end them
+ (``-->``, ``?>``); ``<!-`` without a second ``-``, or ``--``
+ inside a comment, which both parsers reject, is refused.
+ Scanning stops at the first ``<`` that opens neither, the root
+ element (or markup both parsers reject), so ``<!`` in content,
+ comments and CDATA sections is never examined."""
+
+ def __init__(self) -> None:
+ self._state = "prolog" # or "dash", "comment", "pi", "done"
+ self._carry = b""
+
+ def feed(self, chunk: bytes) -> None:
+ if self._state == "done":
+ return
+ data = self._carry + chunk
+ self._carry = b""
+ at = 0
+ while True:
+ if self._state == "pi":
+ end = data.find(b"?>", at)
+ if end < 0:
+ if data.endswith(b"?") and len(data) - 1 >= at:
+ self._carry = b"?"
+ return
+ at = end + 2
+ self._state = "prolog"
+ elif self._state == "dash": # after "<!-"
+ if at >= len(data):
+ return
+ if data[at : at + 1] != b"-":
+ raise DecompressionBombError(
+ "document package part has a malformed comment "
+ "before its root element"
+ )
+ at += 1
+ self._state = "comment"
+ elif self._state == "comment":
+ end = data.find(b"--", at)
+ if end < 0:
+ if data.endswith(b"-") and len(data) - 1 >= at:
+ self._carry = b"-"
+ return
+ if end + 2 >= len(data):
+ self._carry = data[end:]
+ return
+ if data[end + 2 : end + 3] != b">":
+ raise DecompressionBombError(
+ "document package part has a malformed comment "
+ "before its root element"
+ )
+ at = end + 3
+ self._state = "prolog"
+ else:
+ start = data.find(b"<", at)
+ if start < 0:
+ return
+ if len(data) - start < 3:
+ # "<" or "<!" (no declaration yet) reach the parser
+ # and are decided with the next chunk.
+ self._carry = data[start:]
+ return
+ after = data[start + 1 : start + 2]
+ if after == b"?":
+ self._state = "pi"
+ at = start + 2
+ elif after != b"!":
+ self._state = "done"
+ return
+ elif data[start + 2 : start + 3] == b"-":
+ self._state = "dash"
+ at = start + 3
+ else:
+ raise DecompressionBombError(
+ "document package part declares a DTD"
+ )
+
+
+class _CountedXmlStream:
+ """A binary stream over *stream* (a member's stream or a
+ ``BytesIO``) that an lxml ``iterparse`` reads in place of it: the
+ part is held to ``_require_utf8_xml`` before its first byte is
+ returned, and every chunk is counted by ``_XmlTagSigns`` and
+ scanned by ``_XmlProlog`` before it is returned, so the parser
+ never receives a start tag of more than
+ ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` attributes or more of a document
+ type declaration than the ``<!`` that opens it (when a chunk ends
+ there; the next chunk is refused). A read returns at most
+ ``_XML_SCAN_CHUNK`` bytes."""
+
+ def __init__(self, stream) -> None:
+ self._stream = stream
+ self._signs: Optional[_XmlTagSigns] = None
+ self._prolog = _XmlProlog()
+ self._pending = b""
+
+ def read(self, size: Optional[int] = -1) -> bytes:
+ if self._signs is None:
+ head = self._stream.read(_XML_SCAN_CHUNK)
+ _require_utf8_xml(head)
+ self._signs = _XmlTagSigns()
+ self._signs.feed(head)
+ self._prolog.feed(head)
+ self._pending = head
+ if size is None or size < 0 or size > _XML_SCAN_CHUNK:
+ size = _XML_SCAN_CHUNK
+ if self._pending:
+ chunk = self._pending[:size]
+ self._pending = self._pending[size:]
+ return chunk
+ chunk = cast(bytes, self._stream.read(size))
+ self._signs.feed(chunk)
+ self._prolog.feed(chunk)
+ return chunk
+
+
+def _read_counted_xml(archive: zipfile.ZipFile, info: zipfile.ZipInfo) -> bytes:
+ """Member *info*, a whole part about to be parsed from a buffer,
+ read through ``_CountedXmlStream``: held to ``_require_utf8_xml``,
+ counted by ``_XmlTagSigns`` and scanned by ``_XmlProlog`` chunk by
+ chunk as it is read, so a refused part is refused before the rest
+ of it is read."""
+ with archive.open(info) as member:
+ stream = _CountedXmlStream(member)
+ return b"".join(
+ iter(functools.partial(stream.read, _XML_SCAN_CHUNK), b"")
+ )
+
+
+def _check_xlsx_sheet_fan_out(content: bytes) -> None:
+ """Refuse a workbook listing the same sheet part more than once.
+
+ openpyxl (via pandas) reads and converts a sheet part once per
+ ``<sheet>`` that resolves to it, so N ``<sheet>`` entries sharing
+ one part turn one bounded part into N times the parsing work and
+ extracted text. Genuine workbooks never share a sheet part.
+
+ The sheet list is computed by openpyxl itself — the same
+ ``ExcelReader`` steps ``load_workbook`` runs (``read_manifest``,
+ ``read_workbook``, ``WorkbookParser.find_sheets``) with the options
+ pandas passes (``read_only``, ``data_only``, ``keep_links=False``,
+ no VBA) — so the guard cannot disagree with the loader about which
+ part each sheet names. Those steps parse only ``[Content_Types].xml``,
+ the workbook part and the workbook's relationships (external links
+ are not read with ``keep_links=False``); no worksheet, drawing or
+ shared-string part is parsed. Each of those parts is first held to
+ ``MAX_XLSX_SKELETON_PART_BYTES`` (16 MiB), scanned
+ (``_check_xlsx_namespaces``, ``[Content_Types].xml`` with expat as
+ well, for msoffcrypto) and checked before openpyxl parses it: a DTD
+ is refused, and so, after one lxml parse
+ of the part, is a comment or processing instruction below its root's
+ children (``_refuse_xlsx_nested_node``; openpyxl would build one
+ into a list entry), and the workbook part's lists and elements are
+ held as ``_check_xlsx_workbook_tree`` holds them. The cost is two
+ extra parses of at most that
+ much XML per part, the same parse the loader performs right after.
+ Once the sheet list passes (``_check_xlsx_sheet_list``), every other
+ part openpyxl's load parses (``_xlsx_loaded_parts``) is scanned the
+ same way, each with the parser the load uses for it, and the styles
+ part is then streamed once (``_check_xlsx_styles``).
+
+ ``rel.target`` is compared exactly: ``read_worksheets`` looks it up
+ by exact name among the archive's members, so only identical
+ strings load the same member. Every ``<sheet>``'s name, with or
+ without a relationship, is held to ``MAX_XLSX_SHEET_NAME_CHARS``,
+ and no two may be equal once lowercased.
+ """
+ try:
+ import openpyxl # noqa: F401
+ except ImportError: # no openpyxl, no openpyxl fan-out
+ return
+
+ try:
+ # Imported inside the fail-closed block: if an openpyxl upgrade
+ # moves these, every .xlsx is refused (and the control tests
+ # fail) rather than the check silently switching off.
+ from openpyxl.packaging.relationship import get_rels_path
+ from openpyxl.reader.excel import ExcelReader, _find_workbook_part
+ from openpyxl.xml.constants import ARC_CONTENT_TYPES
+
+ reader = ExcelReader(
+ io.BytesIO(content),
+ read_only=True,
+ keep_vba=False,
+ data_only=True,
+ keep_links=False,
+ )
+ with reader.archive:
+ archive = reader.archive
+ scanned: set[tuple[str, str]] = set()
+ # The parts parsed here are package skeleton, a few KB in
+ # real workbooks; a tighter ceiling than the general parsed
+ # part keeps this extra full-tree parse cheap. Each is
+ # scanned (_check_xlsx_namespaces) before it is parsed, and
+ # [Content_Types].xml for msoffcrypto's minidom too.
+ _require_skeleton_size(
+ archive, ARC_CONTENT_TYPES, scanned, (_LXML, _EXPAT)
+ )
+ reader.read_manifest()
+ workbook = _find_workbook_part(reader.package).PartName[1:]
+ _require_skeleton_size(archive, workbook, scanned, workbook=True)
+ _require_skeleton_size(archive, get_rels_path(workbook), scanned)
+ reader.read_workbook()
+ sheets = list(reader.parser.find_sheets())
+ _check_xlsx_sheet_list(
+ [rel.target for _sheet, rel in sheets],
+ [sheet.name or "" for sheet in reader.parser.sheets],
+ )
+ _check_xlsx_namespaces(
+ archive, _xlsx_loaded_parts(reader, sheets), scanned
+ )
+ _check_xlsx_styles(archive)
+ except DecompressionBombError:
+ raise
+ except Exception as exc: # openpyxl's failure modes are open-ended
+ raise DecompressionBombError("malformed spreadsheet package") from exc
+
+
+def _check_xlsx_sheet_list(targets: list[str], names: list[str]) -> None:
+ """Refuse the sheet list ``_check_xlsx_sheet_fan_out`` read (each
+ sheet's resolved part and every sheet's name) for the reasons its
+ docstring gives."""
+ from openpyxl.packaging.relationship import get_rels_path
+
+ if len(targets) > MAX_XLSX_SHEETS:
+ raise DecompressionBombError(
+ f"spreadsheet lists more than {MAX_XLSX_SHEETS} sheets"
+ )
+ if any(len(name) > MAX_XLSX_SHEET_NAME_CHARS for name in names):
+ raise DecompressionBombError(
+ "spreadsheet sheet name is longer than "
+ f"{MAX_XLSX_SHEET_NAME_CHARS} characters"
+ )
+ folded = [name.lower() for name in names]
+ if len(folded) != len(set(folded)):
+ raise DecompressionBombError("spreadsheet lists two sheets of one name")
+ if len(targets) != len(set(targets)):
+ raise DecompressionBombError(
+ "spreadsheet lists the same sheet part more than once"
+ )
+ # openpyxl also parses each sheet's own relationships part, found
+ # via get_rels_path — which collapses targets that differ only in
+ # repeated slashes onto one path — so those must be unique too.
+ rels_paths = [get_rels_path(target) for target in targets]
+ if len(rels_paths) != len(set(rels_paths)):
+ raise DecompressionBombError(
+ "spreadsheet sheets share one relationships part"
+ )
+
+
+def _xlsx_loaded_parts(reader, sheets) -> dict[str, frozenset[str]]:
+ """The parts openpyxl's read-only load (``ExcelReader.read`` with
+ the options pandas passes) parses after the workbook skeleton, each
+ with its parser family, found as ``read`` finds them: the shared
+ strings part the manifest names (``read_strings``, expat), the core
+ and custom document properties and the styles part when present
+ (``read_properties``, ``read_custom``, ``apply_stylesheet``, lxml),
+ and for every sheet whose resolved part exists
+ (``read_worksheets``) its relationships part when present
+ (``get_dependents``, lxml) and the part itself: a chartsheet's
+ (``"chartsheet"`` in the relationship type) with lxml
+ (``read_chartsheet``), a worksheet's with expat, which pandas
+ streams it with. ``read_theme`` reads the theme's bytes without
+ parsing them, and drawings are never read
+ (``openpyxl_hardening``), so neither is listed, nor is any part
+ found only by its name or folder (images, unreferenced members)."""
+ from openpyxl.packaging.relationship import get_rels_path
+ from openpyxl.xml.constants import (
+ ARC_CORE,
+ ARC_CUSTOM,
+ ARC_STYLE,
+ SHARED_STRINGS,
+ )
+
+ valid = set(reader.valid_files)
+ parts: dict[str, set[str]] = {}
+
+ def add(name: str, family: str) -> None:
+ if name in valid:
+ parts.setdefault(name, set()).add(family)
+
+ strings = reader.package.find(SHARED_STRINGS)
+ if strings is not None:
+ add(strings.PartName[1:], _EXPAT)
+ for name in (ARC_CORE, ARC_CUSTOM, ARC_STYLE):
+ add(name, _LXML)
+ for _sheet, rel in sheets:
+ if rel.target not in valid:
+ continue
+ add(get_rels_path(rel.target), _LXML)
+ add(rel.target, _LXML if "chartsheet" in rel.Type else _EXPAT)
+ return {name: frozenset(families) for name, families in parts.items()}
+
+
+#: Ceiling for the package-skeleton parts the fan-out check parses in
+#: full ([Content_Types].xml, the workbook part and its relationships).
+#: Typical workbooks keep them in kilobytes, and thousands of sheets
+#: stay well under 1 MiB, but the workbook part grows with defined
+#: names: a workbook with more than roughly 170k defined names (about
+#: 100 bytes each) exceeds 16 MiB and is refused. At the general
+#: 128 MiB parsed-part ceiling, one extra full-tree parse would cost
+#: gigabytes.
+MAX_XLSX_SKELETON_PART_BYTES = 16 * 1024 * 1024
+
+#: Ceiling on the sheets a workbook lists (``<sheet>`` entries with a
+#: relationship id, as openpyxl's ``find_sheets`` yields them). openpyxl
+#: checks each sheet's target against the archive's member list, a
+#: Python list (``rel.target not in self.valid_files``), before it skips
+#: a sheet whose part is missing, and pandas looks every sheet up by
+#: name in the list of all sheet names, then in the workbook's sheets
+#: (``raise_if_bad_sheet_by_name`` and ``Workbook.__getitem__``): sheets
+#: times members, and sheets squared. 10,000 empty sheets, a 2.5 MB file
+#: within the entry ceiling, took 40 s in ``pandas.read_excel`` before
+#: the change, and 100,000 sheets without parts next to 9,000 other
+#: members, a 2.2 MB file, 7.6 s in ``openpyxl.load_workbook`` alone
+#: (a 16 MiB workbook part lists about 370,000). 2,000 empty sheets take
+#: about 2 s in ``pandas.read_excel``, and 2,000 one-cell sheets about
+#: 5 s in unstructured's ``partition_xlsx`` (500, 1.2 s). Workbooks
+#: rarely have more than a few hundred sheets.
+MAX_XLSX_SHEETS = 2_000
+
+#: Ceiling on the characters of a sheet's name (``<sheet name>``).
+#: openpyxl names every chartsheet it reads after comparing its name,
+#: lowercased, with every sheet name before it, and pandas looks every
+#: worksheet up by name in lists of all of them, so long names multiply
+#: the per-sheet work ``MAX_XLSX_SHEETS`` bounds: 2,000 sheets of
+#: 8,000-character names, a 554 KB file, took 6.4 s in
+#: ``pandas.read_excel`` (of 31 characters, about 2 s). Excel limits a
+#: sheet name to 31 characters and Google Sheets to 100. Two sheets
+#: whose names are equal once lowercased (``str.lower``) are refused
+#: too: Excel forbids them, and openpyxl renames such a chartsheet by
+#: joining every sheet name into one string and searching it with a
+#: regular expression, once per chartsheet.
+MAX_XLSX_SHEET_NAME_CHARS = 255
+
+#: Ceiling on the characters of a defined name's value in the workbook
+#: part (measured at the longest of a ``definedName`` entry's attribute
+#: values, its text and its children's: openpyxl reads the value from
+#: an ``attr_text`` or ``attr-text`` attribute or the text, and other
+#: fields from attributes or children of their names). Excel limits a
+#: formula, and the reference a name stands for, to 8,192 characters.
+MAX_XLSX_DEFINED_NAME_CHARS = 8_192
+
+#: Ceiling on the work openpyxl's load spends on the print titles and
+#: print areas of the workbook's defined names, each counted at its
+#: value's length squared plus ``XLSX_PRINT_NAME_BASE_UNITS``. On every
+#: load (pandas' read-only one too, ``WorkbookParser.assign_names``)
+#: openpyxl parses each sheet-local name that starts like
+#: ``_xlnm.Print_Titles`` or ``_xlnm.Print_Area`` (a prefix match, so
+#: one sheet can hold any number of them) with
+#: ``PrintTitles.from_string`` or ``PrintArea.from_string``, whose
+#: regular expressions scan for a sheet title from every position of
+#: the value and back off at its end: time quadratic in its length, up
+#: to about 34 ns per character squared (a value of 40,000 ``#`` took
+#: 14 s and 31 s, and a 1 MB one would take hours, holding the GIL),
+#: plus about 50 us per name (65,536 values of 32 characters took
+#: 5.5 s). The guard counts such names whatever their sheet. This
+#: ceiling admits one value at ``MAX_XLSX_DEFINED_NAME_CHARS``, which
+#: takes 2.3 to 2.9 s to load, 16,476 of 45 characters (2.2 s) or
+#: 31,776 of 8 (0.9 s); Excel writes one print area and one set of
+#: print titles per sheet, a sheet reference per range (under 100
+#: characters each).
+XLSX_PRINT_NAME_BASE_UNITS = 2_048
+MAX_XLSX_PRINT_NAME_WORK = (
+ MAX_XLSX_DEFINED_NAME_CHARS**2 + XLSX_PRINT_NAME_BASE_UNITS
+)
+_XLSX_PRINT_NAMES = ("_xlnm.Print_Titles", "_xlnm.Print_Area")
+
+#: Ceiling on the characters of a namespace URI declared in any XML
+#: member of an ``.xlsx`` package. lxml builds every element and
+#: attribute name it hands back as ``{URI}local``, and openpyxl (and
+#: the guard) read the name of every element of every part they parse,
+#: so one long URI declared once and used through a short prefix is
+#: copied again for every element: 2,000 empty elements under a
+#: 1,000,000-character URI in a worksheet, a 5.9 KB file, took 3.8 s
+#: in ``pandas.read_excel``. Office writers declare URIs well under 100
+#: characters; this is the ``.docx`` ceiling
+#: (``MAX_DOCX_NAMESPACE_URI_CHARS``). The scan that checks it in
+#: every part openpyxl parses (``_check_xlsx_namespaces``), with a
+#: Python call per element for the depth ceiling, costs the guard about
+#: 6.5 s per 100 MB of worksheet XML (pandas takes about 20 s to read it)
+#: and about 8 s per 100 MB of element-dense lxml parts.
+MAX_XLSX_NAMESPACE_URI_CHARS = 1_024
+
+
+#: Ceiling on the characters of a custom number format code
+#: (``<numFmt formatCode>``) in ``xl/styles.xml``. Excel's format
+#: dialog and the ``.xls`` Format record hold a code to 255
+#: characters; this allows four times that.
+MAX_XLSX_NUMBER_FORMAT_CHARS = 1_024
+
+#: Ceiling on the entries of each of the cell-format lists of
+#: ``xl/styles.xml`` (``<xf>`` elements of ``cellXfs`` and of
+#: ``cellStyleXfs``, ``<cellStyle>`` elements of ``cellStyles``), each
+#: counted over every such list in the part. Excel's specifications
+#: limit a workbook to 65,490 unique cell formats and cell styles.
+MAX_XLSX_CELL_FORMATS = 65_490
+
+#: Ceiling on the work openpyxl's stylesheet load spends on number
+#: formats, which it does on every load (``apply_stylesheet``, under
+#: pandas' read-only load too). ``Stylesheet._normalise_numbers`` runs
+#: ``is_date_format`` and ``is_timedelta_format`` (a split and three
+#: regular-expression scans) over the format code of every ``<xf>`` of
+#: ``cellXfs``, so N formats sharing one long code cost N times its
+#: length: one 1,000,000-character code under 2,000 formats, a 3.3 KB
+#: file, took 53 s to load. One scan skips ahead past a ``[`` only at
+#: the next ``]``, so a code with B unclosed ``[`` costs up to B times
+#: its length. Each format is counted at its code's length times
+#: ``XLSX_NUMBER_FORMAT_SCAN_WEIGHT`` plus its ``[`` (a code shared by
+#: several ``numFmt`` entries at the costliest of them; a built-in
+#: format at 64 characters); a unit measured about 0.5 ns for codes of
+#: zeros and of brackets alike: 3,600 formats of 1,024 ``[``, counted
+#: at 0.99 of this ceiling, load in 2.1 s, and 65,490 formats of 1,024
+#: zeros, at 0.84, in 2.9 s. 65,490 formats of an ordinary 30-character
+#: date code with one bracket count about 100 million.
+MAX_XLSX_NUMBER_FORMAT_WORK = 4_000_000_000
+XLSX_NUMBER_FORMAT_SCAN_WEIGHT = 50
+_XLSX_BUILTIN_FORMAT_CHARS = 64
+
+#: Ceiling on the work openpyxl spends per named style, which it does
+#: on every load (under pandas' read-only load too). For every named
+#: style (``<cellStyle>``, duplicates dropped) ``Stylesheet``
+#: builds a ``NamedStyle`` with fresh default font, fill, border,
+#: alignment and protection objects, rebuilds the dict of every custom
+#: number format (``custom_formats``) when its ``cellStyleXfs`` format
+#: is custom, and ``apply_stylesheet`` binds it to the workbook
+#: (``NamedStyle.bind``), which hashes its font, fill, border,
+#: alignment, protection and number format into the workbook's indexed
+#: lists and compares each with an equal entry already listed. A hash
+#: walks the whole object, so a gradient fill costs every stop, and a
+#: comparison reads every string, so a font costs its name's length.
+#: Each named style is counted at ``XLSX_NAMED_STYLE_BASE_UNITS`` plus
+#: the ``numFmt`` entries plus, for the largest font, the largest fill
+#: and the largest border of the part (whichever one it binds),
+#: ``XLSX_STYLE_NODE_UNITS`` per element and one unit per
+#: ``XLSX_STYLE_CHARS_PER_UNIT`` characters of attribute values and
+#: text, plus the longest format code at the same rate. A unit is
+#: about 130 ns (one entry of the rebuilt format dict); an element
+#: (one gradient stop is two) about 1.5 us, and the fixed work about
+#: 75 us. Named styles are counted as the distinct ``xfId`` values of
+#: ``cellStyle`` entries within ``-n`` to ``n - 1`` for the ``n``
+#: ``cellStyleXfs`` entries: openpyxl drops a style whose ``xfId``
+#: repeats, indexes a negative one from the end (so ``n`` formats
+#: carry up to ``2n`` named styles) and fails to load an id out of that
+#: range. 8,800 named styles over 4,400 formats and 4,400 custom
+#: formats took 5.3 s to load, and 1,000 named styles of a 1,000-stop
+#: gradient fill about 3 s; 20,000 named styles of a minimal font, fill
+#: and border, counted at 0.66 of this ceiling, load in 1.8 s, 2,000 of
+#: a 256-stop gradient fill, at 0.89, in 1.6 s, and a workbook bloated
+#: to 15,000 named styles of Excel's default font, fills and border
+#: with 300 custom formats, at 0.84, in 2 s (20,000 such, at 1.12,
+#: take 2.7 s and are refused).
+MAX_XLSX_NAMED_STYLE_WORK = 20_000_000
+XLSX_NAMED_STYLE_BASE_UNITS = 600
+XLSX_STYLE_NODE_UNITS = 16
+XLSX_STYLE_CHARS_PER_UNIT = 256
+
+#: Ceiling on the ``<stop>`` elements of one gradient fill in
+#: ``xl/styles.xml``. openpyxl hashes every stop each time a named style
+#: binds the fill. Excel's cell gradient dialog sets two or three
+#: stops (its "Fill Effects" offer two colours); this allows 256.
+MAX_XLSX_GRADIENT_STOPS = 256
+
+_XLSX_STYLES_PART = "xl/styles.xml"
+#: The ``xl/styles.xml`` lists whose entries openpyxl binds once per
+#: named style (each read as a list of all the container's children,
+#: whatever their tag; comments and processing instructions are refused
+#: there, see ``_refuse_xlsx_nested_node``).
+_XLSX_BOUND_LISTS = ("fonts", "fills", "borders")
+
+
+def _refuse_xlsx_nested_node(depth: int, part: str) -> None:
+ """Refuse a comment or processing instruction of the ``.xlsx``
+ *part* (named for the message) that is *depth* elements deep,
+ unless it lies outside the root (*depth* 0) or directly under it
+ (*depth* 1).
+
+ openpyxl parses ``xl/styles.xml`` and the workbook skeleton parts
+ with lxml, which keeps comments and processing instructions as
+ child nodes, and ``NestedSequence`` builds one entry per child
+ *node* of its container, whatever it is
+ (``[expected_type.from_tree(el) for el in node]``): a comment among
+ the ``fonts``, ``borders`` or ``dxfs`` of ``xl/styles.xml`` becomes a
+ default ``Font``, ``Border`` or ``DifferentialStyle``, one among
+ ``mruColors`` a default ``Color``, and one among the workbook's
+ ``bookViews`` a default ``BookView`` (among ``fills``,
+ ``indexedColors`` and ``sheets`` openpyxl fails to load instead).
+ The guard counts elements, so 2,000,000 empty comments after one
+ font, a 25 KB file whose styles part is 14 MB, were accepted and
+ took openpyxl 37 s and 960 MB to load as 2,000,001 fonts, and
+ 2,390,000 among the ``bookViews`` of a 16 MiB workbook part took the
+ guard's own openpyxl parse of it 19.6 s and 1.1 GB. Elsewhere below
+ the root openpyxl skips them (``Serialisable.from_tree``, which
+ reads ``Sequence`` lists such as ``cellXfs``, ``numFmts``,
+ ``cellStyles`` or a gradient's stops, and single entries) or fails
+ to load (in a ``fill`` before its pattern, or in a ``patternFill``).
+ Directly under the root ``Serialisable.from_tree`` skips them too,
+ at the cost of the tree node lxml builds for each, and the
+ relationships list, read as every child node of its root, fails to
+ load, which leaves openpyxl without the workbook's sheets (refused
+ as malformed). Excel writes no comments or processing instructions
+ in these parts, so any below the root's children is refused rather
+ than counted, and every child node of a list the guard counts is
+ then an element it counts."""
+ if depth >= 2:
+ raise DecompressionBombError(
+ f"spreadsheet {part} part has a comment or processing "
+ "instruction below its top level"
+ )
+
+
+#: Ceiling on the entries of each of the font, fill and border lists of
+#: ``xl/styles.xml``, each counted over every such list in the part.
+#: openpyxl builds every entry into a style object and an indexed list
+#: of each list on every load, and the guard rebuilds each differently
+#: spelled entry once (``MAX_XLSX_STYLE_HASH_CHAIN``). Excel's
+#: specifications allow 512 fonts per workbook and 256 fill and line
+#: styles; this allows 8,192 of each. A 16 MB styles part with all
+#: three lists at this ceiling and 65,490 cell formats, each with its
+#: own alignment and protection, loads in 5.3 s (the guard takes 10 s).
+MAX_XLSX_STYLE_LIST_ENTRIES = 8_192
+
+#: Ceilings on the other lists of ``xl/styles.xml`` and of the workbook
+#: part that openpyxl builds an object from per entry, each counted over
+#: every such list in the part (``_XLSX_STYLE_LISTS`` and
+#: ``_XLSX_WORKBOOK_LISTS``). Excel documents 200 to 250 custom number
+#: formats per workbook; the differential formats of conditional
+#: formatting and tables (``dxfs``) are held to its 65,490 cell formats;
+#: Excel writes a 64-colour ``indexedColors`` palette and up to ten
+#: ``mruColors``; custom table styles, workbook views, external
+#: references and pivot caches have no documented limit and number a
+#: handful in real files. A table style has one element per table part
+#: (28 kinds; counted per table style). Extensions (``<ext>`` of every
+#: ``extLst``, counted over the part) number one per cell format at most
+#: in Excel's output (``xfComplement``), plus a few.
+MAX_XLSX_NUMBER_FORMATS = 8_192
+MAX_XLSX_DIFFERENTIAL_FORMATS = 65_490
+MAX_XLSX_COLOR_LIST_ENTRIES = 1_024
+MAX_XLSX_TABLE_STYLES = 1_024
+MAX_XLSX_TABLE_STYLE_ELEMENTS = 32
+MAX_XLSX_EXTENSIONS = 131_072
+MAX_XLSX_WORKBOOK_LIST_ENTRIES = 8_192
+
+#: Ceiling on the elements below ``dxfs`` in ``xl/styles.xml`` (its
+#: entries and everything in them). A differential format holds up to a
+#: font, number format, fill, alignment, border and protection, each a
+#: handful of elements, and openpyxl builds them all: 10,000 with every
+#: one of those filled in (43 elements each, a 9 MB part) take 3.5 s to
+#: load. Excel writes a few elements per differential format.
+MAX_XLSX_DIFFERENTIAL_FORMAT_ELEMENTS = 500_000
+
+#: Ceiling on the gradient ``<stop>`` elements of ``xl/styles.xml``
+#: together (fills and differential formats). openpyxl builds every
+#: stop and its colour, and the guard rebuilds every distinct fill:
+#: 1,000 fills of 256 stops, a 14 MB part, took 4.5 s to load and the
+#: guard 8 s, and the 8,192 fills allowed would take about 37 s and
+#: 66 s. Excel's gradients have two or three stops.
+MAX_XLSX_GRADIENT_STOPS_TOTAL = 65_536
+
+#: Ceiling on the elements of one entry of the font, fill, border and
+#: cell-format lists of ``xl/styles.xml`` (the entry and everything in
+#: it, the content of an extension included). The guard holds each such
+#: entry whole until it ends, to rebuild it with openpyxl's classes,
+#: and then drops it; lxml frees a detached subtree in linear time, but
+#: when a Python proxy of a node inside it is still alive (as
+#: ``iterparse`` leaves some) and the part declares a namespace, as
+#: every Office part does, lxml instead moves the subtree to a document
+#: of its own in time quadratic in its nodes: one fill holding 80,000
+#: elements took the guard 1.6 s to drop, 160,000 took 6.5 s. Excel
+#: writes a dozen or so; a gradient fill at ``MAX_XLSX_GRADIENT_STOPS``
+#: stops has 514.
+MAX_XLSX_STYLE_ENTRY_ELEMENTS = 1_024
+
+#: Ceiling on the child elements of the root of ``xl/styles.xml`` and of
+#: the workbook part. openpyxl builds every child it knows into an
+#: object (keeping only the last of a repeated one), so 1,800,000 empty
+#: ``<calcPr/>`` in a 16 MiB workbook part took its parse 17 s (the
+#: guard's own parse as long again). Excel writes about a dozen.
+MAX_XLSX_TOP_LEVEL_ELEMENTS = 256
+
+#: Range of the integers openpyxl reads from ``xl/styles.xml`` (ids,
+#: colour indices, charsets and the like; the schema types them as
+#: 32-bit, ``xsd:int`` or ``xsd:unsignedInt``), and the magnitude of its
+#: floats (sizes, tints, gradient geometry; Excel's largest font is 409
+#: points). Python hashes a number modulo ``2**61 - 1``, so integers
+#: ``1 + k * (2**61 - 1)`` are distinct values of one hash: 4,000 fonts
+#: differing only in such a ``charset`` took 6.6 s to load (a 51 KB
+#: part) and 8,000 of them under 8,000 named styles 81 s. Within this
+#: range distinct integers hash apart, which also keeps the dicts
+#: openpyxl and the guard key by format and style ids linear.
+XLSX_STYLE_INT_MIN = -(2**31)
+XLSX_STYLE_INT_MAX = 2**32 - 1
+MAX_XLSX_STYLE_FLOAT = float(2**32)
+
+#: Ceiling on the distinct values of one hash in any of the indexed
+#: lists openpyxl's stylesheet load builds (fonts, fills, borders,
+#: alignments, protections, cell formats, number format codes) and in
+#: its set of named-style names. Each list is a dict keyed by the
+#: style object, whose hash openpyxl takes over the object's field
+#: values, so distinct objects of one hash cost a comparison with each
+#: other on insertion (quadratic in their number) and on every later
+#: lookup, which each named style repeats for its font, fill, border,
+#: alignment and protection. Bounding the numbers alone does not
+#: prevent it: a float field reaches almost any hash value (``x`` and
+#: ``x * 2**-61`` share one), and the hash of a tuple of free 32-bit
+#: fields can be steered by a meet-in-the-middle search. Real
+#: stylesheets have none; this allows the pair Python's hash folds
+#: (``-1`` and ``-2``). 28,000 named styles each binding the second of
+#: a pair in every list loaded in 8.2 s, against 7 s without pairs.
+MAX_XLSX_STYLE_HASH_CHAIN = 2
+
+#: The lists of ``xl/styles.xml`` under its root (matched by local
+#: name) and under its ``colors``, each read as a list of entries: by
+#: ``NestedSequence`` (every child node) or ``Sequence`` (every child of
+#: the entry's name; ``cellXfs`` also reads ``alignment`` and
+#: ``protection`` children), all counted here.
+_XLSX_STYLE_LISTS = (
+ "numFmts",
+ "fonts",
+ "fills",
+ "borders",
+ "cellStyleXfs",
+ "cellXfs",
+ "cellStyles",
+ "dxfs",
+ "tableStyles",
+)
+_XLSX_COLOR_LISTS = ("indexedColors", "mruColors")
+
+#: The lists of the workbook part under its root, each counted over
+#: every such list in the part: ``NestedSequence`` lists and the
+#: ``Sequence`` lists of the smart tag, function group and web publish
+#: objects. ``definedNames`` is held only by the part's 16 MiB ceiling
+#: (``MAX_XLSX_SKELETON_PART_BYTES``).
+_XLSX_WORKBOOK_LISTS = (
+ "bookViews",
+ "sheets",
+ "customWorkbookViews",
+ "externalReferences",
+ "pivotCaches",
+ "smartTagTypes",
+ "functionGroups",
+ "webPublishObjects",
+)
+
+
+def _xlsx_list_cap(name: str) -> int:
+ """The ceiling on the entries of the ``.xlsx`` list *name*."""
+ return {
+ "numFmts": MAX_XLSX_NUMBER_FORMATS,
+ "fonts": MAX_XLSX_STYLE_LIST_ENTRIES,
+ "fills": MAX_XLSX_STYLE_LIST_ENTRIES,
+ "borders": MAX_XLSX_STYLE_LIST_ENTRIES,
+ "cellStyleXfs": MAX_XLSX_CELL_FORMATS,
+ "cellXfs": MAX_XLSX_CELL_FORMATS,
+ "cellStyles": MAX_XLSX_CELL_FORMATS,
+ "dxfs": MAX_XLSX_DIFFERENTIAL_FORMATS,
+ "tableStyles": MAX_XLSX_TABLE_STYLES,
+ "indexedColors": MAX_XLSX_COLOR_LIST_ENTRIES,
+ "mruColors": MAX_XLSX_COLOR_LIST_ENTRIES,
+ "tableStyle": MAX_XLSX_TABLE_STYLE_ELEMENTS,
+ "extLst": MAX_XLSX_EXTENSIONS,
+ "sheets": MAX_XLSX_SHEETS,
+ }.get(name, MAX_XLSX_WORKBOOK_LIST_ENTRIES)
+
+
+def _refuse_xlsx_list_entry(part: str, name: str, count: int) -> None:
+ """Refuse the ``.xlsx`` *part* once list *name* has *count* entries
+ over its ceiling (``_xlsx_list_cap``)."""
+ cap = _xlsx_list_cap(name)
+ if count > cap:
+ if name == "sheets":
+ raise DecompressionBombError(
+ f"spreadsheet lists more than {cap} sheets"
+ )
+ raise DecompressionBombError(
+ f"spreadsheet {part} list more than {cap} {name} entries"
+ )
+
+
+def _refuse_xlsx_repeated_child(part: str, parent: str, seen: set, tag: str):
+ """Refuse the ``.xlsx`` *part* when an element that is not a list
+ (*parent*, whose child local names so far are *seen*) has a second
+ child named *tag*. openpyxl builds every child it knows into an
+ object and keeps only the last of a repeated one, so repeats cost a
+ build each and are bounded by nothing else; Excel writes none."""
+ if tag in seen:
+ raise DecompressionBombError(
+ f"spreadsheet {part} element {parent} repeats its {tag} child"
+ )
+ seen.add(tag)
+
+
+#: The ``xl/styles.xml`` lists whose entries the guard rebuilds as
+#: openpyxl's style objects (held in full until the entry ends).
+_XLSX_MODELLED_LISTS = ("fonts", "fills", "borders", "cellXfs", "cellStyleXfs")
+
+
+class _XlsxIndexedList:
+ """The distinct values openpyxl's ``IndexedList`` of *what* holds,
+ grouped by hash: ``add`` returns a value's index as
+ ``IndexedList.add`` does and refuses a value that would be the
+ ``MAX_XLSX_STYLE_HASH_CHAIN + 1``-th distinct one of its hash. The
+ groups are keyed by hash values (ints), which reduce modulo
+ ``2**61 - 1`` again, so at most eight of them share a slot here."""
+
+ def __init__(self, what: str, initial: tuple = ()) -> None:
+ self._what = what
+ self._groups: dict[int, list[tuple[object, int]]] = {}
+ self._size = 0
+ for value in initial:
+ self.add(value)
+
+ def add(self, value) -> int:
+ group = self._groups.setdefault(hash(value), [])
+ for known, index in group:
+ if known is value or known == value:
+ return index
+ if len(group) >= MAX_XLSX_STYLE_HASH_CHAIN:
+ raise DecompressionBombError(
+ f"spreadsheet styles hold more than "
+ f"{MAX_XLSX_STYLE_HASH_CHAIN} distinct {self._what} of "
+ "one hash"
+ )
+ group.append((value, self._size))
+ self._size += 1
+ return self._size - 1
+
+
[email protected]_cache(maxsize=1)
+def _xlsx_numeric_fields() -> tuple[
+ frozenset[str], frozenset[str], frozenset[str]
+]:
+ """Names of the integer fields and of the float fields of the
+ openpyxl style classes ``Stylesheet`` reads (walked from it through
+ every complex field and its subclasses), and of those read from a
+ ``val`` attribute of a child element of that name (``<sz val>``).
+ Derived from openpyxl so an upgrade that adds a field is covered.
+ No name is an integer in one class and a float in another."""
+ from openpyxl.descriptors import Descriptor
+ from openpyxl.descriptors.serialisable import Serialisable
+ from openpyxl.styles.stylesheet import Stylesheet
+
+ ints: set[str] = set()
+ floats: set[str] = set()
+ nested: set[str] = set()
+ seen: set[type] = set()
+ pending: list[type] = [Stylesheet]
+ while pending:
+ cls = pending.pop()
+ if cls in seen:
+ continue
+ seen.add(cls)
+ pending.extend(cls.__subclasses__())
+ for name in dir(cls):
+ desc = getattr(cls, name, None)
+ if not isinstance(desc, Descriptor):
+ continue
+ kind = getattr(desc, "expected_type", None)
+ if isinstance(kind, type) and issubclass(kind, Serialisable):
+ pending.append(kind)
+ elif kind is int or kind is float:
+ (ints if kind is int else floats).add(name)
+ if getattr(desc, "nested", False):
+ nested.add(name)
+ return frozenset(ints), frozenset(floats), frozenset(nested)
+
+
+def _check_xlsx_style_number(name: str, value: Optional[str]) -> None:
+ """Refuse *value* of the numeric style field *name* if openpyxl would
+ read it as an integer outside ``XLSX_STYLE_INT_MIN`` to
+ ``XLSX_STYLE_INT_MAX`` or a float of magnitude over
+ ``MAX_XLSX_STYLE_FLOAT`` (NaN included). A value that is not a
+ number is left to openpyxl, which fails to load it."""
+ ints, floats, _nested = _xlsx_numeric_fields()
+ if value is None or (name not in ints and name not in floats):
+ return
+ try:
+ number: float = int(value) if name in ints else float(value)
+ except ValueError:
+ return
+ if name in ints:
+ fits = XLSX_STYLE_INT_MIN <= number <= XLSX_STYLE_INT_MAX
+ else:
+ fits = abs(number) <= MAX_XLSX_STYLE_FLOAT
+ if not fits:
+ raise DecompressionBombError(
+ f"spreadsheet style {name} value is out of range"
+ )
+
+
+def _xlsx_text_fields(cls) -> frozenset[str]:
+ """Names of the fields of openpyxl style class *cls* that
+ ``Serialisable.from_tree`` also reads from a child element of that
+ local name (its text), overriding the attribute: every descriptor
+ that is neither a converter itself nor typed by a class with its
+ own ``from_tree``. Derived from openpyxl so an upgrade that adds a
+ field is covered; ``CellStyle`` gives ``numFmtId``, ``fontId``,
+ ``fillId``, ``borderId``, ``xfId``, ``quotePrefix``,
+ ``pivotButton`` and the ``apply*`` flags (its ``alignment``,
+ ``protection`` and ``extLst`` children, which Excel writes, are
+ complex types), ``_NamedCellStyle`` ``name``, ``xfId``,
+ ``builtinId``, ``iLevel``, ``hidden`` and ``customBuiltin`` (its
+ ``extLst`` is complex)."""
+ from openpyxl.descriptors import Descriptor
+
+ fields = set()
+ for name in dir(cls):
+ desc = getattr(cls, name, None)
+ if (
+ isinstance(desc, Descriptor)
+ and not hasattr(desc, "from_tree")
+ and hasattr(desc, "expected_type")
+ and not hasattr(desc.expected_type, "from_tree")
+ ):
+ fields.add(name)
+ return frozenset(fields)
+
+
+def _check_xlsx_styles(archive: zipfile.ZipFile) -> None:
+ """Refuse a workbook whose ``xl/styles.xml`` (the fixed name
+ openpyxl reads it by) declares a DTD, has a number format code over
+ ``MAX_XLSX_NUMBER_FORMAT_CHARS``, more than ``MAX_XLSX_CELL_FORMATS``
+ entries in a cell-format list, a gradient fill of more than
+ ``MAX_XLSX_GRADIENT_STOPS`` stops, a field the guard reads given as
+ a child element, more than ``MAX_XLSX_STYLE_LIST_ENTRIES`` fonts,
+ fills or borders, a numeric field out of the range
+ ``_check_xlsx_style_number`` allows, more than
+ ``MAX_XLSX_STYLE_HASH_CHAIN`` distinct style objects of one hash in
+ any indexed list openpyxl builds from it, a comment or processing
+ instruction below the root's children (``_refuse_xlsx_nested_node``)
+ or more than ``MAX_XML_OUTSIDE_ROOT_NODES`` outside the root, more
+ than ``MAX_XLSX_TOP_LEVEL_ELEMENTS`` elements under the root, more
+ entries in its lists (``_XLSX_STYLE_LISTS``, ``_XLSX_COLOR_LISTS``,
+ a table style's elements and every ``extLst``'s extensions, every
+ child element counting) than ``_xlsx_list_cap`` allows, more than
+ ``MAX_XLSX_DIFFERENTIAL_FORMAT_ELEMENTS`` elements under ``dxfs``,
+ more than ``MAX_XLSX_GRADIENT_STOPS_TOTAL`` gradient stops in all,
+ an element that is not a list repeating a child's local name
+ (``_refuse_xlsx_repeated_child``; the content of an extension, which
+ openpyxl does not read, excepted), a font, fill, border or
+ cell-format entry of more than ``MAX_XLSX_STYLE_ENTRY_ELEMENTS``
+ elements, or would cost openpyxl's stylesheet load more than
+ ``MAX_XLSX_NUMBER_FORMAT_WORK`` or ``MAX_XLSX_NAMED_STYLE_WORK``.
+ Elements are classed as openpyxl reads them: an ``extLst`` is an
+ extension list only as the child of an element that is not a list
+ (as a list's entry it is that entry, and as a fill's first child a
+ gradient whose stops count), and only the ``ext`` children of an
+ extension list are extensions.
+
+ The part is read as openpyxl reads it: children are matched by
+ local name in any namespace (``Serialisable.from_tree``) under any
+ root, and numeric ids are read with ``int``. openpyxl keeps the last
+ of repeated lists; every one is counted here. ``from_tree`` also
+ reads a field from a child element of the field's name, whose text
+ replaces the attribute (``<numFmt numFmtId="164"><formatCode>``),
+ so any element child of a ``numFmt`` is refused, as is a child of a
+ cell-format ``xf`` or a ``cellStyle`` named after one of its
+ attribute fields (``_xlsx_text_fields``); Excel writes neither.
+ The part is streamed once, each element dropped once read (an entry
+ of the font, fill, border and cell-format lists once that entry has
+ been rebuilt with openpyxl's own ``from_tree``), so the guard holds
+ the path to the current element, the ``cellStyle`` ids, the cell
+ formats' format ids and the distinct style objects (which openpyxl
+ holds too). A non-integer id, which openpyxl cannot load, is refused
+ as malformed."""
+ from lxml import etree
+ from openpyxl.styles.alignment import Alignment
+ from openpyxl.styles.borders import Border
+ from openpyxl.styles.cell_style import CellStyle
+ from openpyxl.styles.fills import Fill
+ from openpyxl.styles.fonts import Font
+ from openpyxl.styles.named_styles import _NamedCellStyle
+ from openpyxl.styles.protection import Protection
+
+ try:
+ info = archive.getinfo(_XLSX_STYLES_PART)
+ except KeyError:
+ return
+ ints, floats, nested = _xlsx_numeric_fields()
+ numeric = ints | floats
+ entry_classes = {"fonts": Font, "fills": Fill, "borders": Border}
+ # openpyxl's indexed lists, seeded as it seeds them.
+ lists = {
+ "fonts": _XlsxIndexedList("fonts"),
+ "fills": _XlsxIndexedList("fills"),
+ "borders": _XlsxIndexedList("borders"),
+ }
+ alignments = _XlsxIndexedList("alignments", (Alignment(),))
+ protections = _XlsxIndexedList("protections", (Protection(),))
+ cell_styles = _XlsxIndexedList("cell formats")
+ strings = _XlsxIndexedList("format codes or style names")
+ modelled: dict[str, set[bytes]] = {
+ name: set() for name in _XLSX_MODELLED_LISTS
+ }
+ text_fields = {
+ ("cellXfs", "xf"): _xlsx_text_fields(CellStyle),
+ ("cellStyleXfs", "xf"): _xlsx_text_fields(CellStyle),
+ ("cellStyles", "cellStyle"): _xlsx_text_fields(_NamedCellStyle),
+ }
+ format_units: dict[int, int] = {}
+ cell_format_ids: list[int] = []
+ style_ids: set[int] = set()
+ counts = {"cellXfs": 0, "cellStyleXfs": 0, "cellStyles": 0}
+ entry_tags = {
+ "cellXfs": "xf",
+ "cellStyleXfs": "xf",
+ "cellStyles": "cellStyle",
+ }
+ bound_units = dict.fromkeys(_XLSX_BOUND_LISTS, 0)
+ number_formats = longest_code = depth = 0
+ entry_nodes = entry_chars = stops = outside = top = held = 0
+ all_stops = dxf_elements = 0
+ extensions = [0]
+ path: list[str] = []
+ # Per open element: ("root"), ("set", child names so far) for an
+ # element that is not a list, ("list", name, counter) for a list,
+ # ("gradient", child names but stops), or ("skip") inside an
+ # extension, whose content openpyxl does not read.
+ frames: list[tuple] = []
+ totals = {name: [0] for name in _XLSX_STYLE_LISTS + _XLSX_COLOR_LISTS}
+ with archive.open(info) as stream:
+ for event, element in etree.iterparse(
+ _CountedXmlStream(stream),
+ events=("start", "end", "comment", "pi"),
+ resolve_entities=False,
+ no_network=True,
+ ):
+ if event in ("comment", "pi"):
+ _refuse_xlsx_nested_node(depth, "styles")
+ if depth == 0:
+ outside = _note_outside_root_node(outside)
+ # Outside the root or directly under it, where openpyxl
+ # skips it: drop the siblings before it (it gets no end
+ # event; the next sibling's end drops it in turn).
+ parent = element.getparent()
+ if parent is not None:
+ while element.getprevious() is not None:
+ del parent[0]
+ continue
+ if event == "end":
+ tag = path[-1]
+ # from_tree reads such a child's text (before its own
+ # first child, if it has any) in place of the attribute.
+ if (
+ tag in numeric
+ and tag not in nested
+ and (element.text or "").strip()
+ ):
+ _check_xlsx_style_number(tag, element.text)
+ if depth == 3 and path[1] in _XLSX_MODELLED_LISTS:
+ # An entry spelled like one already rebuilt adds
+ # nothing new (bloated workbooks repeat entries).
+ spelling = hashlib.blake2b(
+ etree.tostring(element), digest_size=16
+ ).digest()
+ if spelling not in modelled[path[1]]:
+ modelled[path[1]].add(spelling)
+ _model_xlsx_style_entry(
+ element,
+ path[1],
+ entry_classes,
+ lists,
+ alignments,
+ protections,
+ cell_styles,
+ )
+ if depth >= 3 and path[1] in bound_units:
+ entry_nodes += 1
+ entry_chars += len(element.text or "") + sum(
+ len(value) for value in element.attrib.values()
+ )
+ if depth == 3:
+ units = (
+ entry_nodes * XLSX_STYLE_NODE_UNITS
+ + entry_chars // XLSX_STYLE_CHARS_PER_UNIT
+ )
+ if units > bound_units[path[1]]:
+ bound_units[path[1]] = units
+ entry_nodes = entry_chars = 0
+ depth -= 1
+ path.pop()
+ frames.pop()
+ if depth >= 3 and path[1] in _XLSX_MODELLED_LISTS:
+ continue # rebuilt with its entry, then dropped
+ element.clear()
+ parent = element.getparent()
+ if parent is not None:
+ while element.getprevious() is not None:
+ del parent[0]
+ continue
+ depth += 1
+ tag = etree.QName(element).localname
+ path.append(tag)
+ if depth == 1:
+ _refuse_dtd(element)
+ frames.append(("root",))
+ continue
+ frame = frames[-1]
+ kind = frame[0]
+ if depth >= 3 and path[1] in _XLSX_MODELLED_LISTS:
+ # Held whole until the entry ends, extension content
+ # included (see MAX_XLSX_STYLE_ENTRY_ELEMENTS).
+ held = 1 if depth == 3 else held + 1
+ if held > MAX_XLSX_STYLE_ENTRY_ELEMENTS:
+ raise DecompressionBombError(
+ f"spreadsheet style {path[2]} entry has more than "
+ f"{MAX_XLSX_STYLE_ENTRY_ELEMENTS} elements"
+ )
+ if kind == "skip":
+ frames.append(frame)
+ else:
+ if kind == "root":
+ top += 1
+ if top > MAX_XLSX_TOP_LEVEL_ELEMENTS:
+ raise DecompressionBombError(
+ "spreadsheet styles part has more than "
+ f"{MAX_XLSX_TOP_LEVEL_ELEMENTS} top-level elements"
+ )
+ elif kind == "list":
+ frame[2][0] += 1
+ _refuse_xlsx_list_entry("styles", frame[1], frame[2][0])
+ elif kind == "gradient" and tag == "stop":
+ stops += 1
+ all_stops += 1
+ if stops > MAX_XLSX_GRADIENT_STOPS:
+ raise DecompressionBombError(
+ "spreadsheet gradient fill has more than "
+ f"{MAX_XLSX_GRADIENT_STOPS} stops"
+ )
+ if all_stops > MAX_XLSX_GRADIENT_STOPS_TOTAL:
+ raise DecompressionBombError(
+ "spreadsheet gradient fills have more than "
+ f"{MAX_XLSX_GRADIENT_STOPS_TOTAL} stops together"
+ )
+ else:
+ _refuse_xlsx_repeated_child(
+ "styles", path[-2], frame[1], tag
+ )
+ if path[1] == "dxfs" and depth >= 3:
+ dxf_elements += 1
+ if dxf_elements > MAX_XLSX_DIFFERENTIAL_FORMAT_ELEMENTS:
+ raise DecompressionBombError(
+ "spreadsheet differential formats have more "
+ f"than {MAX_XLSX_DIFFERENTIAL_FORMAT_ELEMENTS} "
+ "elements"
+ )
+ # The kind of this element, as openpyxl reads it. It
+ # reads a fill's first child, whatever its tag, as a
+ # gradient unless that tag (namespace included) contains
+ # "patternFill"; every child of a list as an entry
+ # (``NestedSequence``, whatever its tag) or not at all
+ # (``Sequence``, another tag), never as an extension
+ # list; and an extension's content not at all.
+ if tag == "ext" and kind == "list" and frame[1] == "extLst":
+ frames.append(("skip",))
+ elif (
+ kind == "set"
+ and len(frame[1]) == 1
+ and (
+ (depth == 4 and path[1] == "fills")
+ or path[-2] == "fill"
+ )
+ and "patternFill" not in element.tag
+ ):
+ stops = 0
+ frames.append(("gradient", set()))
+ elif tag == "extLst" and kind != "list":
+ frames.append(("list", tag, extensions))
+ elif depth == 2 and tag in totals:
+ frames.append(("list", tag, totals[tag]))
+ elif depth == 3 and path[1] == "colors" and tag in totals:
+ frames.append(("list", tag, totals[tag]))
+ elif depth == 3 and path[1] == "tableStyles":
+ frames.append(("list", "tableStyle", [0]))
+ else:
+ frames.append(("set", set()))
+ for key, value in element.attrib.items():
+ _check_xlsx_style_number(key, value)
+ if tag in nested:
+ _check_xlsx_style_number(tag, element.get("val"))
+ if depth >= 3 and path[-2] == "numFmt":
+ raise DecompressionBombError(
+ "spreadsheet number format has a child element"
+ )
+ if depth == 4 and tag in text_fields.get((path[1], path[2]), ()):
+ raise DecompressionBombError(
+ f"spreadsheet style {path[2]} gives {tag} as a child "
+ "element"
+ )
+ if depth != 3:
+ continue
+ container = path[1]
+ if container == "numFmts" and tag == "numFmt":
+ number_formats += 1
+ code = element.get("formatCode") or ""
+ strings.add(code)
+ if len(code) > MAX_XLSX_NUMBER_FORMAT_CHARS:
+ raise DecompressionBombError(
+ "spreadsheet number format code is longer than "
+ f"{MAX_XLSX_NUMBER_FORMAT_CHARS} characters"
+ )
+ longest_code = max(longest_code, len(code))
+ format_id = int(element.get("numFmtId"))
+ units = _xlsx_format_units(code)
+ if units > format_units.get(format_id, 0):
+ format_units[format_id] = units
+ elif entry_tags.get(container) == tag:
+ counts[container] += 1
+ if container == "cellXfs":
+ cell_format_ids.append(int(element.get("numFmtId", 0)))
+ elif container == "cellStyles":
+ style_ids.add(int(element.get("xfId")))
+ strings.add(element.get("name"))
+ builtin = _XLSX_BUILTIN_FORMAT_CHARS * XLSX_NUMBER_FORMAT_SCAN_WEIGHT
+ work = sum(
+ format_units.get(format_id, builtin) for format_id in cell_format_ids
+ )
+ if work > MAX_XLSX_NUMBER_FORMAT_WORK:
+ raise DecompressionBombError(
+ f"spreadsheet number formats cost {work} units in openpyxl's "
+ f"stylesheet load (ceiling {MAX_XLSX_NUMBER_FORMAT_WORK})"
+ )
+ style_formats = counts["cellStyleXfs"]
+ named_styles = sum(
+ -style_formats <= style_id < style_formats for style_id in style_ids
+ )
+ per_style = (
+ XLSX_NAMED_STYLE_BASE_UNITS
+ + number_formats
+ + sum(bound_units.values())
+ + longest_code // XLSX_STYLE_CHARS_PER_UNIT
+ )
+ named = named_styles * per_style
+ if named > MAX_XLSX_NAMED_STYLE_WORK:
+ raise DecompressionBombError(
+ f"spreadsheet named styles cost {named} units in openpyxl's "
+ f"stylesheet load (ceiling {MAX_XLSX_NAMED_STYLE_WORK})"
+ )
+
+
+def _model_xlsx_style_entry(
+ element,
+ container: str,
+ entry_classes: dict,
+ lists: dict[str, _XlsxIndexedList],
+ alignments: _XlsxIndexedList,
+ protections: _XlsxIndexedList,
+ cell_styles: _XlsxIndexedList,
+) -> None:
+ """Rebuild one entry of a styles list as openpyxl's load does and add
+ it to the indexed lists it lands in: a font, fill or border entry
+ (any tag; ``NestedSequence.from_tree``) to its list
+ (``apply_stylesheet``); a cell format ``xf``'s alignment and
+ protection to theirs and its style array to the cell formats
+ (``CellStyleList._to_array``); a named style format's alignment and
+ protection to theirs (``NamedStyle.bind``, which adds an absent one
+ as the default already listed)."""
+ if container in entry_classes:
+ lists[container].add(entry_classes[container].from_tree(element))
+ return
+ from lxml import etree
+ from openpyxl.styles.cell_style import CellStyle
+
+ if etree.QName(element).localname != "xf":
+ return
+
+ xf = CellStyle.from_tree(element)
+ alignment = (
+ alignments.add(xf.alignment) if xf.alignment is not None else None
+ )
+ protection = (
+ protections.add(xf.protection) if xf.protection is not None else None
+ )
+ if container == "cellXfs":
+ style = xf.to_array()
+ if alignment is not None:
+ style.alignmentId = alignment
+ if protection is not None:
+ style.protectionId = protection
+ cell_styles.add(style)
+
+
+def _xlsx_format_units(code: str) -> int:
+ """Units of ``MAX_XLSX_NUMBER_FORMAT_WORK`` one date/timedelta test
+ of format *code* costs openpyxl."""
+ return max(len(code), 1) * (
+ XLSX_NUMBER_FORMAT_SCAN_WEIGHT + code.count("[")
+ )
+
+
+def _require_skeleton_size(
+ archive: zipfile.ZipFile,
+ name: str,
+ scanned: set[tuple[str, str]],
+ families: tuple[str, ...] = (_LXML,),
+ *,
+ workbook: bool = False,
+) -> None:
+ """Hold *name* to ``MAX_XLSX_SKELETON_PART_BYTES``, scan it with
+ *families* (``_check_xlsx_namespaces``, which records it in
+ *scanned*) and refuse it if
+ it declares a DTD (refused by the scan, in its bytes) or has a
+ comment or processing instruction below its root's children
+ (``_refuse_xlsx_nested_node``), found by one lxml parse of the part
+ before openpyxl parses it, walking only its comments and processing
+ instructions. The *workbook* part's lists and elements are then held
+ as ``_check_xlsx_workbook_tree`` holds them."""
+ from lxml import etree
+
+ try:
+ info = archive.getinfo(name)
+ except KeyError:
+ return # openpyxl reports the missing part itself
+ if info.file_size > MAX_XLSX_SKELETON_PART_BYTES:
+ raise DecompressionBombError(
+ "spreadsheet package part is larger than "
+ f"{MAX_XLSX_SKELETON_PART_BYTES} bytes"
+ )
+ _check_xlsx_namespaces(archive, {name: frozenset(families)}, scanned)
+ with archive.open(info) as stream:
+ for _event, element in etree.iterparse(
+ _CountedXmlStream(stream),
+ events=("start",),
+ resolve_entities=False,
+ no_network=True,
+ ):
+ _refuse_dtd(element)
+ break
+ root = etree.fromstring(
+ archive.read(info),
+ etree.XMLParser(resolve_entities=False, no_network=True),
+ )
+ for node in root.iter(etree.Comment, etree.ProcessingInstruction):
+ _refuse_xlsx_nested_node(
+ 1 if node.getparent() is root else 2, "workbook skeleton"
+ )
+ if workbook:
+ _check_xlsx_workbook_tree(root)
+ del root
+
+
+def _check_xlsx_workbook_tree(root) -> None:
+ """Refuse a workbook part (parsed, with no comment or processing
+ instruction below its root's children) whose root has more than
+ ``MAX_XLSX_TOP_LEVEL_ELEMENTS`` child elements, whose lists
+ (``_XLSX_WORKBOOK_LISTS``) hold more entries than ``_xlsx_list_cap``
+ allows, counted over every such list, or that has an extension list
+ of more than ``MAX_XLSX_EXTENSIONS`` entries, an element that is
+ not a list repeating a child's local name
+ (``_refuse_xlsx_repeated_child``) or defined names that
+ ``_check_xlsx_defined_names`` refuses.
+
+ This covers the elements openpyxl's ``WorkbookPackage.from_tree``
+ builds objects from: the root's children, the entries of its lists
+ and the children of those entries and of the root's other children
+ (an extension list's extensions, whose content it does not read).
+ Deeper elements it skips or reads as text, and it builds a defined
+ name from each ``definedName`` of a ``definedNames`` list, its
+ attributes, its text and its children's."""
+ from lxml import etree
+
+ totals = dict.fromkeys(_XLSX_WORKBOOK_LISTS + ("extLst",), 0)
+ top = 0
+ print_work = [0]
+
+ def entry(element) -> None:
+ if len(element) == 0:
+ return
+ seen: set = set()
+ parent = etree.QName(element).localname
+ for child in element:
+ tag = etree.QName(child).localname
+ _refuse_xlsx_repeated_child("workbook", parent, seen, tag)
+ if tag == "extLst":
+ totals[tag] += len(child)
+ _refuse_xlsx_list_entry("workbook", tag, totals[tag])
+
+ for child in root.iterchildren(etree.Element):
+ top += 1
+ if top > MAX_XLSX_TOP_LEVEL_ELEMENTS:
+ raise DecompressionBombError(
+ "spreadsheet workbook part has more than "
+ f"{MAX_XLSX_TOP_LEVEL_ELEMENTS} top-level elements"
+ )
+ tag = etree.QName(child).localname
+ if tag in totals:
+ totals[tag] += len(child)
+ _refuse_xlsx_list_entry("workbook", tag, totals[tag])
+ if tag != "extLst": # openpyxl does not read inside an <ext>
+ for item in child:
+ entry(item)
+ elif tag == "definedNames":
+ _check_xlsx_defined_names(child, print_work)
+ else:
+ entry(child)
+
+
+def _check_xlsx_defined_names(names, print_work: list[int]) -> None:
+ """Refuse a ``definedNames`` list of the workbook part with a defined
+ name whose value is longer than ``MAX_XLSX_DEFINED_NAME_CHARS``, or
+ that brings the print names' work (*print_work*, counted over every
+ such list of the part) over ``MAX_XLSX_PRINT_NAME_WORK``.
+
+ openpyxl's ``Serialisable.from_tree`` reads a defined name's value
+ (``attr_text``) from an ``attr_text`` or ``attr-text`` attribute
+ (it turns ``-`` in an attribute name into ``_``), replaced by the
+ element's text when there is any, and its other fields from
+ attributes or from child elements of their names, so every entry is
+ read here, whatever its tag, at the longest of its attribute values,
+ its text and its children's. A name that starts like
+ ``_xlnm.Print_Titles`` or ``_xlnm.Print_Area`` (openpyxl matches
+ the reserved names as a prefix) is counted at that length squared
+ plus ``XLSX_PRINT_NAME_BASE_UNITS``, whatever its sheet."""
+ from lxml import etree
+
+ for item in names.iterchildren(etree.Element):
+ value = max(
+ len(text or "")
+ for text in (
+ item.text,
+ *(c.text for c in item),
+ *item.attrib.values(),
+ )
+ )
+ if value > MAX_XLSX_DEFINED_NAME_CHARS:
+ raise DecompressionBombError(
+ "spreadsheet defined name is longer than "
+ f"{MAX_XLSX_DEFINED_NAME_CHARS} characters"
+ )
+ spellings = [item.get("name")] + [
+ c.text for c in item if etree.QName(c).localname == "name"
+ ]
+ if any(
+ (spelling or "").startswith(_XLSX_PRINT_NAMES)
+ for spelling in spellings
+ ):
+ print_work[0] += value * value + XLSX_PRINT_NAME_BASE_UNITS
+ if print_work[0] > MAX_XLSX_PRINT_NAME_WORK:
+ raise DecompressionBombError(
+ "spreadsheet print areas and titles cost "
+ f"{print_work[0]} units in openpyxl's load (ceiling "
+ f"{MAX_XLSX_PRINT_NAME_WORK})"
+ )
+
+
+def _refuse_dtd(element) -> None:
+ """Refuse the part *element* belongs to if it has a document type
+ declaration, internal subset or not.
+
+ A DTD is the only way to declare an entity. lxml with
+ ``resolve_entities=False`` keeps each reference to a declared
+ entity as an ``_Entity`` node, and with an external subset it does
+ the same for undeclared ones (the subset is not loaded, so they
+ are not errors); ``iterparse`` emits no event for either, so the
+ guard's streaming counts would miss them. OPC (ECMA-376 Part 2)
+ forbids DTDs in the parts it defines and Office writes none in the
+ XML parts it generates.
+ Every part the guard parses is first read through
+ ``_CountedXmlStream``, whose ``_XmlProlog`` refuses the declaration
+ in the bytes, before a parser reads it; this is a second line. It looks at the root's start event, by which libxml2 has
+ read the whole internal subset (one million attribute declarations,
+ a 17.9 MB part, held 424 MB first)."""
+ docinfo = element.getroottree().docinfo
+ if (
+ docinfo.doctype
+ or docinfo.internalDTD is not None
+ or docinfo.externalDTD is not None
+ ):
+ raise DecompressionBombError("document package part declares a DTD")
+
+
+#: Ceiling on the comments and processing instructions outside the root
+#: element (before or after it) of a part the guard streams with
+#: comment events and does not otherwise count them in: the ``.xlsx``
+#: styles part, ``.pptx`` slides, layouts and masters, and ``.docx``
+#: ``document.xml``, headers and footers. lxml's ``iterparse``
+#: emits the event for one before the root in time linear in the nodes
+#: already there, so N of them cost the guard N squared: 60,000 empty
+#: comments before a slide's root, a 420 KB part, kept the guard busy
+#: for 16.7 s (40,000, 5.6 s; after the root they cost nothing extra).
+#: Office writers put none there.
+MAX_XML_OUTSIDE_ROOT_NODES = 64
+
+
+def _note_outside_root_node(count: int) -> int:
+ """Count one more comment or processing instruction outside a
+ part's root element, refusing the part past
+ ``MAX_XML_OUTSIDE_ROOT_NODES``; returns the new count."""
+ count += 1
+ if count > MAX_XML_OUTSIDE_ROOT_NODES:
+ raise DecompressionBombError(
+ "document package part has more than "
+ f"{MAX_XML_OUTSIDE_ROOT_NODES} comments or processing "
+ "instructions outside its root element"
+ )
+ return count
+
+
+# --- Reference fan-out in .pptx / .docx -----------------------------------
+#
+# python-pptx and python-docx load each package part once, but the text
+# extractors walk *references*: unstructured's ``partition_pptx`` emits a
+# slide once per ``<p:sldId>`` that resolves to it, and ``partition_docx``
+# emits a header/footer part once per section that references it, after
+# python-docx has located each section's content with XPath over the
+# body-level elements and over every body-level paragraph's children
+# (so N sections cost N passes over the body; see
+# ``MAX_DOCX_SECTION_BLOCK_WORK`` and ``MAX_DOCX_SECTION_WORK``). One
+# bounded part referenced N times is therefore N times the work and the
+# extracted text, which no per-entry ceiling bounds. The same holds per
+# paragraph: unstructured looks up each non-empty paragraph's style
+# about four times (each a scan of the styles part and of the document
+# part's relationships), reads each run's text about five times, and
+# splits a paragraph at each rendered page break. python-docx's and
+# unstructured's cost is not modelled exactly: the section count and
+# the parts read per section or per paragraph are capped
+# (``MAX_DOCX_SECTIONS``, ``MAX_PART_RELATIONSHIPS``,
+# ``MAX_DOCX_SETTINGS_CHILDREN``, ``MAX_DOCX_STYLES``), and the work
+# that grows with the body is counted as products of those counts,
+# each priced at the slowest layout measured. The checks below parse in
+# full only package skeleton parts (relationships, ``presentation.xml``,
+# the ``.docx`` settings and styles parts), each held to
+# ``MAX_OPC_SKELETON_PART_BYTES``; ``document.xml`` is not a skeleton
+# part: it is streamed once without building a tree, and is bounded
+# only by the parsed-part ceiling (``MAX_ENTRY_BYTES``, 128 MiB).
+
+#: Ceiling for the skeleton parts the .pptx/.docx fan-out checks parse
+#: in full (package and part relationships, ``presentation.xml``, the
+#: ``.docx`` settings and styles parts). Real ones are kilobytes (a
+#: styles part with hundreds of styles is a few hundred KB); 10,000
+#: slides list in well under 1 MiB.
+MAX_OPC_SKELETON_PART_BYTES = 16 * 1024 * 1024
+
+#: Ceiling on the entries (children of the root element) of every
+#: relationships part (``*.rels`` member) of a ``.docx`` or ``.pptx``
+#: package, the parts the guard reads (the package's, the main
+#: document's and the presentation's) and the others alike: the
+#: libraries parse the relationships part of every part they reach
+#: (see ``MAX_PACKAGE_RELATIONSHIPS``). python-docx finds the settings
+#: and styles parts by scanning every relationship of the document part
+#: in Python (uncached): unstructured does that twice per section for
+#: the settings part, which this cap keeps small (10,000 relationships
+#: under ``MAX_DOCX_SECTIONS`` sections measured about 3 s), and about
+#: four times per non-empty paragraph for the styles part, which
+#: ``MAX_DOCX_STYLE_WORK`` counts. Real documents have tens to a few
+#: hundred relationships (one per image, hyperlink and header/footer
+#: part, plus about a dozen fixed parts), so a document with thousands
+#: of images or external hyperlinks still fits.
+MAX_PART_RELATIONSHIPS = 10_000
+
+#: Ceiling on the attributes of any element of a relationships part.
+#: The OPC schema (ECMA-376 Part 2) gives ``Relationship`` four
+#: (``Id``, ``Type``, ``Target``, ``TargetMode``) and ``Relationships``
+#: none; namespace declarations are not attributes. Checked at each
+#: element's start, so a part whose first entry carries hundreds of
+#: thousands of attributes is refused after that entry rather than
+#: read to its end.
+MAX_RELS_ELEMENT_ATTRIBUTES = 64
+
+#: Ceiling on the relationships of all the relationships parts of a
+#: ``.docx`` or ``.pptx`` package together. python-docx and python-pptx
+#: load every part reachable through relationships and parse each
+#: one's relationships part, about 5-8 us per relationship (a million,
+#: in 100 parts of 10,000 external hyperlinks each, a 5.9 MB file, took
+#: 5.2 s to open in python-docx and 8.1 s in python-pptx), so 50,000
+#: cost well under a second. Real documents have tens to hundreds; one
+#: with 10,000 images and as many hyperlinks has about 20,000.
+MAX_PACKAGE_RELATIONSHIPS = 50_000
+
+#: Ceiling on python-docx's relationship walks when it opens a package:
+#: its ``PackageReader._walk_phys_parts`` keeps the parts it has visited
+#: in a list and, for every internal relationship of every part it
+#: reaches, scans that list (``partname in visited_partnames``), and
+#: ``OpcPackage.iter_rels`` (run on load to gather the image parts)
+#: does the same with its own list. The guard counts the internal
+#: relationships (``TargetMode`` other than ``External``) of every
+#: relationships part times the archive's members (an upper bound on
+#: the parts visited: each must exist), each member counted as one step
+#: plus one per ``DOCX_RELATIONSHIP_WALK_NAME_BYTES_PER_STEP`` bytes of
+#: its name as CPython stores it (comparing names of equal length reads
+#: them: one, two or four bytes per character, by the name's widest
+#: code point; ``_str_width``). A step measured 17-25 ns: 9,000 parts
+#: and one part with 200,000 relationships to the last of them, a
+#: 1.66 MB file with every relationships part the guard read under
+#: ``MAX_PART_RELATIONSHIPS``, took 41 s to open before the change, and
+#: 2,000 parts with 20,000, 1.0 s; 9,000 parts with 19,000 internal
+#: relationships, counted at 0.91 of this ceiling, open in 3.0 s. Names
+#: of four-byte characters cost two to four times as much per character
+#: as ASCII ones and were counted per character before: 2,400 parts
+#: named by 450 emoji and 10,114 internal relationships open in 2.1 s
+#: and are counted at 1.01 of this ceiling (0.34 per character), and
+#: 2,000 parts named by 2,000 emoji and 10,014 relationships, counted
+#: at 3.3 (0.89 per character), in 9.5 s, so opening at the ceiling
+#: costs about 2-5 s whatever the names. A document with 10,000 images
+#: (one part and one relationship each) counts about 110 million.
+MAX_DOCX_RELATIONSHIP_WALK = 200_000_000
+DOCX_RELATIONSHIP_WALK_NAME_BYTES_PER_STEP = 256
+
+#: Ceiling on the ``w:sectPr`` elements anywhere in ``document.xml``
+#: (python-docx enumerates those in body-level paragraph properties and
+#: at body level as sections; any other is counted too). python-docx and
+#: unstructured do work once per section that this guard does not model
+#: exactly: each section re-evaluates the ``_sectPrs`` XPath (whose
+#: union merge compares the two kinds of ``w:sectPr`` pairwise and whose
+#: returned nodes cost about 100 ns each), and unstructured reads the
+#: settings part's ``evenAndOddHeaders`` twice (a scan of the document
+#: part's relationships and a search of the settings root's children).
+#: This cap, with ``MAX_PART_RELATIONSHIPS`` and
+#: ``MAX_DOCX_SETTINGS_CHILDREN``, bounds each of those factors instead:
+#: 1,000 sections packed into one paragraph's properties, or split
+#: between paragraph and body level, partition in under 2 s. Word writes
+#: one ``w:sectPr`` per section break plus the body's own; real
+#: documents rarely have more than a few hundred (a mail merge to
+#: "individual documents" writes one per record). Each section's
+#: paragraphs also count toward ``MAX_DOCX_SECTION_BLOCK_WORK`` and the
+#: shared budget: measured on documents python-docx writes (where each
+#: section break is a paragraph of its own), more than about 580
+#: one-paragraph sections, or about 180 ten-paragraph ones, are
+#: refused.
+MAX_DOCX_SECTIONS = 1_000
+
+#: Ceiling on the children of the settings part's root element. The
+#: part is the one the document part's settings relationship names, as
+#: python-docx resolves it, and unstructured searches its root's
+#: children twice per section. Word's settings.xml has well under 200.
+MAX_DOCX_SETTINGS_CHILDREN = 5_000
+
+#: Ceiling on the quadratic part of python-docx's per-section content
+#: lookup: the sum, over sections, of the body-level paragraphs and
+#: tables (``w:p``/``w:tbl``) from the start of the body to the
+#: section's end, times the child nodes of the body (elements, comments,
+#: processing instructions and text). python-docx 1.2 finds a section's
+#: blocks with ``preceding-sibling::*[self::w:p | self::w:tbl]`` from the
+#: section's end, which returns that section's blocks and every earlier
+#: one, and libxml2 (2.14 measured) sorts that reverse-axis result into
+#: document order with comparisons that each walk sibling links towards
+#: the end of the body. One evaluation therefore costs up to (blocks
+#: returned) x (body nodes) steps; it runs once per section. A step
+#: costs about 5 ns while the body fits in the CPU caches, but a large
+#: body is walked from memory, and the cost then grows with what each
+#: node occupies: measured end to end in ``partition_docx`` behind 1,240
+#: paragraphs, about 16 ns per step for bare elements, ~48 ns with three
+#: attributes, ~70-100 ns with 8-40 attributes or twenty child elements,
+#: and ~80 ns per counted step for three-attribute elements separated by
+#: text. The ceiling prices every step at that slowest layout, ~100 ns,
+#: so this fan-out at the ceiling measured about 45 s (1,240 paragraphs
+#: before 348,000 twenty-attribute bookmarks, at 96% of it: 40 s; before
+#: the change, 1,240 paragraphs and 2,000,000 three-attribute bookmarks,
+#: a 234 KiB file, were accepted and took 121 s). Bodies of plain
+#: paragraphs that python-docx would walk at a few ns per step are
+#: priced the same. On its own the ceiling would admit a single section
+#: of about 21,000 paragraphs and tables; with the shared budget (the
+#: style lookup costs about as much per paragraph) the measured limits
+#: are about half that (see "Known gaps" in the module docstring).
+#: Text between body-level elements is counted whether or not it is
+#: whitespace (python-docx's parser drops most whitespace-only text, but
+#: not all), so a pretty-printed ``document.xml`` counts up to twice its
+#: nodes.
+MAX_DOCX_SECTION_BLOCK_WORK = 450_000_000
+
+#: Ceiling on the linear part of python-docx's per-section work, in
+#: units of one body node per section: the section count times (the
+#: body's child nodes, which each section's sibling walk and
+#: ``count()`` visit, plus the nodes the ``_sectPrs`` XPath visits
+#: divided by ``DOCX_SECTION_XPATH_NODES_PER_UNIT``, plus the node pairs
+#: its union compares divided by ``DOCX_SECTION_UNION_PAIRS_PER_UNIT``).
+#: The ``_sectPrs`` XPath is
+#: ``/w:document/w:body/w:p/w:pPr/w:sectPr | /w:document/w:body/w:sectPr``;
+#: its child steps visit every child node (elements, comments,
+#: processing instructions, text) of the document node, of
+#: ``w:document``, of each ``w:body``, of each body-level ``w:p`` and of
+#: each such paragraph's ``w:pPr``, at 12-33 ns per visit, and libxml2
+#: merges its two branches by comparing every paragraph-level
+#: ``w:sectPr`` with every body-level one (1-4 ns per pair). The weights
+#: are generous rather than exact: at this ceiling 1,000 body-level
+#: sections over ~9,700 body nodes took 1-2 s in ``partition_docx``.
+MAX_DOCX_SECTION_WORK = 10_000_000
+
+#: Section-XPath node visits that count as one unit of
+#: ``MAX_DOCX_SECTION_WORK`` (one body-level element per section).
+DOCX_SECTION_XPATH_NODES_PER_UNIT = 64
+
+#: Node pairs compared by the section XPath's union (per evaluation)
+#: that count as one unit of ``MAX_DOCX_SECTION_WORK``.
+DOCX_SECTION_UNION_PAIRS_PER_UNIT = 1_000
+
+#: Ceiling on header/footer bytes as extracted: each section's
+#: header/footer reference costs one text read of the referenced part,
+#: so the referenced part's size is counted once per reference. A read
+#: costs up to about 3.5 us per byte (empty runs, empty paragraphs or
+#: empty table cells: 20 references to a 1.2 MB header of empty runs
+#: took ~73 s), so the sum is held to 12 MiB, about 45 s (39-40 s
+#: measured for this fan-out at the ceiling). Real documents reference kilobyte-sized
+#: headers from a handful of sections; a mail merge of 1,000 records
+#: whose header and footer total 12 KB would be refused. Each read also
+#: evaluates the part's node-set unions, which are not linear in its
+#: size (see ``DOCX_UNION_STEPS_PER_HEADER_BYTE``): a header holding a
+#: table before 8,000 empty paragraphs and 40,000 empty elements,
+#: referenced by ten sections, a 37 KB file, took 35 s and was counted
+#: at 0.23 of this ceiling before.
+MAX_DOCX_HEADER_FOOTER_BYTES = 12 * 1024 * 1024
+
+#: Ceiling on the children of the styles part's root element (the part
+#: the document part's styles relationship names, as python-docx
+#: resolves it). Word writes the styles a document uses plus its
+#: defaults, typically tens to a few hundred ``w:style`` elements;
+#: python-docx's own template has 164.
+MAX_DOCX_STYLES = 5_000
+
+#: Ceiling on unstructured's style lookups: the paragraphs that can have
+#: text (body-level ``w:p`` with a ``w:r`` or ``w:hyperlink`` child, plus
+#: one per ``w:lastRenderedPageBreak`` in them, since each page break
+#: splits off a fragment that is looked up again) times (the styles
+#: root's children, plus their attributes divided by
+#: ``DOCX_STYLE_ATTRIBUTES_PER_ENTRY``, plus the document part's
+#: relationships divided by ``DOCX_RELATIONSHIPS_PER_STYLE_ENTRY``).
+#: unstructured reads ``paragraph.style`` about four times per such
+#: paragraph; each read scans every relationship of the document part in
+#: Python (``part_related_by``) and, for a paragraph whose style is
+#: unset or does not resolve, loops over every ``w:style`` in Python
+#: (``default_for``), reading two attributes of each. Measured at about
+#: 15 us per unit (50 paragraphs beside 300,000 styles, an 805 KB file,
+#: took 132 s before the change), so this fan-out at the ceiling is
+#: about 45 s: 597 paragraphs beside 5,000 styles took 40 s, and 5,664
+#: paragraphs beside 10,000 relationships, at 90% of it, 24 s. On its
+#: own it would admit about 18,000 non-empty paragraphs under
+#: python-docx's template (166 entries), fewer with more styles; with
+#: the shared budget the measured limits are lower (see "Known gaps").
+MAX_DOCX_STYLE_WORK = 3_000_000
+
+#: Document-part relationships that count as one styles-part entry in
+#: ``MAX_DOCX_STYLE_WORK`` (a relationship costs about 0.1 us per read,
+#: a style about 3.5 us).
+DOCX_RELATIONSHIPS_PER_STYLE_ENTRY = 32
+
+#: Attributes of the styles root's children that count as one entry in
+#: ``MAX_DOCX_STYLE_WORK``: libxml2 finds an attribute by scanning the
+#: element's attributes, so styles of 50 or 250 attributes cost 1.4 or
+#: 3.1 times as much per read as plain ones.
+DOCX_STYLE_ATTRIBUTES_PER_ENTRY = 32
+
+#: Ceiling on the sibling sorting of unstructured's page-break splits:
+#: the sum over body-level paragraphs of K * (K + 3) * S**2, K being the
+#: paragraph's ``w:lastRenderedPageBreak`` elements and S the largest
+#: child-node count of the paragraph or of any element in it.
+#: unstructured splits a paragraph at its first rendered page break and
+#: recurses into the rest; each split evaluates python-docx XPath with
+#: reverse sibling axes (``precedes_all_content`` once per break left in
+#: the first run, and the fragment builders), each sorted at up to S**2
+#: steps. Measured at up to ~5 ns per unit (one break after 55,000
+#: elements of one run took 34-61 s; one run with 600 breaks, a 37 KB
+#: file, ran for over 180 s before the change), so this fan-out at the
+#: ceiling is about 45 s. Word writes about one rendered page break per
+#: page, in paragraphs of tens to hundreds of runs.
+MAX_DOCX_PAGE_BREAK_WORK = 9_000_000_000
+
+#: Ceiling on the ``w:lastRenderedPageBreak`` elements anywhere in
+#: ``document.xml``. unstructured asks once per document whether it has
+#: any, with a four-branch union over the whole body
+#: (``w:body/w:p/w:r``, ``w:body/w:p/w:hyperlink/w:r`` and the same two
+#: under ``w:body/w:tbl/w:tr/w:tc``), and libxml2 merges each branch by
+#: comparing every node with every node already merged, then sorts the
+#: result with comparisons that walk the siblings after the breaks:
+#: 20,000 breaks in one table cell after 20,000 in body paragraphs took
+#: 0.8 s, quadrupling per doubling, and 10,000 breaks in each of the two
+#: cell branches with 800-1,200 empty elements between consecutive ones
+#: 2.3-2.5 s (~25 ns per pair), while a break in a cell costs the other
+#: ceilings about one unit of ``MAX_DOCX_RUN_WORK``. Word writes one
+#: rendered page break per page in each flow of text the page boundary
+#: cuts (the body, and each cell of a table row the boundary crosses),
+#: so a 1,000-page document of ten-column tables has about 10,000 and a
+#: book of 20,000 pages this many. This ceiling bounds the merges, not
+#: the sort: once a later branch's break precedes an earlier branch's,
+#: the sort walks the shared parent's children after the breaks, so
+#: filler there costs per break (1,000 breaks of each hyperlink and
+#: plain branch in table rows before 160,000 empty table children, a
+#: 42 KB file, took 2.2-2.6 s per evaluation, 640,000 of them 10.5 s,
+#: and 10,000 rows of each branch alternating with empty spacer rows
+#: 3.8-7.6 s). The merges' pairs and the sort's steps are both priced
+#: in ``MAX_DOCX_RUN_WORK`` (``DOCX_PAGE_BREAK_UNION_PAIRS_PER_UNIT``,
+#: ``DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT``): those three shapes were
+#: counted at 0.02, 0.02 and 0.36 of it before, and are now counted at
+#: 1.24, 4.85 and 3.06 of it and refused; the sort's price covers
+#: siblings that lie far apart in memory and libxml2's binary-insertion
+#: runs, which plain filler and 1,000 breaks per branch do not reach,
+#: so the union at that ceiling costs about 30 s. Before the change, 96,000
+#: breaks in each of the two cell branches, about 0.9 of
+#: ``MAX_DOCX_RUN_WORK``, were accepted and would take ~18 s
+#: (extrapolated: a 45 KB file with 20,000 in each took 0.77 s and was
+#: counted at 0.19 of it). ``w:br w:type="page"`` is
+#: not part of this union (it is one of a run's text branches, see
+#: ``DOCX_UNION_STEPS_PER_RUN_WORK_UNIT``) and is not counted here.
+MAX_DOCX_PAGE_BREAKS = 20_000
+
+#: Node pairs compared by that union's merges (the sum, over pairs of
+#: branches, of the product of their break counts) that count as one
+#: unit of ``MAX_DOCX_RUN_WORK``: 2-3 ns per pair for the merges and up
+#: to ~25 ns with the sort measured, priced at 30 ns.
+DOCX_PAGE_BREAK_UNION_PAIRS_PER_UNIT = 1_000
+
+#: Steps of that union's sort that count as one unit of
+#: ``MAX_DOCX_RUN_WORK``, a step priced at 150 ns. With two or more
+#: non-empty branches, the merged set is out of document order as soon
+#: as a later branch's break precedes an earlier branch's, and libxml2
+#: then compares breaks under a common ancestor by walking that
+#: ancestor's children from one towards the other, to the end of them
+#: when the order is reversed. The guard counts, for every element, the
+#: union's breaks below it, B, times its child nodes (text included),
+#: weighted by ``B + DOCX_PAGE_BREAK_SORT_INSERTION_WALKS *
+#: min(B, DOCX_PAGE_BREAK_SORT_INSERTION_RUN)``, summed, and only when
+#: at least two branches are non-empty (one branch is already in
+#: document order). The weight covers libxml2's timsort: below 64 nodes,
+#: and for each run of the merged set shorter than its minimum run
+#: (32-64 nodes; the merged set is at most four ascending runs, one per
+#: branch), it sorts by binary insertion, about log2(n) comparisons, so
+#: up to six walks, per node: 62 breaks of one branch before one of
+#: another walked the filler after them 12 times per break, against
+#: about 2.5 times for 2,000 breaks. Each walk step is a dependent load
+#: of the next sibling, so its cost is set by how far apart siblings
+#: lie in memory, not by what they are: 3-9 ns for siblings allocated
+#: back to back, and 35-45 ns, a cache miss each, once each carries 16
+#: or more attributes, a few descendants or text (64 and 256 attributes
+#: cost no more). Measured per weighted step, the worst shapes found
+#: (62 breaks of one branch and one of another, or 31 of each of four
+#: branches, before 150,000-200,000 filler elements with 16-64
+#: attributes each; 1,000 breaks of one branch and one of another before
+#: 100,000 filler elements with 64 attributes) cost 70-95 ns, so the
+#: sort at the ceiling costs about 30 s. Priced at 30 ns per unweighted
+#: step before, 1,000 breaks of each of two branches in table rows
+#: before 600,000 filler elements with 16 empty attributes each, a
+#: 386 KB file, were accepted at 0.83 of ``MAX_DOCX_RUN_WORK`` and took
+#: 50 s for one evaluation of the union.
+DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT = 200
+
+#: Extra walks per break of the binary-insertion runs of that union's
+#: sort, and the breaks they apply to (see
+#: ``DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT``).
+DOCX_PAGE_BREAK_SORT_INSERTION_WALKS = 4
+DOCX_PAGE_BREAK_SORT_INSERTION_RUN = 64
+
+#: Ceiling on unstructured's text extraction from body-level paragraphs
+#: and tables: the sum over them of (K + 1) * (``DOCX_RUN_WORK_ITEM_WEIGHT``
+#: * (``w:r``, ``w:tr`` and ``w:tc`` elements) + child nodes of the
+#: ``w:r`` elements) + K * (descendant nodes) //
+#: ``DOCX_FRAGMENT_NODES_PER_RUN_WORK_UNIT``, K being a paragraph's
+#: rendered page breaks (0 for a table). unstructured reads each
+#: fragment's text about five times, and each read of a run is an XPath
+#: evaluation (~25 us) plus a Python loop over the run's children;
+#: tables cost about as much per row and cell (cells counted as
+#: ``_DocxSectionStats.run_work`` describes, with python-docx's steps up
+#: vertical merges priced by ``DOCX_MERGE_STEP_WEIGHT``); and each
+#: page-break split deep-copies the paragraph. Measured at up to ~30 us
+#: per unit (1.8 million tabs in one run; 120 paragraphs of 2,479 one-character
+#: runs, a 76 KB file, took 40 s, and the cost was bounded only by the
+#: 128 MiB part ceiling before the change), so this fan-out at the
+#: ceiling is about 45 s. On its own it would admit about 50,000
+#: paragraphs of five runs; with the shared budget, far fewer (see
+#: "Known gaps").
+MAX_DOCX_RUN_WORK = 1_500_000
+
+#: Units of ``MAX_DOCX_RUN_WORK`` per run, table row or table cell.
+DOCX_RUN_WORK_ITEM_WEIGHT = 5
+
+#: Descendant nodes of a split paragraph that count as one unit of
+#: ``MAX_DOCX_RUN_WORK`` per page break (the deep copy and the walks of
+#: each fragment: ~650 ns per node and break measured).
+DOCX_FRAGMENT_NODES_PER_RUN_WORK_UNIT = 32
+
+#: Ceiling on every ``w:gridSpan``, ``w:gridBefore`` and ``w:gridAfter``
+#: value in ``document.xml``. python-docx's ``_Row.cells`` yields a cell
+#: once per grid column it spans, and unstructured re-reads the cell's
+#: text for each yield (and pads a row with one empty string per
+#: ``gridBefore``/``gridAfter`` column), so the value is a multiplier
+#: on a cell's work and on the text it retains: a 950-byte file with
+#: one cell spanning 400,000 columns took 53 s, and at 2**31 - 1
+#: python-docx would build a tuple of about 17 GB. Word's tables are
+#: at most 63 columns wide, and the values of any writer are bounded
+#: by the table grid; 1,000 leaves 16 times Word's width. A value
+#: python-docx cannot read as an integer (``int()`` of the attribute,
+#: as python-docx converts it) is refused too, as is a missing one or
+#: one of more than ``_MAX_DOCX_GRID_VALUE_CHARS`` characters. Negative
+#: values are accepted (they span and pad nothing).
+MAX_DOCX_GRID_SPAN = 1_000
+
+#: Longest ``w:val`` of a grid element the guard parses.
+_MAX_DOCX_GRID_VALUE_CHARS = 32
+
+#: Most attributes any one element of ``document.xml`` may carry. lxml
+#: reads each attribute value by scanning the element's attribute list
+#: again (``attrib.values()``, ``items()``), so reading them all is
+#: quadratic in their number: 10,000 attributes took 0.35 s, 40,000
+#: 11 s, and one paragraph of 50,000 empty attributes, a 145 KB file,
+#: kept this guard itself busy for 40 s before. Real writers put at
+#: most a few dozen on an element (Word's ``w:p`` carries up to seven
+#: revision and paragraph ids, ``wp:anchor`` eleven; the most found in
+#: Word, LibreOffice and python-docx output was twelve, and VML shapes
+#: allow a few dozen), so 256 is refused outright, checked by counting
+#: (linear) before any attribute is read. lxml has built the element by
+#: then; one of more than ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` attributes is
+#: refused before lxml receives it (``_CountedXmlStream``).
+MAX_DOCX_ELEMENT_ATTRIBUTES = 256
+
+#: Most namespace declarations in scope at any element of
+#: ``document.xml`` (its own and its ancestors'). libxml2 resolves the
+#: namespace of every element and attribute it copies by walking the
+#: declarations in scope, so a paragraph whose elements use N
+#: declarations costs N squared per copy, and python-docx copies a
+#: paragraph twice per rendered page break: 8,000 declarations on the
+#: ``w:document`` element used by 8,000 elements took 0.6 s per copy,
+#: and the cost quadruples per doubling. Word declares about 35 on
+#: ``w:document`` and drawings add a few each; 256 is refused outright.
+MAX_DOCX_NAMESPACES_IN_SCOPE = 256
+
+#: Most namespace declarations inside one body-level paragraph of
+#: ``document.xml`` (on the ``w:p`` and on everything in it). lxml's
+#: ``remove()``, which python-docx calls on a copy of the paragraph for
+#: every rendered page break, re-homes the removed subtree's namespace
+#: declarations through a cache it searches linearly, so its cost grows
+#: with the square of the declarations in that subtree: 5,000 one-
+#: declaration elements took 0.007 s per removal, 40,000 0.4-0.8 s, and
+#: six page breaks before 40,000 of them, a 142 KB file, took 5 s to
+#: partition and were accepted before (at the copied-bytes ceiling a
+#: paragraph of 480,000 would cost minutes). At this cap a removal
+#: costs well under a millisecond (a paragraph at the cap with 140 page
+#: breaks partitioned in 1.7 s, against 1.65 s without the
+#: declarations). Word declares its namespaces on ``w:document`` and up
+#: to five more per inline picture (python-docx two), so 1,024 admits
+#: paragraphs of 200 pictures. Tables are not split, so they are not
+#: capped.
+MAX_DOCX_PARAGRAPH_NAMESPACES = 1_024
+
+#: Longest namespace URI, and longest prefix, a declaration in
+#: ``document.xml`` may have, in characters; checked when the
+#: declaration is announced, before any element name is read. lxml
+#: builds every element and attribute name it hands back as
+#: ``{URI}local``, so one long URI declared once and used through a
+#: short prefix is copied again for every name read under it: a single
+#: 8 MB URI used by 3,000 elements, a 44 KB file, ran this guard out of
+#: a 3 GB address space within 3 s (a 1 MB one took 3.5 s), and a 1 MB
+#: URI on 1,024 attribute names grew it by ~0.5 GB. With the cap, the
+#: guard reads each name a bounded number of times, so a name costs it
+#: at most about 1 KB per read (100,000 elements named through a URI
+#: at the cap took about a third longer than through Word's own). The
+#: namespaces Office writers use are well under 100
+#: characters (the longest in Word's output,
+#: ``http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing``,
+#: has 71), and their prefixes under ten.
+MAX_DOCX_NAMESPACE_URI_CHARS = 1_024
+MAX_DOCX_NAMESPACE_PREFIX_CHARS = 64
+
+#: Most ``w:tc`` children of one ``w:tr``, and most grid columns one row
+#: may cover (its ``gridBefore``, the spans of its cells and its
+#: ``gridAfter``). python-docx resolves a cell that continues a
+#: vertical merge (``row.cells``) by computing its grid offset, which
+#: reads the span of every earlier cell of its row, and then walking
+#: the row above to that offset, recursively up the merge; unstructured
+#: reads ``row.cells`` twice per table. Each such step therefore costs
+#: time proportional to the row's width, and a merged row costs its
+#: width squared: two rows of 1,000 cells, the second all continuing, a
+#: 37 KB file, took 6-7 s per read of the cells (4,000 cells, minutes).
+#: The steps are priced in ``MAX_DOCX_RUN_WORK`` (see
+#: ``DOCX_MERGE_STEP_WEIGHT``); this cap keeps each step's price, which
+#: the guard bounds linearly in the row's width, inside the range it was
+#: measured over (past a few hundred cells a step grows faster than
+#: linearly; a merged row of 256 cells: ~0.4 s per read, 0.84 s to
+#: partition). Word's tables are at most
+#: 63 columns wide, so 256 cells is four times that; 2,048 columns
+#: admits a row of a cell at the ``MAX_DOCX_GRID_SPAN`` cap with that
+#: much padding on both sides.
+MAX_DOCX_ROW_CELLS = 256
+MAX_DOCX_ROW_GRID_COLUMNS = 2_048
+
+#: Units of ``MAX_DOCX_RUN_WORK`` per step python-docx takes to resolve
+#: a cell continuing a vertical merge (``_tc_above``: two XPath
+#: evaluations and the grid offset computations, about 0.1 ms per read
+#: of ``row.cells`` for a one-column table), plus one per
+#: ``DOCX_MERGE_CELLS_PER_UNIT`` cells whose span it reads (the cells
+#: before the continuing cell in its row, and those before the cell it
+#: lands on in the row above, or all of them if there is none: 2-4 us
+#: each per read) and one per ``DOCX_MERGE_NODES_PER_UNIT`` nodes it
+#: walks: the child and descendant nodes of the row before the cell and
+#: of the row above (which those reads and the row above's cell list
+#: walk); the row's children up to its first ``w:trPr`` (all of them if
+#: it has none; capped by ``MAX_DOCX_ROW_OTHER_CHILDREN``) and the nodes
+#: in that ``w:trPr`` (``grid_before``'s ``find`` calls, wherever the
+#: ``w:trPr`` sits); and the table's children from the row above
+#: through the row (``_tr_above``; capped by
+#: ``MAX_DOCX_TABLE_ROW_GAP``). A cell whose merge goes up D rows takes D
+#: steps, each priced at its own rows, so one column merged down R rows
+#: costs R squared over two steps. The prices cover both of
+#: unstructured's reads: end to end in ``partition_docx``, merged
+#: tables of 1-256 columns and 2-500 rows (and rows with 256 other
+#: children and 256 more between each two, or cells whose ``w:tcPr``
+#: holds 2,000 children), at 0.84-0.96 of the ceiling, took 1-21 us per
+#: unit counted, under the ~30 us per unit the ceiling assumes; 64
+#: columns merged down 26 rows, at 0.96 of the ceiling, took 22 s.
+DOCX_MERGE_STEP_WEIGHT = 10
+DOCX_MERGE_CELLS_PER_UNIT = 2
+DOCX_MERGE_NODES_PER_UNIT = 16
+
+#: Most children of a table row python-docx reads (a direct ``w:tr``
+#: child of a ``w:tbl``) that are not ``w:tc`` elements, and most
+#: children of a ``w:tbl`` other than ``w:tr`` elements before or
+#: between two of its ``w:tr`` children (``w:tblPr`` and ``w:tblGrid``
+#: included); elements, comments and processing instructions count
+#: (the text between them is at most one node more each). Every step
+#: up a vertical merge reads ``grid_before`` of the continuing cell's
+#: row, an lxml ``find`` over all the row's children when it has no
+#: ``w:trPr``, and evaluates ``_tr_above``
+#: (``ancestor::w:tr[1]/preceding-sibling::w:tr[1]``), which visits
+#: every sibling between that row and the one above. The siblings are
+#: walked, not their content: a row padded with 200,000 empty elements
+#: after its cells, a 1.6 KB file, took 7.6 s per read of the cells,
+#: and 26 merged rows of 64 cells with 200,000 between each pair, an
+#: 81 KB file, 58 s per read (unstructured reads twice), at 0.09 and
+#: 0.90 of the ceiling before; 20,000 wrapped in one ``w:sdt`` per
+#: row cost nothing. In a table
+#: Word, LibreOffice and python-docx write, a row's other children are
+#: its ``w:trPr`` and ``w:tblPrEx`` and the children between rows are
+#: none (the ``w:tblPr`` and ``w:tblGrid`` before the first row); the
+#: schema also allows bookmark, comment, permission and revision range
+#: markers, ``w:proofErr``, and ``w:sdt``/``w:customXml`` wrappers
+#: there, one element per wrapped cell or group of rows. 256, the
+#: ``MAX_DOCX_ROW_CELLS`` cap, admits Word's widest row (63 columns)
+#: with every cell wrapped and room for markers; a step at both caps
+#: takes ~0.12 ms per read instead of ~0.10 ms, and the siblings are
+#: priced in it (see ``DOCX_MERGE_STEP_WEIGHT``). Children after a
+#: table's last row, which no step walks, are not capped (a table may
+#: hold all its rows in ``w:sdt`` wrappers).
+MAX_DOCX_ROW_OTHER_CHILDREN = 256
+MAX_DOCX_TABLE_ROW_GAP = 256
+
+#: Descendant nodes of a table cell that count as one unit of
+#: ``MAX_DOCX_RUN_WORK``, before the cell's work is multiplied by its
+#: span (or added for each cell continuing its merge).
+#: unstructured reads a cell's content once per grid column it is
+#: yielded for (``iter_inner_content`` and ``paragraphs`` walk its
+#: children, ``Paragraph.text`` each paragraph's), so content other
+#: than runs is walked span times too: a cell spanning 1,000 columns
+#: with 60,000 empty elements after its paragraph took ~1.7 s to
+#: partition (~28 ns per node and yield) and was counted 5,005 units.
+#: Real cells hold tens of nodes, which count nothing. That walk is
+#: linear only for nodes python-docx skips; the cell's paragraphs and
+#: tables are priced as items (``DOCX_CELL_BLOCK_ITEM_WEIGHT``) and the
+#: union that selects them by ``DOCX_UNION_STEPS_PER_RUN_WORK_UNIT``.
+DOCX_CELL_NODES_PER_UNIT = 256
+
+#: Units of ``MAX_DOCX_RUN_WORK`` per ``w:p`` or ``w:tbl`` child of a
+#: table cell, before the cell's work is multiplied by its span:
+#: unstructured builds a python-docx object for each of them and reads
+#: its text (and a paragraph's runs for emphasis) once per yield, about
+#: 20 us for an empty paragraph and 7 us for an empty table measured
+#: (16,000 of either in one cell, 1 against 8 yields).
+DOCX_CELL_BLOCK_ITEM_WEIGHT = 1
+
+#: Node-set unions python-docx and unstructured evaluate on each read
+#: of a cell, paragraph or run: ``./w:p | ./w:tbl`` over a cell's
+#: children (and a header's, and, in a document with no sections, the
+#: body's), ``w:r | w:hyperlink`` over a paragraph's, and the six
+#: text-element branches of ``CT_R.text`` over a run's.
+#: libxml2 (2.14 measured) merges each branch's result into the
+#: previous ones by comparing every node with every node already
+#: there, then sorts the merged set into document order with
+#: comparisons that each walk sibling links towards the end of the
+#: parent; the merged set is out of order as soon as a later branch's
+#: node precedes an earlier branch's, so one evaluation with M nodes
+#: selected out of N child nodes costs up to M * N steps (per branch
+#: merged after the first): ~2 ns a step in cache, ~60 ns from memory
+#: in isolation (one ``w:tbl`` before 10,000 twenty-attribute
+#: paragraphs and 40,000 forty-attribute elements: 31 s for one
+#: evaluation), and up to ~115 ns per step and read end to end in
+#: ``partition_docx`` (1,000 ``w:t`` before a ``w:br`` and 40,000 to
+#: 60,000 elements of 40-120 attributes in one run). A step is priced
+#: at 120 ns, so one unit (~30 us) is 250 steps of one evaluation; the
+#: steps of a cell, paragraph or run are counted ``DOCX_UNION_READS``
+#: times (then multiplied, like the rest of its work, by its span, its
+#: page breaks or its merges). At 0.82-0.86 of the ceiling under the
+#: 100 ns first tried, such a run took 35 s, such a paragraph (a
+#: hyperlink before 1,000 runs and 60,000 forty-attribute elements)
+#: 21 s and such a cell (a table before 1,000 paragraphs and 60,000
+#: forty-attribute elements) 11 s. A body-level paragraph's text is
+#: also read with unstructured's
+#: ``w:r | w:hyperlink | w:r/descendant::wp:inline[ancestor::w:drawing][1]//w:r``,
+#: whose third branch selects the runs inside an inline drawing of each
+#: of the paragraph's runs: those are counted as a third branch
+#: (any ``w:r`` under a ``wp:inline`` under a ``w:drawing`` in one of
+#: the paragraph's ``w:r`` children), and since they are not the
+#: paragraph's children, and libxml2 merges each run's share of them
+#: into the earlier shares the same way, the evaluation is counted at
+#: M * max(M, N) steps: a run whose inline drawing holds one run, before
+#: 10,000 plain runs (a 37 KB file), took 0.37 s per evaluation, and
+#: before 40,000, 8.9 s; ten runs whose drawings hold 5,000 runs each,
+#: 2.9 s (counted at 0.04 and 0.17 of the ceiling before, so that
+#: 0.9 of it would have bought minutes). Sorting two runs of one drawing
+#: walks that drawing's nodes after the earlier one, so such an
+#: evaluation also counts M times the child nodes of every node inside
+#: the paragraph's runs' inline drawings (the inlines' own included):
+#: one run with a hyperlink after it, whose drawing holds 1,000 runs
+#: before 100,000 empty elements (a 38 KB file), took 0.31-0.39 s per
+#: evaluation and was counted at 0.04 of the ceiling before (1.65 now);
+#: the costliest accepted shape measured with it, 30 runs before 1.8
+#: million elements in one drawing (52 KB, 0.92 of the ceiling), takes
+#: 2.3 s per evaluation (~40 ns per step). Only an evaluation with at least
+#: two non-empty branches is counted: one branch needs no merge and is
+#: already in order (an evaluation already in order costs only the
+#: merge's comparisons, but is counted the same). Before the change, a 37 KB file with one
+#: cell spanning 1,000 columns that held 16,000 empty paragraphs and
+#: 16,000 empty tables was accepted at 0.09 of the ceiling and took
+#: ~1.5 s per yield (~25 minutes).
+DOCX_UNION_STEPS_PER_RUN_WORK_UNIT = 250
+
+#: Evaluations counted per union of a cell, paragraph or run. Measured
+#: per body-level paragraph fragment: five of each run's union and four
+#: of the paragraph's (its text twice, unstructured's classification
+#: lookup and its hyperlink walk); per cell, span + 1 of the cell's
+#: union and of its paragraphs' and 2 * span + 1 of its runs' (one or
+#: two per yield and one for the table's text), which six per yield
+#: covers.
+DOCX_UNION_READS = 6
+
+#: Union steps of one header/footer read that count as one byte of
+#: ``MAX_DOCX_HEADER_FOOTER_BYTES`` (a byte read is priced at ~3.5 us,
+#: a step at 120 ns): each reference reads the part's root union, and
+#: each of its cells', paragraphs' and runs' unions, once.
+DOCX_UNION_STEPS_PER_HEADER_BYTE = 29
+
+#: Attributes up to which the guard reads an element's attribute values
+#: with ``attrib.values()``, quadratic in their number but fastest for
+#: few (about 0.4 us for three); above it, with an ``@*`` XPath, linear
+#: with a larger fixed cost (about 60 us for 256 against 140 us).
+_DOCX_ATTRIBUTE_VALUES_SCAN = 64
+
+#: ``gridBefore``/``gridAfter`` padding columns that count as one unit
+#: of ``MAX_DOCX_RUN_WORK`` (one empty string yielded and one ``<td/>``
+#: emitted each: ~0.5 us and ~20 bytes measured).
+DOCX_GRID_PADDING_PER_RUN_WORK_UNIT = 8
+
+#: Ceiling on the bytes python-docx and unstructured *copy* out of
+#: ``document.xml`` beyond reading it once: the text, attributes,
+#: namespace declarations and nodes that one bounded paragraph or cell
+#: turns into many copies, each priced at what a copy of it was
+#: measured to keep.
+#:
+#: - A paragraph with K rendered page breaks: unstructured's
+#: ``iter_paragraph_items`` recurses once per break, and each level
+#: deep-copies the rest of the paragraph twice (python-docx's
+#: preceding and following fragments) and keeps both until the
+#: paragraph is done. Runs and hyperlinks leave the fragment they do
+#: not belong to, so their content is kept up to K + 1 times (80
+#: breaks before 3 MB of text, a 40 KB file, kept ~230 MB more than
+#: the same paragraph without them, and 20 breaks before 200,000
+#: nested empty elements ~530 MB, ~130 bytes a node); everything else
+#: stays in all 2K copies: the ``w:p`` element with its attributes
+#: and namespace declarations, its ``w:pPr``, the comments and
+#: processing instructions in it, the text after it (lxml copies an
+#: element's tail), and a declaration of each namespace it uses that
+#: an ancestor declares (libxml2 re-declares those on every copy).
+#: Each break is therefore counted as two copies of the paragraph,
+#: of its tail, and of each namespace declaration of the
+#: ``w:document`` and ``w:body`` elements whose URI an element or
+#: attribute name in the paragraph uses: 8 breaks before a 2 MB
+#: namespace URI on the ``w:p``, a 39 KB file, kept ~29 MB, and such
+#: declarations were not counted before (a URI that long is now
+#: refused outright, see ``MAX_DOCX_NAMESPACE_URI_CHARS``).
+#: - A table cell spanning S grid columns: its text is extracted and
+#: kept S times (counted as S - 1 extra copies, multiplied through
+#: nested tables), each copy priced at
+#: ``DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE`` per byte of its text, since
+#: unstructured keeps each copy as a string and twice more HTML-escaped
+#: (in its row's and in the table's HTML): 20 extra copies of a 1 MB
+#: cell of ``"`` and one emoji, a 38 KB file, kept ~1 GB.
+#: - A cell continuing a vertical merge: python-docx yields the cell
+#: its merge starts from, so that cell's text is kept once more per
+#: continuing row, priced as a spanned cell's copies are. The
+#: streaming pass cannot resolve which cell that is, so it counts the
+#: largest cell (times its span) of the earlier rows of the same
+#: table: 300 continuing rows under a 1 MB cell, a 38 KB file, kept
+#: ~930 MB and took 21 s, and 20 under a 1 MB cell of ``"`` and one
+#: emoji kept ~1 GB. A table whose continuing rows times its largest
+#: earlier cell exceed about 2 MiB of text (``MAX_DOCX_COPIED_BYTES``
+#: divided by ``DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE``; 200 continuing
+#: rows beside a 10 KB cell) is therefore refused, even when the cells
+#: actually merged are small. A cell continues exactly
+#: when python-docx and unstructured say so (``tc.vMerge ==
+#: "continue"``): the first ``w:vMerge`` of the cell's first
+#: ``w:tcPr`` has ``w:val="continue"`` or no ``w:val``. Any other
+#: cell, whatever other ``w:vMerge`` or ``w:tcPr`` elements it
+#: carries, is counted as an ordinary cell, once per spanned column.
+#:
+#: Real documents copy a few MB: Word writes about one rendered page
+#: break per page, in paragraphs of a few KB, and spans and merges of
+#: small cells. Element, attribute and processing-instruction names
+#: are not counted: lxml's copies share them through the parser's name
+#: dictionary (measured: no growth). The count is not a measurement:
+#: each item is priced at about the most its copy was measured to keep
+#: (an element ~130 bytes, an attribute ~275, a declaration ~110,
+#: a byte of lxml text about 1; a byte of table-cell text ~52 at worst,
+#: ~12 for plain ASCII), and the shapes measured kept less than they
+#: were counted (20 page breaks before 200,000 nested empty elements
+#: ~530 MB, counted ~1 GB; 20 before 200 elements of 256 empty
+#: attributes ~310 MB, counted ~590 MB; 20 extra copies of a 1 MB cell of ``"`` and
+#: one emoji ~1 GB, counted ~1.3 GB), so a document at this ceiling
+#: keeps on the order of 128 MiB of copies, not more.
+MAX_DOCX_COPIED_BYTES = 128 * 1024 * 1024
+
+#: Bytes a copied element, comment, processing instruction or
+#: namespace declaration counts in ``MAX_DOCX_COPIED_BYTES`` besides
+#: its text, attribute values, prefix and URI: an lxml node (~130 bytes
+#: per copied empty element, ~110 per copied declaration measured).
+DOCX_COPIED_BYTES_PER_NODE = 128
+
+#: Bytes an attribute counts in ``MAX_DOCX_COPIED_BYTES`` besides its
+#: value: libxml2 copies it as an attribute node and a text node
+#: (~275 bytes per empty attribute per copy measured, the same with or
+#: without a namespace).
+DOCX_COPIED_BYTES_PER_ATTRIBUTE = 288
+
+#: Bytes a byte of table-cell text counts in ``MAX_DOCX_COPIED_BYTES``
+#: per extra copy of the cell (spanned column or continued merged
+#: row). unstructured's ``_convert_table_to_html`` keeps every copy as
+#: a string, then HTML-escaped in its row's string and again in the
+#: table's, all at once: a ``"`` (one byte of XML text) becomes
+#: ``&quot;`` (six characters) and one astral character in a string
+#: makes it four bytes per character, so a byte costs up to 4 + 2 x 24
+#: = 52 bytes (measured ~49 per extra copy; ~12 for plain ASCII text).
+DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE = 64
+
+#: Children of python-docx's default styles part, which it creates when
+#: the document part has no styles relationship; the style lookup
+#: (``MAX_DOCX_STYLE_WORK``) scans at least that many entries.
+DOCX_DEFAULT_STYLES_ENTRIES = 6
+
+_RELS_NS = "{http://schemas.openxmlformats.org/package/2006/relationships}"
+_R_ID = (
+ "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id"
+)
+_RT_OFFICE_DOCUMENT = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
+ "officeDocument"
+)
+_P_NS = "{http://schemas.openxmlformats.org/presentationml/2006/main}"
+_W_NS = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
+_W_HDRFTR_REFS = (f"{_W_NS}headerReference", f"{_W_NS}footerReference")
+
+
+def _skeleton_xml(archive: zipfile.ZipFile, name: str):
+ """Parse member *name* (held to ``MAX_OPC_SKELETON_PART_BYTES``,
+ and read through ``_read_counted_xml``: UTF-8, start tags of at
+ most ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` attributes, no DTD) without
+ entity resolution or network access; ``None`` if absent."""
+ from lxml import etree
+
+ try:
+ info = archive.getinfo(name)
+ except KeyError:
+ return None
+ if info.file_size > MAX_OPC_SKELETON_PART_BYTES:
+ raise DecompressionBombError(
+ "document package part is larger than "
+ f"{MAX_OPC_SKELETON_PART_BYTES} bytes"
+ )
+ parser = etree.XMLParser(resolve_entities=False, no_network=True)
+ root = etree.fromstring(_read_counted_xml(archive, info), parser=parser)
+ _refuse_dtd(root)
+ return root
+
+
+def _part_rels(
+ archive: zipfile.ZipFile,
+ packuri_cls,
+ partname: str,
+ *,
+ skip_missing_targets: bool,
+) -> dict[str, tuple[str, Optional[str]]]:
+ """``{rId: (reltype, target partname or None if external)}`` for
+ *partname*, built the way the loading library builds it: later
+ duplicates of an rId win, and (python-pptx only,
+ *skip_missing_targets*) internal relationships whose target is not
+ in the archive are dropped before that. A relationships part with
+ more than ``MAX_PART_RELATIONSHIPS`` children is refused."""
+ members = set(archive.namelist())
+ root = _skeleton_xml(archive, packuri_cls(partname).rels_uri.membername)
+ rels: dict[str, tuple[str, Optional[str]]] = {}
+ if root is None:
+ return rels
+ if len(root) > MAX_PART_RELATIONSHIPS:
+ raise DecompressionBombError(
+ f"package relationships part has {len(root)} entries "
+ f"(ceiling {MAX_PART_RELATIONSHIPS})"
+ )
+ base_uri = packuri_cls(partname).baseURI
+ for rel in root.findall(f"{_RELS_NS}Relationship"):
+ if rel.get("TargetMode", "Internal") == "External":
+ target = None
+ else:
+ target = packuri_cls.from_rel_ref(base_uri, rel.get("Target"))
+ if skip_missing_targets and target[1:] not in members:
+ continue
+ rels[rel.get("Id")] = (rel.get("Type"), target)
+ return rels
+
+
+def _check_package_relationships(
+ archive: zipfile.ZipFile, *, price_walk: bool
+) -> None:
+ """Refuse a ``.docx``/``.pptx`` package any of whose relationships
+ parts (``*.rels`` members, whichever part they belong to, reached
+ or not) is over ``MAX_OPC_SKELETON_PART_BYTES``, declares a DTD or
+ has more than ``MAX_PART_RELATIONSHIPS`` entries, whose
+ relationships parts have more than ``MAX_PACKAGE_RELATIONSHIPS``
+ entries together, or (*price_walk*, python-docx) whose internal
+ relationships times its members cost python-docx's relationship
+ walks more than ``MAX_DOCX_RELATIONSHIP_WALK``. Each part is
+ streamed and each entry dropped once read, so at most the root and
+ one entry are held: every element child of the root counts as an
+ entry, internal unless its ``TargetMode`` is ``External``, as the
+ libraries read it, and every comment and processing instruction
+ counts as an entry too. A part with an element below an entry, or
+ an element with more than ``MAX_RELS_ELEMENT_ATTRIBUTES``
+ attributes, is refused when that element starts: the OPC schema
+ gives ``Relationship`` four attributes and text content only, and
+ without this one entry holding millions of children (16 MiB, about
+ 16 KB deflated, in a part no library reads) was built in full,
+ costing the guard 3.1 s and ~550 MB per part. Each part is read
+ through ``_CountedXmlStream``, so lxml never receives a start tag of
+ more than ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` attributes: ``iterparse``
+ builds one in full before its start event (1,000,000 attributes
+ cost this check about 200 MB before)."""
+ from lxml import etree
+
+ total = internal = 0
+ for info in archive.infolist():
+ if not info.filename.lower().endswith(".rels"):
+ continue
+ if info.file_size > MAX_OPC_SKELETON_PART_BYTES:
+ raise DecompressionBombError(
+ "document package part is larger than "
+ f"{MAX_OPC_SKELETON_PART_BYTES} bytes"
+ )
+ entries = depth = 0
+ with archive.open(info) as stream:
+ for event, element in etree.iterparse(
+ _CountedXmlStream(stream),
+ events=("start", "end", "comment", "pi"),
+ resolve_entities=False,
+ no_network=True,
+ ):
+ if event == "end":
+ depth -= 1
+ if depth == 1:
+ # Keep no tree: drop each entry once read.
+ element.clear()
+ parent = element.getparent()
+ while element.getprevious() is not None:
+ del parent[0]
+ continue
+ if event == "start":
+ depth += 1
+ if depth > 2:
+ raise DecompressionBombError(
+ "package relationships entry has child elements"
+ )
+ if len(element.attrib) > MAX_RELS_ELEMENT_ATTRIBUTES:
+ raise DecompressionBombError(
+ "package relationships element has more than "
+ f"{MAX_RELS_ELEMENT_ATTRIBUTES} attributes"
+ )
+ if depth == 1:
+ _refuse_dtd(element)
+ continue
+ if element.get("TargetMode") != "External":
+ internal += 1
+ # An entry, or a comment or processing instruction
+ # anywhere in the part (each stays in the tree until
+ # the entry it is in, or the next one, ends).
+ entries += 1
+ if entries > MAX_PART_RELATIONSHIPS:
+ raise DecompressionBombError(
+ "package relationships part has more than "
+ f"{MAX_PART_RELATIONSHIPS} entries"
+ )
+ total += entries
+ if total > MAX_PACKAGE_RELATIONSHIPS:
+ raise DecompressionBombError(
+ "package relationships parts have more than "
+ f"{MAX_PACKAGE_RELATIONSHIPS} entries together"
+ )
+ if not price_walk or not internal:
+ return
+ names = archive.namelist()
+ steps = (
+ len(names)
+ + sum(len(name) * _str_width(name) for name in names)
+ // DOCX_RELATIONSHIP_WALK_NAME_BYTES_PER_STEP
+ )
+ if internal * steps > MAX_DOCX_RELATIONSHIP_WALK:
+ raise DecompressionBombError(
+ f"package's {internal} internal relationships over {len(names)} "
+ f"members cost {internal * steps} steps in python-docx's "
+ f"relationship walk (ceiling {MAX_DOCX_RELATIONSHIP_WALK})"
+ )
+
+
+def _str_width(text: str) -> int:
+ """Bytes per character CPython stores *text* with (PEP 393): 1 when
+ every code point is below 256, 2 below 65,536, else 4. Comparing
+ two equal strings of equal length reads ``len * width`` bytes."""
+ if text.isascii():
+ return 1
+ widest = max(text)
+ if widest <= "\xff":
+ return 1
+ return 2 if widest <= "\uffff" else 4
+
+
+def _main_part(
+ archive: zipfile.ZipFile, packuri_cls, *, skip_missing_targets: bool
+) -> Optional[str]:
+ """The package's main document partname, resolved as the library
+ resolves it, or ``None`` when the library cannot load the package
+ at all: python-pptx and python-docx both require exactly one
+ internal officeDocument relationship (``part_with_reltype`` raises
+ otherwise) whose target is in the archive. Such a package is
+ refused: the library cannot extract text from it, and a package
+ without its main part is what a content sniffer may take for
+ another type (see ``_check_package_type``)."""
+ rels = _part_rels(
+ archive, packuri_cls, "/", skip_missing_targets=skip_missing_targets
+ )
+ mains = [
+ target
+ for reltype, target in rels.values()
+ if reltype == _RT_OFFICE_DOCUMENT
+ ]
+ if len(mains) != 1 or mains[0] is None:
+ return None
+ if mains[0][1:] not in set(archive.namelist()):
+ return None
+ return mains[0]
+
+
+_CT_NS = "{http://schemas.openxmlformats.org/package/2006/content-types}"
+_CT_PREFIX = "application/vnd.openxmlformats-officedocument."
+_CT_PML_SLIDE = frozenset({_CT_PREFIX + "presentationml.slide+xml"})
+_CT_PML_SLIDE_LAYOUT = frozenset(
+ {_CT_PREFIX + "presentationml.slideLayout+xml"}
+)
+_CT_PML_SLIDE_MASTER = frozenset(
+ {_CT_PREFIX + "presentationml.slideMaster+xml"}
+)
+#: python-pptx's ``Presentation()`` accepts these main parts only.
+_CT_PML_MAINS = frozenset(
+ {
+ _CT_PREFIX + "presentationml.presentation.main+xml",
+ "application/vnd.ms-powerpoint.presentation.macroEnabled.main+xml",
+ }
+)
+#: python-docx's ``Document()`` accepts this main part only.
+_CT_WML_MAINS = frozenset({_CT_PREFIX + "wordprocessingml.document.main+xml"})
+_CT_WML_STYLES = frozenset({_CT_PREFIX + "wordprocessingml.styles+xml"})
+_CT_WML_SETTINGS = frozenset({_CT_PREFIX + "wordprocessingml.settings+xml"})
+_CT_WML_HEADER = frozenset({_CT_PREFIX + "wordprocessingml.header+xml"})
+_CT_WML_FOOTER = frozenset({_CT_PREFIX + "wordprocessingml.footer+xml"})
+
+
+class _ContentTypes(NamedTuple):
+ """``[Content_Types].xml`` as python-pptx and python-docx read it:
+ ``Override`` content types by lower-cased part name and ``Default``
+ ones by lower-cased extension, a later entry replacing an earlier
+ one with the same key."""
+
+ overrides: dict[str, Optional[str]]
+ defaults: dict[str, Optional[str]]
+
+
+def _content_types(archive: zipfile.ZipFile) -> _ContentTypes:
+ """Read the package's content types (see ``_ContentTypes``; the
+ part is held to ``MAX_OPC_SKELETON_PART_BYTES`` and refused with a
+ DTD). A package without the part, or with an entry missing its
+ part name or extension, is refused: both libraries fail to open
+ it."""
+ root = _skeleton_xml(archive, "[Content_Types].xml")
+ if root is None:
+ raise DecompressionBombError("document package has no content types")
+ overrides: dict[str, Optional[str]] = {}
+ defaults: dict[str, Optional[str]] = {}
+ for kind, key, table in (
+ ("Override", "PartName", overrides),
+ ("Default", "Extension", defaults),
+ ):
+ for entry in root.findall(f"{_CT_NS}{kind}"):
+ name = entry.get(key)
+ if name is None:
+ raise DecompressionBombError(
+ "document package has a malformed content type entry"
+ )
+ table[name.lower()] = entry.get("ContentType")
+ return _ContentTypes(overrides, defaults)
+
+
+def _content_type(types: _ContentTypes, partname: str) -> Optional[str]:
+ """The content type the libraries give *partname* (an absolute
+ part name): its ``Override``, else the ``Default`` of its extension
+ (``PackURI.ext``), else ``None``."""
+ key = partname.lower()
+ if key in types.overrides:
+ return types.overrides[key]
+ ext = posixpath.splitext(partname)[1]
+ ext = ext[1:] if ext.startswith(".") else ext
+ return types.defaults.get(ext.lower())
+
+
+def _require_content_type(
+ types: _ContentTypes, partname: str, allowed: frozenset[str], what: str
+) -> None:
+ """Refuse the package unless *partname*'s content type is in
+ *allowed*.
+
+ python-pptx and python-docx pick a part's class from its content
+ type, not from the relationship that reaches it, and several
+ classes answer the same property by following their own
+ relationship of the same type: a slide whose layout relationship
+ targets another slide reaches that slide's layout (``SlidePart``
+ has ``slide_layout`` too), and a document part whose styles or
+ settings relationship targets another document part reaches that
+ part's styles or settings. The guard reads the part a relationship
+ targets as the kind the relationship names, so such a chain would
+ let python-pptx or python-docx read parts the guard never priced
+ (a slide over a chained 300-placeholder layout was counted at 1,200
+ units, the same layout reached directly at about 90,000). A part
+ the library would build as another class either fails there or is
+ such a chain, so nothing a document legitimately holds is lost."""
+ content_type = _content_type(types, partname)
+ if content_type not in allowed:
+ raise DecompressionBombError(
+ f"document package's {what} part has the wrong content type"
+ )
+
+
+#: Ceiling on python-pptx's placeholder inheritance as unstructured
+#: drives it: the sum over slides of the slide's placeholders times the
+#: cost of one inherited read (``_pptx_inherited_read_units``).
+#: unstructured reads ``top`` and ``left`` of every shape on a slide up
+#: to three times each (to sort the shapes, and twice more to skip
+#: off-slide ones); a slide placeholder with no position of its own
+#: inherits it, and each such read rebuilds the slide part's
+#: relationships by type, finds the slide layout's placeholder of the
+#: same ``idx`` by building a proxy for each placeholder of the layout's
+#: shape tree in turn (two to three XPath evaluations each, every one
+#: walking the shape's children, its first child's and that child's
+#: ``p:nvPr``'s), and, when that one has no position either, does the
+#: same over the slide master's shape tree. Nothing is cached, so a
+#: slide of P placeholders over a layout of L shapes costs about
+#: 6 * P * L proxy builds: before the change, 100 placeholders over a
+#: 100-placeholder layout, a 30 KB file, took 5.2 s and 200 over 200,
+#: 18.6 s, quadrupling per doubling. A unit measured 400-430 us end to
+#: end in ``partition_pptx`` (the 200-over-200 slide is 46,000 units,
+#: 0.51 of the ceiling), so this fan-out at the ceiling is about 40 s.
+#: Office's default theme, as python-pptx and pandoc ship it, has 5-10
+#: shapes per layout and 7 on the master, and its title-and-content
+#: slide two placeholders without a position: 34 units per slide, so
+#: about 2,600 such slides fit; templates with tens of shapes per
+#: layout and master fit proportionally fewer (see "Known gaps").
+MAX_PPTX_PLACEHOLDER_WORK = 90_000
+
+#: Nodes below a layout's or master's shapes (``_PptxShapeTree.nodes``)
+#: that count as one unit of ``MAX_PPTX_PLACEHOLDER_WORK``: each of the
+#: six reads walks them at ~50 ns per node (a unit is ~420 us), so one
+#: counted twice for the text before it is priced at about ten times
+#: that.
+PPTX_PLACEHOLDER_NODES_PER_UNIT = 256
+
+#: Relationships of the slide and layout parts that count as one unit of
+#: ``MAX_PPTX_PLACEHOLDER_WORK``: python-pptx rebuilds the part's
+#: relationships by type on every read (100 placeholders on a slide of
+#: 10,000 relationships took 3.7 s more, ~0.6 us per relationship and
+#: read), so one is priced at about 3.5 times that.
+PPTX_PLACEHOLDER_RELATIONSHIPS_PER_UNIT = 32
+
+_RT_SLIDE_LAYOUT = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
+ "slideLayout"
+)
+_RT_SLIDE_MASTER = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
+ "slideMaster"
+)
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_P_CSLD = f"{_P_NS}cSld"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_P_SPTREE = f"{_P_NS}spTree"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_P_NVPR = f"{_P_NS}nvPr"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_P_PH = f"{_P_NS}ph"
+
+
+class _PptxShapeTree(NamedTuple):
+ """What ``_pptx_shape_tree`` counts in one slide-like part."""
+
+ #: Children of ``p:cSld/p:spTree`` (shapes and anything else but
+ #: text).
+ shapes: int
+ #: Their children, grandchildren and great-grandchildren (elements,
+ #: comments and processing instructions; python-pptx's
+ #: ``./*[1]/p:nvPr/p:ph`` walks some of them), each counted twice
+ #: for the text node that may precede it.
+ nodes: int
+ #: Children holding a ``p:ph`` in a ``p:nvPr`` of one of their own
+ #: children: python-pptx's placeholders (it looks in the first
+ #: child only, so this can only overcount).
+ placeholders: int
+
+
+def _check_pptx_slide_fan_out(content: bytes) -> None:
+ """Refuse a presentation listing the same slide part more than once,
+ or whose placeholder inheritance costs more than
+ ``MAX_PPTX_PLACEHOLDER_WORK``.
+
+ python-pptx yields one slide per ``<p:sldId>`` (first ``p:sldIdLst``
+ of the presentation part), resolved through that part's
+ relationships, so N entries resolving to one slide part make
+ unstructured extract that slide N times. Genuine presentations list
+ each slide part once. A ``<p:sldId>`` without a resolvable internal
+ relationship is refused too: python-pptx fails on it, so nothing
+ indexable is lost, and the check never has to guess. Each slide, and
+ each slide layout a slide with placeholders relates to and each
+ slide master such a layout relates to, is then streamed once (see
+ ``_pptx_shape_tree``). Every relationships part of the package is
+ held to ``MAX_PART_RELATIONSHIPS`` entries, and all of them together
+ to ``MAX_PACKAGE_RELATIONSHIPS`` (``_check_package_relationships``).
+ """
+ try:
+ import pptx # noqa: F401
+ except ImportError: # no python-pptx, no .pptx loader
+ return
+ try:
+ # Inside the fail-closed block, as for .xlsx: if an upgrade
+ # moves the helper, uploads are refused, not left unchecked.
+ from pptx.opc.packuri import PackURI
+
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
+ _check_package_relationships(archive, price_walk=False)
+ types = _content_types(archive)
+ targets = _pptx_slide_targets(archive, PackURI, types)
+ repeated = len(targets) != len(set(targets))
+ work = (
+ 0
+ if repeated
+ else _pptx_placeholder_work(
+ archive, PackURI, targets, MAX_PPTX_PLACEHOLDER_WORK, types
+ )
+ )
+ except DecompressionBombError:
+ raise
+ except Exception as exc: # lxml/zipfile failure modes are open-ended
+ raise DecompressionBombError("malformed presentation package") from exc
+ if repeated:
+ raise DecompressionBombError(
+ "presentation lists the same slide part more than once"
+ )
+ if work > MAX_PPTX_PLACEHOLDER_WORK:
+ raise DecompressionBombError(
+ "presentation's placeholders cost more than "
+ f"{MAX_PPTX_PLACEHOLDER_WORK} units of python-pptx's layout and "
+ "master lookups"
+ )
+
+
+def _pptx_placeholder_work(
+ archive: zipfile.ZipFile,
+ packuri_cls,
+ slides: list[str],
+ limit: int,
+ content_types: Optional[_ContentTypes] = None,
+) -> int:
+ """The sum over *slides* of each slide's placeholders times the
+ units of one inherited read (see ``MAX_PPTX_PLACEHOLDER_WORK``),
+ returned as soon as it exceeds *limit* (so that no more parts are
+ streamed than needed to refuse). Every placeholder is counted as
+ inheriting (whether or not it has a position of its own), every
+ slide layout a slide relates to (python-pptx fails on more than
+ one) and every master such a layout relates to are counted at the
+ costliest, and each part is streamed at most once. Each such layout
+ and master must have the content type python-pptx builds it from
+ (see ``_require_content_type``)."""
+ if content_types is None:
+ content_types = _content_types(archive)
+ types = content_types
+ members = set(archive.namelist())
+ trees: dict[str, _PptxShapeTree] = {}
+ rels: dict[str, dict[str, tuple[str, Optional[str]]]] = {}
+
+ def tree(partname: str) -> _PptxShapeTree:
+ if partname not in trees:
+ trees[partname] = _pptx_shape_tree(archive, partname[1:])
+ return trees[partname]
+
+ def related(
+ partname: str, reltype: str, allowed: frozenset[str], what: str
+ ) -> list[str]:
+ if partname not in rels:
+ rels[partname] = _part_rels(
+ archive, packuri_cls, partname, skip_missing_targets=True
+ )
+ targets = [
+ target
+ for kind, target in rels[partname].values()
+ if kind == reltype and target is not None and target[1:] in members
+ ]
+ for target in targets:
+ _require_content_type(types, target, allowed, what)
+ return targets
+
+ work = 0
+ for slide in slides:
+ placeholders = tree(slide).placeholders
+ if not placeholders:
+ continue
+ read = 0
+ for layout in related(
+ slide, _RT_SLIDE_LAYOUT, _CT_PML_SLIDE_LAYOUT, "slide layout"
+ ):
+ masters = related(
+ layout, _RT_SLIDE_MASTER, _CT_PML_SLIDE_MASTER, "slide master"
+ )
+ relationships = len(rels[slide]) + len(rels[layout])
+ candidates: list[Optional[str]] = list(masters) or [None]
+ for master in candidates:
+ read = max(
+ read,
+ _pptx_inherited_read_units(
+ tree(layout),
+ _PptxShapeTree(0, 0, 0)
+ if master is None
+ else tree(master),
+ relationships,
+ ),
+ )
+ work += placeholders * read
+ if work > limit:
+ break
+ return work
+
+
+def _pptx_inherited_read_units(
+ layout: _PptxShapeTree, master: _PptxShapeTree, relationships: int
+) -> int:
+ """Units of ``MAX_PPTX_PLACEHOLDER_WORK`` for one slide placeholder:
+ the shapes of its layout and master, their nodes per
+ ``PPTX_PLACEHOLDER_NODES_PER_UNIT`` and the slide's and layout's
+ *relationships* per ``PPTX_PLACEHOLDER_RELATIONSHIPS_PER_UNIT``
+ (each rounded up)."""
+ return (
+ layout.shapes
+ + master.shapes
+ - (-(layout.nodes + master.nodes) // PPTX_PLACEHOLDER_NODES_PER_UNIT)
+ - (-relationships // PPTX_PLACEHOLDER_RELATIONSHIPS_PER_UNIT)
+ )
+
+
+def _pptx_shape_tree(archive: zipfile.ZipFile, name: str) -> _PptxShapeTree:
+ """Count member *name*'s shape tree (see ``_PptxShapeTree``) in one
+ streaming pass, with no tree kept. A DTD, a namespace URI or
+ prefix over the caps ``document.xml`` is held to, or more than
+ ``MAX_XML_OUTSIDE_ROOT_NODES`` comments and processing instructions
+ outside the root, is refused. An
+ element's name is read only down to the depth of ``p:ph``, so the
+ pass is linear in the part's size."""
+ from lxml import etree
+
+ shapes = nodes = placeholders = outside = 0
+ # Names of the open elements down to p:ph's depth (7), and the depth.
+ path: list[str] = []
+ depth = 0
+ in_tree = has_ph = False
+ with archive.open(name) as stream:
+ for event, element in etree.iterparse(
+ _CountedXmlStream(stream),
+ events=("start-ns", "start", "end", "comment", "pi"),
+ resolve_entities=False,
+ no_network=True,
+ ):
+ if event == "start-ns":
+ prefix, uri = element
+ if (
+ len(uri) > MAX_DOCX_NAMESPACE_URI_CHARS
+ or len(prefix) > MAX_DOCX_NAMESPACE_PREFIX_CHARS
+ ):
+ raise DecompressionBombError(
+ "presentation part declares a namespace URI of more "
+ f"than {MAX_DOCX_NAMESPACE_URI_CHARS} or a prefix of "
+ f"more than {MAX_DOCX_NAMESPACE_PREFIX_CHARS} "
+ "characters"
+ )
+ continue
+ if event == "end":
+ if depth <= 7:
+ path.pop()
+ if depth == 3:
+ in_tree = False
+ depth -= 1
+ element.clear(keep_tail=False)
+ elif event == "start":
+ depth += 1
+ if depth == 1:
+ _refuse_dtd(element)
+ if depth <= 7:
+ tag = element.tag
+ path.append(tag)
+ if depth == 3:
+ in_tree = path[1] == _P_CSLD and tag == _P_SPTREE
+ elif in_tree and depth == 4:
+ shapes += 1
+ has_ph = False
+ elif in_tree:
+ nodes += 2
+ if (
+ depth == 7
+ and tag == _P_PH
+ and path[5] == _P_NVPR
+ and not has_ph
+ ):
+ has_ph = True
+ placeholders += 1
+ elif depth == 0:
+ outside = _note_outside_root_node(outside)
+ elif in_tree and depth == 3:
+ # A comment or processing instruction among the shapes,
+ # which python-pptx iterates over too.
+ shapes += 1
+ elif in_tree and 5 <= depth + 1 <= 7:
+ # A comment or processing instruction among the nodes.
+ nodes += 2
+ if event != "start":
+ # Drop what has been read (comments and processing
+ # instructions get no end event).
+ parent = element.getparent()
+ if parent is not None:
+ while element.getprevious() is not None:
+ del parent[0]
+ return _PptxShapeTree(shapes, nodes, placeholders)
+
+
+def _pptx_slide_targets(
+ archive: zipfile.ZipFile,
+ packuri_cls,
+ content_types: Optional[_ContentTypes] = None,
+) -> list[str]:
+ """The slide partname of every ``<p:sldId>``, in order. The main
+ part and each slide must have the content type python-pptx builds
+ them from (see ``_require_content_type``)."""
+ main = _main_part(archive, packuri_cls, skip_missing_targets=True)
+ if main is None:
+ raise DecompressionBombError(
+ "presentation package has no main document part"
+ )
+ if content_types is None:
+ content_types = _content_types(archive)
+ _require_content_type(content_types, main, _CT_PML_MAINS, "main")
+ root = _skeleton_xml(archive, main[1:])
+ if root is None: # pragma: no cover - _main_part checked membership
+ return []
+ rels = _part_rels(archive, packuri_cls, main, skip_missing_targets=True)
+ sld_id_lst = root.find(f"{_P_NS}sldIdLst")
+ if sld_id_lst is None:
+ return []
+ targets = []
+ for sld_id in sld_id_lst.findall(f"{_P_NS}sldId"):
+ resolved = rels.get(sld_id.get(_R_ID))
+ if resolved is None or resolved[1] is None:
+ raise DecompressionBombError(
+ "presentation lists a slide it cannot resolve"
+ )
+ _require_content_type(
+ content_types, resolved[1], _CT_PML_SLIDE, "slide"
+ )
+ targets.append(resolved[1])
+ return targets
+
+
+def _check_docx_section_fan_out(content: bytes) -> None:
+ """Bound python-docx's and unstructured's per-section,
+ per-paragraph, per-page-break and per-spanned-column work and
+ header/footer repeats (the known fan-outs; not the document's total
+ parse cost, see "Known gaps" in the module docstring).
+
+ Refused: more than ``MAX_DOCX_SECTIONS`` ``w:sectPr`` elements or
+ ``MAX_DOCX_PAGE_BREAKS`` ``w:lastRenderedPageBreak`` elements
+ anywhere in ``document.xml``; a relationships part with
+ more than ``MAX_PART_RELATIONSHIPS`` entries, relationships parts
+ with more than ``MAX_PACKAGE_RELATIONSHIPS`` together, or internal
+ relationships times members over ``MAX_DOCX_RELATIONSHIP_WALK``
+ (``_check_package_relationships``); a settings or styles
+ part over ``MAX_OPC_SKELETON_PART_BYTES``, with a DTD, or with more
+ than ``MAX_DOCX_SETTINGS_CHILDREN`` or ``MAX_DOCX_STYLES`` children
+ of its root; a ``w:gridSpan``, ``w:gridBefore`` or ``w:gridAfter``
+ over ``MAX_DOCX_GRID_SPAN`` or that python-docx cannot read; an
+ element with more than ``MAX_DOCX_ELEMENT_ATTRIBUTES`` attributes
+ or more than ``MAX_DOCX_NAMESPACES_IN_SCOPE`` namespace declarations
+ in scope; a body-level paragraph with more than
+ ``MAX_DOCX_PARAGRAPH_NAMESPACES`` declarations; a declaration whose
+ URI or prefix is longer than ``MAX_DOCX_NAMESPACE_URI_CHARS`` or
+ ``MAX_DOCX_NAMESPACE_PREFIX_CHARS``; a table row of more than
+ ``MAX_DOCX_ROW_CELLS`` cells or ``MAX_DOCX_ROW_GRID_COLUMNS``
+ columns; the
+ sum over sections of the body-level blocks up to
+ each section's end, times the body's child nodes, over
+ ``MAX_DOCX_SECTION_BLOCK_WORK``; the section count times the linear
+ per-section work (the body's child nodes, plus the nodes the
+ ``_sectPrs`` XPath visits divided by
+ ``DOCX_SECTION_XPATH_NODES_PER_UNIT``, plus the node pairs its union
+ compares divided by ``DOCX_SECTION_UNION_PAIRS_PER_UNIT``) over
+ ``MAX_DOCX_SECTION_WORK``; the summed size of the parts the
+ sections' ``headerReference``/``footerReference`` children point at
+ (counted once per reference, with the union steps of each read)
+ over ``MAX_DOCX_HEADER_FOOTER_BYTES``;
+ the style lookups over ``MAX_DOCX_STYLE_WORK``; the page-break
+ splitting over ``MAX_DOCX_PAGE_BREAK_WORK``; the text extraction
+ from runs and table cells (once per spanned column) over
+ ``MAX_DOCX_RUN_WORK`` (with each cell's paragraphs and tables and
+ the node-set unions of cells, paragraphs and runs, see
+ ``DOCX_UNION_STEPS_PER_RUN_WORK_UNIT``, and the merges and sort of
+ unstructured's page-break union, see
+ ``DOCX_PAGE_BREAK_UNION_PAIRS_PER_UNIT`` and
+ ``DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT``); the bytes copied per page
+ break, spanned column and continued merged cell over
+ ``MAX_DOCX_COPIED_BYTES``;
+ and, since each ceiling is the work one kind alone may cost, any
+ document whose seven works' shares of their ceilings sum to more
+ than 1.
+ Sections are the ``w:sectPr`` elements python-docx enumerates
+ (``w:body/w:p/w:pPr/w:sectPr`` and ``w:body/w:sectPr``). A
+ reference that does not resolve to a part in the archive is
+ refused, as python-docx fails on it. ``document.xml`` is streamed
+ with no tree kept, so this costs one parse pass over it.
+
+ The section, relationship, settings and styles caps bound the
+ per-section and per-paragraph work python-docx and unstructured do
+ that is not counted (see ``MAX_DOCX_SECTIONS``); it is bounded by
+ those caps, not modelled.
+ """
+ try:
+ import docx # noqa: F401
+ except ImportError: # no python-docx, no .docx loader
+ return
+ try:
+ from docx.opc.packuri import PackURI
+
+ with zipfile.ZipFile(io.BytesIO(content)) as archive:
+ _check_package_relationships(archive, price_walk=True)
+ stats = _docx_section_stats(archive, PackURI)
+ except DecompressionBombError:
+ raise
+ except Exception as exc: # lxml/zipfile failure modes are open-ended
+ raise DecompressionBombError(
+ "malformed word-processing package"
+ ) from exc
+
+ if stats.block_work > MAX_DOCX_SECTION_BLOCK_WORK:
+ raise DecompressionBombError(
+ f"document's {stats.sections} sections cost {stats.block_work} "
+ "block-by-node steps in python-docx's section lookup (ceiling "
+ f"{MAX_DOCX_SECTION_BLOCK_WORK})"
+ )
+ sections = stats.sections
+ work = (
+ sections * stats.body_nodes
+ + sections * stats.xpath_nodes // DOCX_SECTION_XPATH_NODES_PER_UNIT
+ + sections * stats.union_pairs // DOCX_SECTION_UNION_PAIRS_PER_UNIT
+ )
+ if work > MAX_DOCX_SECTION_WORK:
+ raise DecompressionBombError(
+ f"document has {sections} sections over {stats.body_nodes} "
+ f"body nodes, {stats.xpath_nodes} section-lookup nodes and "
+ f"{stats.union_pairs} section-lookup pairs (work {work}, ceiling "
+ f"{MAX_DOCX_SECTION_WORK})"
+ )
+ if stats.referenced_bytes > MAX_DOCX_HEADER_FOOTER_BYTES:
+ raise DecompressionBombError(
+ "document's header/footer references total over "
+ f"{MAX_DOCX_HEADER_FOOTER_BYTES} bytes"
+ )
+ style_work = stats.styled_paragraphs * (
+ stats.style_entries
+ + stats.style_attributes // DOCX_STYLE_ATTRIBUTES_PER_ENTRY
+ + stats.relationships // DOCX_RELATIONSHIPS_PER_STYLE_ENTRY
+ )
+ if style_work > MAX_DOCX_STYLE_WORK:
+ raise DecompressionBombError(
+ f"document's {stats.styled_paragraphs} paragraphs cost "
+ f"{style_work} steps in python-docx's style lookup over "
+ f"{stats.style_entries} styles part entries and "
+ f"{stats.relationships} relationships (ceiling "
+ f"{MAX_DOCX_STYLE_WORK})"
+ )
+ if stats.page_break_work > MAX_DOCX_PAGE_BREAK_WORK:
+ raise DecompressionBombError(
+ "document's rendered page breaks cost "
+ f"{stats.page_break_work} steps in python-docx's paragraph "
+ f"splitting (ceiling {MAX_DOCX_PAGE_BREAK_WORK})"
+ )
+ if stats.run_work > MAX_DOCX_RUN_WORK:
+ raise DecompressionBombError(
+ f"document's runs and table cells cost {stats.run_work} units "
+ f"of python-docx text extraction (ceiling {MAX_DOCX_RUN_WORK})"
+ )
+ if stats.copied_bytes > MAX_DOCX_COPIED_BYTES:
+ raise DecompressionBombError(
+ f"document's page breaks, spanned and merged cells copy "
+ f"{stats.copied_bytes} bytes in python-docx and unstructured "
+ f"(ceiling {MAX_DOCX_COPIED_BYTES})"
+ )
+ # Each ceiling above is the work one kind alone may cost; together
+ # they share one budget, so a document near several ceilings at
+ # once costs no more than one at a single ceiling.
+ shares = (
+ stats.block_work / MAX_DOCX_SECTION_BLOCK_WORK,
+ work / MAX_DOCX_SECTION_WORK,
+ stats.referenced_bytes / MAX_DOCX_HEADER_FOOTER_BYTES,
+ style_work / MAX_DOCX_STYLE_WORK,
+ stats.page_break_work / MAX_DOCX_PAGE_BREAK_WORK,
+ stats.run_work / MAX_DOCX_RUN_WORK,
+ stats.copied_bytes / MAX_DOCX_COPIED_BYTES,
+ )
+ if sum(shares) > 1:
+ raise DecompressionBombError(
+ "document's python-docx work takes "
+ f"{sum(shares):.2f} of the combined budget (section lookup, "
+ "section work, header/footer bytes, style lookup, page-break "
+ "splitting, text extraction and copied bytes, each as a share "
+ "of its ceiling)"
+ )
+
+
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_BODY = f"{_W_NS}body"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_P = f"{_W_NS}p"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_PPR = f"{_W_NS}pPr"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_SECTPR = f"{_W_NS}sectPr"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_TBL = f"{_W_NS}tbl"
+_W_BLOCKS = (_W_P, _W_TBL)
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_R = f"{_W_NS}r"
+_W_RUN_CONTAINERS = (_W_R, f"{_W_NS}hyperlink")
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_TR = f"{_W_NS}tr"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_TC = f"{_W_NS}tc"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_TRPR = f"{_W_NS}trPr"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_TCPR = f"{_W_NS}tcPr"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_GRID_SPAN = f"{_W_NS}gridSpan"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_GRID_BEFORE = f"{_W_NS}gridBefore"
+_W_GRID_VALUES = (_W_GRID_SPAN, _W_GRID_BEFORE, f"{_W_NS}gridAfter")
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_VMERGE = f"{_W_NS}vMerge"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_VAL = f"{_W_NS}val"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_LAST_RENDERED_PAGE_BREAK = f"{_W_NS}lastRenderedPageBreak"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_HYPERLINK = f"{_W_NS}hyperlink"
+# nosemgrep: semgrep.rules.sql-string-concatenation, reason: OOXML qualified name constant; no SQL sink
+_W_DRAWING = f"{_W_NS}drawing"
+_WP_INLINE = (
+ "{http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing}"
+ "inline"
+)
+#: The paths of unstructured's page-break union branches below the
+#: root, by depth of the ``w:lastRenderedPageBreak`` (see
+#: ``MAX_DOCX_PAGE_BREAKS``).
+_W_PAGE_BREAK_BRANCHES = {
+ 5: (_W_BODY, _W_P, _W_R),
+ 6: (_W_BODY, _W_P, _W_HYPERLINK, _W_R),
+ 8: (_W_BODY, _W_TBL, _W_TR, _W_TC, _W_P, _W_R),
+ 9: (_W_BODY, _W_TBL, _W_TR, _W_TC, _W_P, _W_HYPERLINK, _W_R),
+}
+#: The branches of ``CT_R.text``'s union, one bit each.
+_W_RUN_TEXT_BRANCHES = {
+ f"{_W_NS}{name}": 1 << bit
+ for bit, name in enumerate(
+ ("br", "cr", "noBreakHyphen", "ptab", "t", "tab")
+ )
+}
+#: Elements whose children python-docx selects with a union.
+_W_UNION_PARENTS = frozenset({_W_TC, _W_P, _W_R})
+_RT_SETTINGS = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
+ "settings"
+)
+_RT_STYLES = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
+)
+
+
+class _DocxSectionStats(NamedTuple):
+ """What ``_docx_section_stats`` counts in one streaming pass."""
+
+ #: ``w:sectPr`` elements anywhere in ``document.xml``.
+ sect_prs: int
+ #: The sections python-docx enumerates (N1 + N2 below).
+ sections: int
+ #: Child nodes of the body: elements, comments, processing
+ #: instructions and (non-empty) text.
+ body_nodes: int
+ #: Node visits of one ``_sectPrs`` XPath evaluation.
+ xpath_nodes: int
+ #: N1 * N2: paragraph-level times body-level section ``w:sectPr``.
+ union_pairs: int
+ #: Sum over sections of the body-level ``w:p``/``w:tbl`` up to the
+ #: section's end, times ``body_nodes``.
+ block_work: int
+ #: Header/footer bytes, counted once per reference, plus the union
+ #: steps of each read (``DOCX_UNION_STEPS_PER_HEADER_BYTE``).
+ referenced_bytes: int
+ #: Body-level paragraphs with a ``w:r`` or ``w:hyperlink`` child
+ #: (the only ones whose text can be non-empty), plus the
+ #: ``w:lastRenderedPageBreak`` elements inside them: an upper bound
+ #: on the paragraph fragments whose style unstructured looks up.
+ styled_paragraphs: int
+ #: Sum over body-level paragraphs of K * (K + 3) * S**2, K being the
+ #: paragraph's ``w:lastRenderedPageBreak`` elements and S the largest
+ #: child-node count of the paragraph or of any element in it.
+ page_break_work: int
+ #: Sum over body-level paragraphs and tables of (K + 1) *
+ #: (``DOCX_RUN_WORK_ITEM_WEIGHT`` * (``w:r``, ``w:tr`` and ``w:tc``
+ #: elements in it) + child nodes of its ``w:r`` elements) + K * (its
+ #: descendant nodes) // ``DOCX_FRAGMENT_NODES_PER_RUN_WORK_UNIT``
+ #: (K = 0 for a table). Within a table, a cell's work (with one
+ #: unit per ``DOCX_CELL_NODES_PER_UNIT`` of its descendant nodes) is
+ #: counted once per grid column it spans (through nested tables), a
+ #: cell continuing a vertical merge instead counts the largest cell
+ #: of the earlier rows, and a row counts its
+ #: ``gridBefore``/``gridAfter`` columns
+ #: (``DOCX_GRID_PADDING_PER_RUN_WORK_UNIT`` per unit) and
+ #: python-docx's steps up the merges its cells continue (see
+ #: ``_docx_merge_steps``). A cell also counts its ``w:p`` and
+ #: ``w:tbl`` children (``DOCX_CELL_BLOCK_ITEM_WEIGHT``), and every
+ #: cell, paragraph and run the steps of its union
+ #: (``DOCX_UNION_STEPS_PER_RUN_WORK_UNIT``; a body-level paragraph's
+ #: with the runs in its runs' inline drawings as a third branch,
+ #: and the nodes in those drawings), multiplied with the rest of its
+ #: work; without sections, the body's union is added once, and the
+ #: pairs merged and the steps sorted by unstructured's page-break
+ #: union are added once (``DOCX_PAGE_BREAK_UNION_PAIRS_PER_UNIT``,
+ #: ``DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT``).
+ run_work: int
+ #: Bytes copied beyond one read (see ``MAX_DOCX_COPIED_BYTES``):
+ #: per body-level paragraph, 2K times its bytes, its tail and the
+ #: ancestors' namespace declarations of the URIs it uses; per
+ #: spanned cell, (span - 1) times its text bytes; per continuing
+ #: merged cell, the text bytes of the largest cell of the earlier
+ #: rows of its table; cell text times
+ #: ``DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE``.
+ copied_bytes: int
+ #: Children of the styles part's root, at least
+ #: ``DOCX_DEFAULT_STYLES_ENTRIES`` (python-docx's default part).
+ style_entries: int
+ #: Attributes of those children.
+ style_attributes: int
+ #: Relationships of the document part.
+ relationships: int
+
+
+def _docx_section_stats(archive: zipfile.ZipFile, packuri_cls):
+ """Section statistics of the main document part (see
+ ``_DocxSectionStats``), from one streaming pass, after checking the
+ relationships, settings and styles parts.
+
+ The union pairs are N1 * N2, N1 being the ``w:body/w:p/w:pPr/w:sectPr``
+ elements and N2 the ``w:body/w:sectPr`` elements: libxml2 compares
+ every node of one union branch's result with every node of the
+ other's to drop duplicates.
+
+ The block work is, summed over sections, the body-level
+ ``w:p``/``w:tbl`` elements from the start of the body through the
+ paragraph holding a paragraph-level ``w:sectPr`` (or before a
+ body-level one), which is what python-docx's ``preceding-sibling``
+ lookup returns for that section, times the body's child nodes,
+ which bound the sibling walk of each comparison sorting them (see
+ ``MAX_DOCX_SECTION_BLOCK_WORK``). Blocks and nodes are counted
+ across all ``w:body`` elements, which can only overcount. Text
+ nodes are counted from the text before each body child and after
+ the last one, so ``element.clear`` keeps tails until then.
+
+ The node visits are those one evaluation of python-docx's
+ ``/w:document/w:body/w:p/w:pPr/w:sectPr | /w:document/w:body/w:sectPr``
+ makes: every element, comment and processing instruction that is a
+ child of the document node, of the root element, or of a ``w:body``
+ child of it (each counted twice, since both union branches walk
+ these levels), or of a body-level ``w:p`` or of that paragraph's
+ ``w:pPr`` (counted once). Text nodes are not counted; each sits
+ beside a counted node or alone in its parent. Entity reference
+ nodes, for which ``iterparse`` emits no event, cannot occur: a
+ ``document.xml`` with a DTD is refused in its bytes, before lxml
+ reads it (``_CountedXmlStream``).
+ Counting does not check the root's tag, which only adds nodes the
+ XPath would not visit.
+
+ Per body-level paragraph and table (python-docx's block items; the
+ content of ``w:sdt`` and other body-level elements is not read), the
+ child nodes of every element in it are counted as python-docx's tree
+ has them, text included: elements, comments and processing
+ instructions, the text before each and the text after the last.
+ From those come the page-break and run work (see
+ ``MAX_DOCX_PAGE_BREAK_WORK`` and ``MAX_DOCX_RUN_WORK``) and the
+ paragraphs whose style is looked up (``MAX_DOCX_STYLE_WORK``).
+ ``w:lastRenderedPageBreak`` elements are counted at any depth of a
+ paragraph and ``w:r`` elements at any depth of a block, though
+ python-docx reads only some of them, which can only overcount. The
+ bytes of each block (``MAX_DOCX_COPIED_BYTES``) are its text, its
+ attribute values, its namespace declarations (prefix and URI, from
+ the ``start-ns`` events), ``DOCX_COPIED_BYTES_PER_NODE`` per node
+ and per declaration and ``DOCX_COPIED_BYTES_PER_ATTRIBUTE`` per
+ attribute; the extra copies of a table cell count its text bytes
+ times ``DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE``; a paragraph's copies also count the text after
+ it and the declarations on the ``w:document`` and ``w:body``
+ elements of the namespace URIs its element and attribute names
+ use. A ``w:tc`` anywhere in a block weighs its content by its
+ ``w:gridSpan`` (the largest under any of its ``w:tcPr``, where
+ python-docx reads the first ``w:gridSpan`` of the first
+ ``w:tcPr``: never less), unless it continues a vertical merge as
+ python-docx reads it (the first ``w:vMerge`` of its first
+ ``w:tcPr``, with ``w:val`` absent or ``continue``): such a cell
+ adds the largest earlier cell of its table instead, which the cell
+ python-docx actually yields cannot exceed, and is not itself a
+ candidate for that largest cell. A row python-docx reads (a direct
+ ``w:tr`` child of a table) also counts python-docx's steps up the
+ vertical merges its cells continue (``_docx_merge_steps``), from the
+ spans and ``gridBefore`` as python-docx reads them.
+
+ Streaming stops with a refusal as soon as ``MAX_DOCX_SECTIONS`` or
+ ``MAX_DOCX_PAGE_BREAKS`` is exceeded, at the first grid value over ``MAX_DOCX_GRID_SPAN``, at
+ the first element with more than ``MAX_DOCX_ELEMENT_ATTRIBUTES``
+ attributes (counted before any is read), at the first with more
+ than ``MAX_DOCX_NAMESPACES_IN_SCOPE`` namespace declarations in
+ scope, at the first namespace declaration whose URI or prefix is
+ over its cap (before any name under it is read), at the first
+ paragraph over ``MAX_DOCX_PARAGRAPH_NAMESPACES``, at the first row
+ cell over ``MAX_DOCX_ROW_CELLS``, at the first other row child over
+ ``MAX_DOCX_ROW_OTHER_CHILDREN``, at the first row after more than
+ ``MAX_DOCX_TABLE_ROW_GAP`` other table children and at the end of
+ the first row over ``MAX_DOCX_ROW_GRID_COLUMNS``.
+
+ The pass reads each element's name (lxml builds it, namespace URI
+ included, on every read) at most twice and each attribute name at
+ most once, and each text, attribute value and comment at most
+ twice, so its time is linear in the size of ``document.xml``, a
+ name costing up to ``MAX_DOCX_NAMESPACE_URI_CHARS`` more per read
+ than its own length; the state it keeps is bounded by the depth (at
+ most 256, libxml2's limit), the namespace declarations in scope
+ (``pending_ns`` is refused as soon as it would exceed them) and the
+ open tables' last rows."""
+ from lxml import etree
+
+ main = _main_part(archive, packuri_cls, skip_missing_targets=False)
+ if main is None:
+ raise DecompressionBombError(
+ "word-processing package has no main document part"
+ )
+ types = _content_types(archive)
+ _require_content_type(types, main, _CT_WML_MAINS, "main")
+ rels = _part_rels(archive, packuri_cls, main, skip_missing_targets=False)
+ _docx_skeleton_entries(
+ archive,
+ rels,
+ _RT_SETTINGS,
+ MAX_DOCX_SETTINGS_CHILDREN,
+ "settings",
+ types,
+ _CT_WML_SETTINGS,
+ )
+ styles, style_attributes = _docx_skeleton_entries(
+ archive,
+ rels,
+ _RT_STYLES,
+ MAX_DOCX_STYLES,
+ "styles",
+ types,
+ _CT_WML_STYLES,
+ )
+ sizes = {info.filename: info.file_size for info in archive.infolist()}
+ body_nodes = xpath_nodes = referenced_bytes = outside = 0
+ # Blocks seen so far, and their sum over sections.
+ sect_prs = blocks = section_blocks = 0
+ # w:sectPr in body-level paragraph properties, and body-level ones.
+ paragraph_sections = body_sections = 0
+ styled_paragraphs = page_break_work = run_work = copied_bytes = 0
+ path: list[str] = []
+ # Child nodes seen so far of each element in ``path``.
+ children: list[int] = []
+ # The body-level paragraph or table being read, if any (0 if none,
+ # else 3, its depth): whether it is a paragraph with a w:r or
+ # w:hyperlink child, its page breaks, descendant nodes, largest
+ # child-node count, bytes (nodes, attribute values and text, see
+ # ``MAX_DOCX_COPIED_BYTES``) and text bytes as read once.
+ block_depth = 0
+ is_paragraph = has_run = False
+ page_breaks = block_nodes = widest = block_bytes = block_text = 0
+ # Run-work units and text bytes of the block as unstructured reads
+ # ``row.cells`` (python-docx shares a cell's objects between its
+ # yields, so only its text is copied):
+ # frames[0] for the block, one more per w:tc open in it, which is
+ # folded into its parent's frame, times its span, when it ends.
+ frames: list[list[int]] = []
+ # The w:tc, w:tbl and w:tr elements open in the block.
+ cells: list[_OpenCell] = []
+ tables: list[_OpenTable] = []
+ rows: list[_OpenRow] = []
+ # Namespace declarations in the body-level paragraph being read.
+ paragraph_ns = 0
+ # Union branch counts of each element in ``path`` whose children
+ # python-docx selects with a union (see
+ # ``DOCX_UNION_STEPS_PER_RUN_WORK_UNIT``), None for the others: a
+ # cell's w:p and w:tbl, a paragraph's w:r and w:hyperlink, a run's
+ # text branches (as a bit set) and their count.
+ unions: list[Optional[list[int]]] = []
+ # The body's w:p and w:tbl children (its union is read once when the
+ # document has no sections).
+ body_paragraphs = body_tables = 0
+ # Header/footer references per part.
+ references: dict[str, int] = {}
+ # w:lastRenderedPageBreak elements anywhere, and those in each branch
+ # of unstructured's page-break union, by depth (see
+ # MAX_DOCX_PAGE_BREAKS).
+ all_breaks = 0
+ break_branches = dict.fromkeys(_W_PAGE_BREAK_BRANCHES, 0)
+ # The union's breaks below each element in ``path``, and the sum
+ # over elements of those breaks (weighted for the sort's binary
+ # insertion) times the element's child nodes (see
+ # DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT).
+ breaks_below: list[int] = []
+ break_sort_steps = 0
+ # The w:drawing elements, and the wp:inline elements below one, open
+ # in a w:r child of the body-level paragraph being read: the runs
+ # under such an inline are the third branch of unstructured's
+ # paragraph union (see DOCX_UNION_STEPS_PER_RUN_WORK_UNIT).
+ drawings = inlines = 0
+
+ def visits(depth: int) -> int:
+ """Section-XPath visits of a node at *depth* (1 = a child of the
+ document node), given the ancestors in ``path[:depth - 1]``."""
+ if depth <= 2:
+ return 2
+ if path[1] != _W_BODY:
+ return 0
+ if depth == 3:
+ return 2
+ if path[2] != _W_P:
+ return 0
+ if depth == 4:
+ return 1
+ if depth == 5 and path[3] == _W_PPR:
+ return 1
+ return 0
+
+ def text_before(node) -> Optional[str]:
+ """The text node that precedes *node* among its siblings, if
+ any: python-docx keeps text that is not whitespace, and some
+ that is."""
+ previous = node.getprevious()
+ text: Optional[str] = (
+ node.getparent().text if previous is None else previous.tail
+ )
+ return text
+
+ # The namespace declarations announced by ``start-ns`` events for
+ # the next element, as (URI, bytes), and the bytes of those on the
+ # w:document and w:body elements by URI: libxml2 re-declares one on
+ # each copy of a paragraph that uses its URI.
+ pending_ns: list[tuple[str, int]] = []
+ ancestor_ns: dict[str, int] = {}
+ # The namespace URIs of ``ancestor_ns`` that element and attribute
+ # names in the body-level paragraph being read use (at most one
+ # entry per declaration there, so this stays small however many
+ # names use them).
+ used_uris: set[str] = set()
+ # Copies kept of the text after the last body-level paragraph,
+ # added when that text is seen.
+ tail_copies = 0
+
+ attribute_values = etree.XPath("@*", smart_strings=False)
+
+ def node_bytes(node, is_element: bool) -> int:
+ """What copying *node* (an element, comment or processing
+ instruction) costs, without its children or the text around
+ them: a node, and per attribute its node and its value."""
+ size = DOCX_COPIED_BYTES_PER_NODE
+ if is_element:
+ # At most MAX_DOCX_ELEMENT_ATTRIBUTES, checked at its start.
+ count = len(node.attrib)
+ if count:
+ size += count * DOCX_COPIED_BYTES_PER_ATTRIBUTE
+ values = (
+ node.attrib.values()
+ if count <= _DOCX_ATTRIBUTE_VALUES_SCAN
+ else attribute_values(node)
+ )
+ for value in values:
+ size += _text_bytes(value)
+ else:
+ size += _text_bytes(node.text)
+ return size
+
+ # Depth of the section-defining w:sectPr being read, if any:
+ # python-docx reads header/footer references from its direct
+ # children only.
+ section_depth = 0
+ # Namespace declarations in scope at each element of ``path``.
+ in_scope: list[int] = []
+ with archive.open(main[1:]) as stream:
+ for event, element in etree.iterparse(
+ _CountedXmlStream(stream),
+ events=("start-ns", "start", "end", "comment", "pi"),
+ resolve_entities=False,
+ no_network=True,
+ ):
+ if event == "start-ns":
+ prefix, uri = element
+ # Before any name under it is read (see
+ # MAX_DOCX_NAMESPACE_URI_CHARS).
+ if (
+ len(uri) > MAX_DOCX_NAMESPACE_URI_CHARS
+ or len(prefix) > MAX_DOCX_NAMESPACE_PREFIX_CHARS
+ ):
+ raise DecompressionBombError(
+ "document declares a namespace URI of more than "
+ f"{MAX_DOCX_NAMESPACE_URI_CHARS} or a prefix of more "
+ f"than {MAX_DOCX_NAMESPACE_PREFIX_CHARS} characters"
+ )
+ pending_ns.append(
+ (
+ uri,
+ DOCX_COPIED_BYTES_PER_NODE
+ + _text_bytes(prefix)
+ + _text_bytes(uri),
+ )
+ )
+ # The element they belong to is checked at its start;
+ # refusing here already keeps pending_ns as small.
+ scope = in_scope[-1] if in_scope else 0
+ if scope + len(pending_ns) > MAX_DOCX_NAMESPACES_IN_SCOPE:
+ raise DecompressionBombError(
+ "document has more than "
+ f"{MAX_DOCX_NAMESPACES_IN_SCOPE} namespace declarations "
+ "in scope"
+ )
+ continue
+ if event in ("comment", "pi"):
+ if not path:
+ # Outside the root, where python-docx never looks.
+ outside = _note_outside_root_node(outside)
+ continue
+ xpath_nodes += visits(len(path) + 1)
+ before = text_before(element)
+ if children:
+ children[-1] += 1 + bool(before)
+ if len(path) == 2 and path[1] == _W_BODY:
+ body_nodes += 1 + bool(before)
+ if tail_copies:
+ copied_bytes += tail_copies * _text_bytes(before)
+ tail_copies = 0
+ if block_depth:
+ text = _text_bytes(before)
+ frames[-1][1] += text
+ block_text += text
+ block_bytes += text + node_bytes(element, False)
+ _note_docx_table_child(len(path) + 1, None, tables, rows)
+ # Comments and PIs get no end event, so drop the
+ # siblings before them here too.
+ parent = element.getparent()
+ if parent is not None:
+ while element.getprevious() is not None:
+ del parent[0]
+ continue
+ # Each element's name is read once per event: lxml builds it
+ # afresh, URI included, on every read.
+ tag = element.tag
+ if event == "end":
+ if len(path) == section_depth:
+ section_depth = 0
+ # Inside an inline drawing of one of the paragraph's runs
+ # (the inline itself included): its child nodes are
+ # walked when the third branch's runs are sorted.
+ in_inline = bool(inlines)
+ if drawings and len(path) > block_depth + 1:
+ # The same test as at the element's start: the
+ # drawings open above it have not changed.
+ if tag == _W_DRAWING:
+ drawings -= 1
+ elif tag == _WP_INLINE:
+ inlines -= 1
+ # The text after the element's last child (or all of
+ # its text, if it has none).
+ last = element[-1] if len(element) else None
+ trailing = element.text if last is None else last.tail
+ if len(path) == 2 and tag == _W_BODY:
+ body_nodes += bool(trailing)
+ if tail_copies:
+ copied_bytes += tail_copies * _text_bytes(trailing)
+ tail_copies = 0
+ own = children.pop() + bool(trailing)
+ counter = unions.pop()
+ below = breaks_below.pop()
+ if below:
+ break_sort_steps += own * (
+ below
+ + DOCX_PAGE_BREAK_SORT_INSERTION_WALKS
+ * min(below, DOCX_PAGE_BREAK_SORT_INSERTION_RUN)
+ )
+ if breaks_below:
+ breaks_below[-1] += below
+ if in_inline and block_depth:
+ paragraph_union = unions[block_depth - 1]
+ if paragraph_union is not None:
+ paragraph_union[3] += own
+ if block_depth:
+ text = _text_bytes(trailing)
+ frames[-1][1] += text
+ block_text += text
+ block_bytes += text
+ block_nodes += own
+ widest = max(widest, own)
+ extra = 0
+ if counter is not None:
+ extra = _union_units(_union_steps(tag, counter, own))
+ if tag == _W_TC:
+ extra += DOCX_CELL_BLOCK_ITEM_WEIGHT * (
+ counter[0] + counter[1]
+ )
+ _fold_docx_text_work(
+ tag,
+ len(path),
+ own,
+ frames,
+ cells,
+ tables,
+ rows,
+ block_nodes,
+ extra,
+ )
+ if len(path) == block_depth:
+ block_depth = 0
+ units, weighted_text = frames.pop()
+ if has_run:
+ styled_paragraphs += 1 + page_breaks
+ page_break_work += (
+ page_breaks * (page_breaks + 3) * widest * widest
+ )
+ run_work += (page_breaks + 1) * units + (
+ page_breaks
+ * block_nodes
+ // DOCX_FRAGMENT_NODES_PER_RUN_WORK_UNIT
+ )
+ # Extra copies of table cells (spanned columns,
+ # continued merges), as unstructured's HTML
+ # keeps them; two fragments per break, each a
+ # deep copy of the paragraph (its tail included)
+ # that re-declares the ancestors' namespaces it
+ # uses.
+ copied_bytes += DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE * (
+ weighted_text - block_text
+ ) + (
+ 2
+ * page_breaks
+ * (
+ block_bytes
+ + sum(ancestor_ns[uri] for uri in used_uris)
+ )
+ )
+ tail_copies = 2 * page_breaks
+ path.pop()
+ in_scope.pop()
+ # Nothing is read after an element's start event but
+ # the text before the next sibling, so the tree is
+ # dropped as it is built, tails kept until then.
+ element.clear(keep_tail=True)
+ parent = element.getparent()
+ if parent is not None:
+ while element.getprevious() is not None:
+ del parent[0]
+ continue
+ # Counted, not read: reading an element's attribute values
+ # is quadratic in their number.
+ if len(element.attrib) > MAX_DOCX_ELEMENT_ATTRIBUTES:
+ raise DecompressionBombError(
+ "document has an element with more than "
+ f"{MAX_DOCX_ELEMENT_ATTRIBUTES} attributes"
+ )
+ declared = len(pending_ns)
+ in_scope.append((in_scope[-1] if in_scope else 0) + declared)
+ if in_scope[-1] > MAX_DOCX_NAMESPACES_IN_SCOPE:
+ raise DecompressionBombError(
+ "document has more than "
+ f"{MAX_DOCX_NAMESPACES_IN_SCOPE} namespace declarations "
+ "in scope"
+ )
+ before = None
+ if not path:
+ _refuse_dtd(element)
+ else:
+ before = text_before(element)
+ children[-1] += 1 + bool(before)
+ path.append(tag)
+ children.append(0)
+ unions.append(None)
+ breaks_below.append(0)
+ depth = len(path)
+ xpath_nodes += visits(depth)
+ if tag == _W_LAST_RENDERED_PAGE_BREAK:
+ all_breaks += 1
+ if all_breaks > MAX_DOCX_PAGE_BREAKS:
+ raise DecompressionBombError(
+ "document has more than "
+ f"{MAX_DOCX_PAGE_BREAKS} rendered page breaks"
+ )
+ branch = _W_PAGE_BREAK_BRANCHES.get(depth)
+ if branch is not None and tuple(path[1:-1]) == branch:
+ break_branches[depth] += 1
+ breaks_below[-1] = 1
+ ns_bytes = 0
+ if pending_ns:
+ for uri, size in pending_ns:
+ ns_bytes += size
+ if depth <= 2:
+ ancestor_ns[uri] = ancestor_ns.get(uri, 0) + size
+ del pending_ns[:]
+ if tag == _W_SECTPR:
+ sect_prs += 1
+ if sect_prs > MAX_DOCX_SECTIONS:
+ raise DecompressionBombError(
+ "document has more than "
+ f"{MAX_DOCX_SECTIONS} sections (w:sectPr elements)"
+ )
+ elif tag in _W_GRID_VALUES:
+ _note_docx_grid_value(element, tag, path, cells, rows)
+ elif tag == _W_TCPR:
+ # python-docx reads a cell's first w:tcPr only...
+ if cells and cells[-1].depth == depth - 1:
+ cells[-1].tc_pr = 1 if cells[-1].tc_pr == 0 else 2
+ elif tag == _W_TRPR:
+ # ...and a row's first w:trPr.
+ if rows and rows[-1].depth == depth - 1:
+ row = rows[-1]
+ row.tr_pr = 1 if row.tr_pr == 0 else 2
+ if row.tr_pr == 1:
+ row.tr_pr_nodes = -block_nodes
+ # The children find() visits up to it.
+ row.tr_pr_index = children[-2]
+ elif tag == _W_VMERGE:
+ # The first w:vMerge of the cell's first w:tcPr, whose
+ # missing w:val means "continue" (``tc.vMerge ==
+ # "continue"``).
+ if (
+ cells
+ and cells[-1].depth == depth - 2
+ and path[-2] == _W_TCPR
+ and cells[-1].tc_pr == 1
+ and not cells[-1].merge_read
+ ):
+ cells[-1].merge_read = True
+ cells[-1].continues = (
+ element.get(_W_VAL, "continue") == "continue"
+ )
+ if depth == 3 and path[1] == _W_BODY:
+ body_nodes += 1 + bool(before)
+ body_paragraphs += tag == _W_P
+ body_tables += tag == _W_TBL
+ if tail_copies:
+ copied_bytes += tail_copies * _text_bytes(before)
+ tail_copies = 0
+ if tag in _W_BLOCKS:
+ blocks += 1
+ block_depth = depth
+ is_paragraph = tag == _W_P
+ has_run = False
+ page_breaks = block_nodes = widest = 0
+ drawings = inlines = 0
+ block_bytes = block_text = paragraph_ns = 0
+ used_uris.clear()
+ frames.append([0, 0])
+ del cells[:], tables[:], rows[:]
+ # The text before the block is not part of it.
+ before = None
+ elif block_depth and is_paragraph:
+ if depth == 4 and tag in _W_RUN_CONTAINERS:
+ has_run = True
+ elif tag == _W_LAST_RENDERED_PAGE_BREAK:
+ page_breaks += 1
+ if block_depth:
+ parent_union = unions[-2]
+ if parent_union is not None:
+ _note_union_child(path[-2], tag, parent_union)
+ if tag in _W_UNION_PARENTS:
+ unions[-1] = [0, 0, 0, 0]
+ if (
+ is_paragraph
+ and depth > block_depth + 1
+ and path[block_depth] == _W_R
+ ):
+ if tag == _W_DRAWING:
+ drawings += 1
+ elif tag == _WP_INLINE:
+ if drawings:
+ inlines += 1
+ elif tag == _W_R and inlines:
+ # A run of the paragraph union's third branch.
+ paragraph_union = unions[block_depth - 1]
+ if paragraph_union is not None:
+ paragraph_union[2] += 1
+ # Before the element is itself recorded as an open
+ # table, row or cell.
+ _note_docx_table_child(depth, tag, tables, rows)
+ if tag == _W_TC:
+ frames.append([0, 0])
+ nodes_before = 0
+ if rows and rows[-1].depth == depth - 1:
+ row = rows[-1]
+ row.count += 1
+ if row.count > MAX_DOCX_ROW_CELLS:
+ raise DecompressionBombError(
+ "document has a table row of more than "
+ f"{MAX_DOCX_ROW_CELLS} cells"
+ )
+ # The row's nodes before this cell: its earlier
+ # children (text included) and their content.
+ nodes_before = (
+ block_nodes - row.nodes + children[-2] - 1
+ )
+ cells.append(_OpenCell(depth, nodes_before, block_nodes))
+ elif tag == _W_TBL:
+ tables.append(_OpenTable(depth))
+ elif tag == _W_TR:
+ # Rows python-docx reads: direct children of a table.
+ table_row = bool(tables) and tables[-1].depth == depth - 1
+ rows.append(_OpenRow(depth, table_row, block_nodes))
+ if table_row:
+ # The table's children before this row and after
+ # the last one python-docx reads (text, this row
+ # and, for the first, w:tblPr and w:tblGrid
+ # included), which _tr_above walks.
+ table = tables[-1]
+ rows[-1].gap = children[-2] - table.row_children
+ table.row_children = children[-2]
+ text = _text_bytes(before)
+ frames[-1][1] += text
+ block_text += text
+ block_bytes += text + node_bytes(element, True) + ns_bytes
+ if is_paragraph:
+ if declared:
+ paragraph_ns += declared
+ if paragraph_ns > MAX_DOCX_PARAGRAPH_NAMESPACES:
+ raise DecompressionBombError(
+ "document has a paragraph with more than "
+ f"{MAX_DOCX_PARAGRAPH_NAMESPACES} namespace "
+ "declarations"
+ )
+ if ancestor_ns:
+ _note_used_uris(
+ tag, element.keys(), ancestor_ns, used_uris
+ )
+ if tag == _W_SECTPR and (
+ (depth == 3 and path[1] == _W_BODY)
+ or (depth == 5 and path[1:4] == [_W_BODY, _W_P, _W_PPR])
+ ):
+ if depth == 3:
+ body_sections += 1
+ else:
+ paragraph_sections += 1
+ # Through the enclosing paragraph (already counted), or
+ # the blocks before a body-level w:sectPr.
+ section_blocks += blocks
+ section_depth = depth
+ elif (
+ section_depth
+ and depth == section_depth + 1
+ and tag in _W_HDRFTR_REFS
+ ):
+ resolved = rels.get(element.get(_R_ID))
+ if (
+ resolved is None
+ or resolved[1] is None
+ or resolved[1][1:] not in sizes
+ ):
+ raise DecompressionBombError(
+ "document references a header or footer it "
+ "cannot resolve"
+ )
+ if tag == _W_HDRFTR_REFS[0]:
+ _require_content_type(
+ types, resolved[1], _CT_WML_HEADER, "header"
+ )
+ else:
+ _require_content_type(
+ types, resolved[1], _CT_WML_FOOTER, "footer"
+ )
+ referenced_bytes += sizes[resolved[1][1:]]
+ references[resolved[1][1:]] = (
+ references.get(resolved[1][1:], 0) + 1
+ )
+ if (
+ not paragraph_sections + body_sections
+ and body_paragraphs
+ and body_tables
+ ):
+ # Without sections, unstructured reads the body's own union.
+ run_work += _union_units(blocks * body_nodes, reads=1)
+ # The merges of unstructured's page-break union (see
+ # MAX_DOCX_PAGE_BREAKS): each branch against the branches before it.
+ merged = break_pairs = 0
+ for count in break_branches.values():
+ break_pairs += merged * count
+ merged += count
+ if break_pairs:
+ run_work += -(-break_pairs // DOCX_PAGE_BREAK_UNION_PAIRS_PER_UNIT)
+ # Two non-empty branches (else there are no pairs): the merged
+ # set may be out of document order, and sorting it walks the
+ # siblings after the breaks.
+ run_work += -(-break_sort_steps // DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT)
+ if referenced_bytes <= MAX_DOCX_HEADER_FOOTER_BYTES:
+ # Each reference reads its part's unions once (see
+ # DOCX_UNION_STEPS_PER_HEADER_BYTE); a sum already over the
+ # ceiling is refused without reading them.
+ for name, count in references.items():
+ referenced_bytes = min(
+ referenced_bytes
+ + _docx_part_union_steps(archive, name)
+ * count
+ // DOCX_UNION_STEPS_PER_HEADER_BYTE,
+ _SATURATED,
+ )
+ return _DocxSectionStats(
+ sect_prs=sect_prs,
+ sections=paragraph_sections + body_sections,
+ body_nodes=body_nodes,
+ xpath_nodes=xpath_nodes,
+ union_pairs=paragraph_sections * body_sections,
+ block_work=section_blocks * body_nodes,
+ referenced_bytes=referenced_bytes,
+ styled_paragraphs=styled_paragraphs,
+ page_break_work=page_break_work,
+ run_work=run_work,
+ copied_bytes=copied_bytes,
+ style_entries=max(styles, DOCX_DEFAULT_STYLES_ENTRIES),
+ style_attributes=style_attributes,
+ relationships=len(rels),
+ )
+
+
+#: Work and byte counts saturate here: nested spans multiply, and a
+#: count past every ceiling needs no more digits.
+_SATURATED = 1 << 64
+
+
+def _note_union_child(parent: str, tag: str, counter: list[int]) -> None:
+ """Count *tag*, a child of *parent* (a cell, a paragraph, a run or a
+ header/footer root), in *counter*, its parent's union branches (see
+ ``DOCX_UNION_STEPS_PER_RUN_WORK_UNIT``)."""
+ if parent == _W_P:
+ if tag == _W_R:
+ counter[0] += 1
+ elif tag == _W_HYPERLINK:
+ counter[1] += 1
+ elif parent == _W_R:
+ bit = _W_RUN_TEXT_BRANCHES.get(tag)
+ if bit:
+ counter[0] |= bit
+ counter[1] += 1
+ elif tag == _W_P:
+ counter[0] += 1
+ elif tag == _W_TBL:
+ counter[1] += 1
+
+
+def _union_steps(tag: str, counter: list[int], own: int) -> int:
+ """Steps of one evaluation of the union over the *own* child nodes
+ of a *tag* element whose branches *counter* counted: per branch
+ merged after the first non-empty one, the nodes selected times the
+ child nodes (or times the nodes selected, when a branch selects
+ nodes that are not children: a body-level paragraph's runs in inline
+ drawings, whose sort also walks the nodes in those drawings,
+ ``counter[3]``), and nothing with fewer than two non-empty
+ branches."""
+ if tag == _W_R:
+ branches = bin(counter[0]).count("1")
+ selected = counter[1]
+ else:
+ branches = sum(1 for count in counter[:3] if count)
+ selected = sum(counter[:3])
+ if branches < 2:
+ return 0
+ steps = (branches - 1) * selected * max(own, selected)
+ if len(counter) > 3 and counter[2]:
+ # A body-level paragraph's runs in inline drawings: sorting
+ # them walks the nodes of those drawings (``counter[3]``).
+ steps += selected * counter[3]
+ return steps
+
+
+def _union_units(steps: int, reads: int = DOCX_UNION_READS) -> int:
+ """Units of ``MAX_DOCX_RUN_WORK`` for *steps* union steps evaluated
+ *reads* times (rounded up)."""
+ if not steps:
+ return 0
+ return min(
+ -(-steps * reads // DOCX_UNION_STEPS_PER_RUN_WORK_UNIT), _SATURATED
+ )
+
+
+def _docx_part_union_steps(archive: zipfile.ZipFile, name: str) -> int:
+ """Union steps of one read of header/footer part *name*: its root's
+ ``./w:p | ./w:tbl``, and the union of every cell, paragraph and run
+ in it (see ``DOCX_UNION_STEPS_PER_RUN_WORK_UNIT``), each evaluated
+ once per read. Streamed with no tree kept; a DTD, or a namespace
+ URI or prefix over its cap, is refused as in ``document.xml``, and
+ so are more than ``MAX_XML_OUTSIDE_ROOT_NODES`` comments and
+ processing instructions outside the root."""
+ from lxml import etree
+
+ steps = outside = 0
+ path: list[str] = []
+ children: list[int] = []
+ unions: list[Optional[list[int]]] = []
+ with archive.open(name) as stream:
+ for event, element in etree.iterparse(
+ _CountedXmlStream(stream),
+ events=("start-ns", "start", "end", "comment", "pi"),
+ resolve_entities=False,
+ no_network=True,
+ ):
+ if event == "start-ns":
+ prefix, uri = element
+ if (
+ len(uri) > MAX_DOCX_NAMESPACE_URI_CHARS
+ or len(prefix) > MAX_DOCX_NAMESPACE_PREFIX_CHARS
+ ):
+ raise DecompressionBombError(
+ "header or footer declares a namespace URI of more "
+ f"than {MAX_DOCX_NAMESPACE_URI_CHARS} or a prefix of "
+ f"more than {MAX_DOCX_NAMESPACE_PREFIX_CHARS} "
+ "characters"
+ )
+ continue
+ if event == "end":
+ last = element[-1] if len(element) else None
+ trailing = element.text if last is None else last.tail
+ own = children.pop() + bool(trailing)
+ counter = unions.pop()
+ tag = path.pop()
+ if counter is not None:
+ steps += _union_steps(tag, counter, own)
+ elif not path:
+ if event == "start":
+ _refuse_dtd(element)
+ path.append(element.tag)
+ children.append(0)
+ unions.append([0, 0])
+ else:
+ # A comment or processing instruction outside the
+ # root.
+ outside = _note_outside_root_node(outside)
+ continue
+ else:
+ previous = element.getprevious()
+ text = (
+ element.getparent().text
+ if previous is None
+ else previous.tail
+ )
+ children[-1] += 1 + bool(text)
+ if event == "start":
+ tag = element.tag
+ if unions[-1] is not None:
+ _note_union_child(path[-1], tag, unions[-1])
+ path.append(tag)
+ children.append(0)
+ unions.append([0, 0] if tag in _W_UNION_PARENTS else None)
+ continue
+ # An ended element, comment or processing instruction: drop
+ # the siblings before it (tails are kept until then).
+ if event == "end":
+ element.clear(keep_tail=True)
+ parent = element.getparent()
+ if parent is not None:
+ while element.getprevious() is not None:
+ del parent[0]
+ return steps
+
+
+def _note_used_uris(
+ tag: str, attributes: list[str], declared: dict[str, int], used: set[str]
+) -> None:
+ """Add to *used* the namespace URIs in *declared* that the element
+ name *tag* and the *attributes* names (Clark notation) use."""
+ for name in (tag, *attributes):
+ if name[:1] == "{":
+ uri = name[1 : name.index("}")]
+ if uri in declared:
+ used.add(uri)
+
+
+class _OpenCell:
+ """A ``w:tc`` open in the block being read."""
+
+ __slots__ = (
+ "depth",
+ "span",
+ "read_span",
+ "continues",
+ "tc_pr",
+ "merge_read",
+ "span_read",
+ "nodes_before",
+ "start_nodes",
+ )
+
+ def __init__(self, depth: int, nodes_before: int, start_nodes: int) -> None:
+ self.depth = depth
+ # The largest w:gridSpan under any of its w:tcPr (the weight of
+ # its work, never less than python-docx's), and the span
+ # python-docx reads: the first w:gridSpan of its first w:tcPr.
+ self.span = 1
+ self.read_span = 1
+ # Whether it continues a vertical merge as python-docx reads it.
+ self.continues = False
+ # 0: no w:tcPr seen yet, 1: in its first, 2: past its first;
+ # and whether that first one's w:vMerge and w:gridSpan were read.
+ self.tc_pr = 0
+ self.merge_read = False
+ self.span_read = False
+ # Child and descendant nodes of its row before it.
+ self.nodes_before = nodes_before
+ # The block's node count when the cell started.
+ self.start_nodes = start_nodes
+
+
+class _OpenRow:
+ """A ``w:tr`` open in the block being read."""
+
+ __slots__ = (
+ "depth",
+ "padding",
+ "cells",
+ "count",
+ "columns",
+ "tr_pr",
+ "grid_before",
+ "before_read",
+ "nodes",
+ "others",
+ "gap",
+ "tr_pr_nodes",
+ "tr_pr_index",
+ )
+
+ def __init__(self, depth: int, table_row: bool, nodes: int) -> None:
+ self.depth = depth
+ # Its gridBefore + gridAfter columns (any w:trPr, negative ones
+ # pad nothing).
+ self.padding = 0
+ # For a row python-docx reads (a direct child of a table), per
+ # direct w:tc: (the span python-docx reads, whether it continues
+ # a vertical merge, the row's nodes before it).
+ self.cells: Optional[list[tuple[int, bool, int]]] = (
+ [] if table_row else None
+ )
+ # Direct w:tc children, and the columns they span (largest
+ # spans, at least one each).
+ self.count = 0
+ self.columns = 0
+ # 0: no w:trPr seen yet, 1: in its first, 2: past its first; and
+ # python-docx's grid_before (first w:gridBefore of the first
+ # w:trPr) once read.
+ self.tr_pr = 0
+ self.grid_before = 0
+ self.before_read = False
+ # The block's node count when the row started.
+ self.nodes = nodes
+ # Children other than w:tc elements (elements, comments and
+ # processing instructions; see MAX_DOCX_ROW_OTHER_CHILDREN).
+ self.others = 0
+ # For a row python-docx reads, its table's child nodes from the
+ # last such row before it (excluded) through it (included).
+ self.gap = 0
+ # The nodes in its first w:trPr (where grid_before is looked
+ # up), once that has ended, and its child nodes up to and
+ # including that w:trPr (0 if it has none).
+ self.tr_pr_nodes = 0
+ self.tr_pr_index = 0
+
+
+class _OpenTable:
+ """A ``w:tbl`` open in the block being read."""
+
+ __slots__ = (
+ "depth",
+ "largest_units",
+ "largest_text",
+ "above",
+ "others",
+ "row_children",
+ )
+
+ def __init__(self, depth: int) -> None:
+ self.depth = depth
+ # The largest cell so far that does not continue a merge (its
+ # run-work units and text bytes, times its span).
+ self.largest_units = 0
+ self.largest_text = 0
+ # The last row python-docx reads, as ``tc_at_grid_offset``
+ # searches it: {grid offset: (index of the cell found there,
+ # merge-step units of that cell if it continues a merge, else
+ # None)}, its cell count and its nodes.
+ self.above: Optional[
+ tuple[dict[int, tuple[int, Optional[int]]], int, int]
+ ] = None
+ # Children other than w:tr elements since the last w:tr child
+ # (elements, comments and processing instructions; see
+ # MAX_DOCX_TABLE_ROW_GAP), and its child nodes (text included)
+ # through the last w:tr child python-docx reads.
+ self.others = 0
+ self.row_children = 0
+
+
+def _note_docx_table_child(
+ depth: int,
+ tag: Optional[str],
+ tables: list[_OpenTable],
+ rows: list[_OpenRow],
+) -> None:
+ """Count a node starting at *depth* (an element named *tag*, or a
+ comment or processing instruction if None) among the children of
+ the open table or row it belongs to, refusing a row python-docx
+ reads with more than ``MAX_DOCX_ROW_OTHER_CHILDREN`` children other
+ than ``w:tc`` and a ``w:tr`` child of a table after more than
+ ``MAX_DOCX_TABLE_ROW_GAP`` other children since the last."""
+ if tables and tables[-1].depth == depth - 1:
+ table = tables[-1]
+ if tag != _W_TR:
+ table.others += 1
+ elif table.others > MAX_DOCX_TABLE_ROW_GAP:
+ raise DecompressionBombError(
+ "document has a table with more than "
+ f"{MAX_DOCX_TABLE_ROW_GAP} children before or between "
+ "its rows"
+ )
+ else:
+ table.others = 0
+ elif rows and rows[-1].depth == depth - 1 and tag != _W_TC:
+ row = rows[-1]
+ if row.cells is not None:
+ row.others += 1
+ if row.others > MAX_DOCX_ROW_OTHER_CHILDREN:
+ raise DecompressionBombError(
+ "document has a table row with more than "
+ f"{MAX_DOCX_ROW_OTHER_CHILDREN} children that are not "
+ "cells"
+ )
+
+
+def _docx_merge_steps(
+ row: _OpenRow,
+ row_cells: list[tuple[int, bool, int]],
+ table: _OpenTable,
+ nodes: int,
+ row_children: int,
+) -> int:
+ """Run-work units of python-docx's steps up vertical merges for
+ *row_cells*, the cells of *row* (which ends with the block's node
+ count at *nodes* and has *row_children* child nodes), and record
+ *row* on *table* as the row above the next.
+
+ A cell continuing a merge at grid offset O (``grid_before`` plus
+ the spans, as python-docx reads them, of the cells before it) takes
+ one step to the row above, where ``tc_at_grid_offset`` returns the
+ first cell starting exactly at O unless an earlier one starts after
+ O (it stops there); if that cell continues too, its own steps
+ follow. Each step is priced at the cells and nodes it walks (see
+ ``DOCX_MERGE_STEP_WEIGHT``): the row's nodes before the cell, its
+ children up to its first ``w:trPr`` (all of them if it has none)
+ and the nodes in that ``w:trPr`` (``grid_before``'s two ``find``
+ calls; nodes before the cell may be counted twice), the
+ table's children from the row above through this one
+ (``_tr_above``'s sibling walk) and the row above's nodes.
+ Without a row above, or a cell at O, python-docx raises after the
+ step, which is priced the same."""
+ walked = (row.tr_pr_index or row_children) + row.tr_pr_nodes + row.gap
+ above = table.above
+ found: dict[int, tuple[int, Optional[int]]] = {}
+ highest: Optional[int] = None
+ offset = row.grid_before
+ total = 0
+ for index, (span, continues, before) in enumerate(row_cells):
+ steps: Optional[int] = None
+ if continues:
+ if above is None:
+ steps = _merge_step(index, before + walked)
+ else:
+ cells_above, count_above, nodes_above = above
+ hit = cells_above.get(offset)
+ if hit is None:
+ steps = _merge_step(
+ index + count_above, before + walked + nodes_above
+ )
+ else:
+ steps = _merge_step(
+ index + hit[0], before + walked + nodes_above
+ )
+ if hit[1] is not None:
+ steps += hit[1]
+ steps = min(steps, _SATURATED)
+ total = min(total + steps, _SATURATED)
+ if highest is None or offset > highest:
+ found[offset] = (index, steps)
+ highest = offset
+ offset += span
+ table.above = (found, len(row_cells), nodes - row.nodes)
+ return total
+
+
+def _merge_step(cells: int, nodes: int) -> int:
+ """Run-work units of one step up a vertical merge that reads the
+ spans of *cells* cells and walks *nodes* nodes."""
+ return (
+ DOCX_MERGE_STEP_WEIGHT
+ + cells // DOCX_MERGE_CELLS_PER_UNIT
+ + nodes // DOCX_MERGE_NODES_PER_UNIT
+ )
+
+
+def _text_bytes(text: Optional[str]) -> int:
+ """UTF-8 size of *text* (0 for ``None``), as lxml stores it."""
+ if not text:
+ return 0
+ return len(text) if text.isascii() else len(text.encode("utf-8"))
+
+
+def _note_docx_grid_value(element, tag, path, cells, rows) -> None:
+ """Refuse a ``w:gridSpan``/``w:gridBefore``/``w:gridAfter`` whose
+ value python-docx cannot read or that exceeds
+ ``MAX_DOCX_GRID_SPAN`` (anywhere in ``document.xml``), and record
+ it on the open cell or row it belongs to: a ``w:gridSpan`` child of
+ a cell's ``w:tcPr`` (the largest, if several, and the one
+ python-docx reads), and ``gridBefore`` / ``gridAfter`` children of
+ a row's ``w:trPr`` (negative ones pad nothing; python-docx's
+ ``grid_before`` is the first ``gridBefore`` of the first
+ ``w:trPr``)."""
+ value = element.get(_W_VAL)
+ if value is None:
+ raise DecompressionBombError(
+ "document has a table grid value python-docx cannot read"
+ )
+ if len(value) > _MAX_DOCX_GRID_VALUE_CHARS:
+ # int() of a long digit string is not linear in its length.
+ raise DecompressionBombError(
+ "document has a table grid value of more than "
+ f"{_MAX_DOCX_GRID_VALUE_CHARS} characters"
+ )
+ try:
+ # python-docx converts the attribute with int() itself.
+ number = int(value)
+ except ValueError:
+ raise DecompressionBombError(
+ "document has a table grid value python-docx cannot read"
+ ) from None
+ if number > MAX_DOCX_GRID_SPAN:
+ raise DecompressionBombError(
+ f"document has a table cell spanning or skipping {number} grid "
+ f"columns (ceiling {MAX_DOCX_GRID_SPAN})"
+ )
+ depth = len(path)
+ if tag == _W_GRID_SPAN:
+ if cells and cells[-1].depth == depth - 2 and path[-2] == _W_TCPR:
+ cell = cells[-1]
+ cell.span = max(cell.span, number)
+ if cell.tc_pr == 1 and not cell.span_read:
+ cell.span_read = True
+ cell.read_span = number
+ elif rows and rows[-1].depth == depth - 2 and path[-2] == _W_TRPR:
+ row = rows[-1]
+ row.padding += max(number, 0)
+ if tag == _W_GRID_BEFORE and row.tr_pr == 1 and not row.before_read:
+ row.before_read = True
+ row.grid_before = number
+
+
+def _fold_docx_text_work(
+ tag, depth, own, frames, cells, tables, rows, nodes, extra=0
+) -> None:
+ """Add the element that ends at *depth* (with *own* child nodes;
+ the block has *nodes* nodes so far) to the run-work units and text
+ bytes of ``frames``: ``DOCX_RUN_WORK_ITEM_WEIGHT`` units for a run
+ (plus its children), row or cell (plus one per
+ ``DOCX_CELL_NODES_PER_UNIT`` of its descendant nodes); a row's
+ ``gridBefore`` and ``gridAfter`` columns and python-docx's steps up
+ the vertical merges its cells continue (``_docx_merge_steps``); and
+ an ending
+ cell's whole frame folded into its parent's, times its span, or,
+ for a cell continuing a vertical merge, plus the largest cell of its
+ table so far (python-docx yields the merge's first cell in its place
+ when unstructured reads ``row.cells``). A row spanning more than
+ ``MAX_DOCX_ROW_GRID_COLUMNS`` columns is refused."""
+ units = text = 0
+ if tag == _W_TC and cells and cells[-1].depth == depth:
+ cell = cells.pop()
+ units, text = frames.pop()
+ # Its descendant nodes, read once per yield (see
+ # DOCX_CELL_NODES_PER_UNIT).
+ units += (
+ DOCX_RUN_WORK_ITEM_WEIGHT
+ + (nodes - cell.start_nodes) // DOCX_CELL_NODES_PER_UNIT
+ + extra
+ )
+ extra = 0
+ if rows and rows[-1].depth == depth - 1:
+ row = rows[-1]
+ row.columns += max(cell.span, 1)
+ if row.cells is not None:
+ row.cells.append(
+ (cell.read_span, cell.continues, cell.nodes_before)
+ )
+ if cell.continues:
+ if tables:
+ units += tables[-1].largest_units
+ text += tables[-1].largest_text
+ else:
+ span = max(cell.span, 1)
+ units = min(units * span, _SATURATED)
+ text = min(text * span, _SATURATED)
+ if tables:
+ table = tables[-1]
+ table.largest_units = max(table.largest_units, units)
+ table.largest_text = max(table.largest_text, text)
+ elif tag == _W_R:
+ units = DOCX_RUN_WORK_ITEM_WEIGHT + own
+ elif tag == _W_TR:
+ units = DOCX_RUN_WORK_ITEM_WEIGHT
+ if rows and rows[-1].depth == depth:
+ row = rows.pop()
+ if row.padding + row.columns > MAX_DOCX_ROW_GRID_COLUMNS:
+ raise DecompressionBombError(
+ "document has a table row spanning more than "
+ f"{MAX_DOCX_ROW_GRID_COLUMNS} grid columns"
+ )
+ units += -(-row.padding // DOCX_GRID_PADDING_PER_RUN_WORK_UNIT)
+ # A row python-docx reads is a direct child of tables[-1].
+ if row.cells is not None and tables:
+ units += _docx_merge_steps(
+ row, row.cells, tables[-1], nodes, own
+ )
+ elif tag == _W_TRPR and rows and rows[-1].depth == depth - 1:
+ row = rows[-1]
+ if row.tr_pr == 1:
+ # Its first w:trPr ends: the nodes in it.
+ row.tr_pr_nodes += nodes
+ elif tag == _W_TBL and tables and tables[-1].depth == depth:
+ tables.pop()
+ frame = frames[-1]
+ frame[0] = min(frame[0] + units + extra, _SATURATED)
+ frame[1] = min(frame[1] + text, _SATURATED)
+
+
+def _docx_skeleton_entries(
+ archive: zipfile.ZipFile,
+ rels: dict[str, tuple[str, Optional[str]]],
+ reltype: str,
+ ceiling: int,
+ what: str,
+ types: _ContentTypes,
+ allowed: frozenset[str],
+) -> tuple[int, int]:
+ """Hold the document part's *reltype* target (the settings or the
+ styles part) to the skeleton treatment, and return the children of
+ its root and their attributes ((0, 0) if there is none).
+
+ python-docx resolves both parts through the document part's
+ relationship of that type (and makes a small default one when there
+ is none). unstructured reads ``settings.odd_and_even_pages_header_footer``
+ twice per section, each a search of the settings root's children,
+ and a paragraph's style about four times per paragraph, each a
+ Python loop over the styles root's ``w:style`` children that reads
+ two attributes of each (see ``MAX_DOCX_STYLE_WORK``). Every internal
+ relationship of *reltype* whose target is in the archive is parsed
+ (``MAX_OPC_SKELETON_PART_BYTES``, DTD refused) and refused if its
+ root has more than *ceiling* children (elements, comments and
+ processing instructions). More than one such relationship makes
+ python-docx fail; checking each, and returning the largest, is
+ simply conservative. Each must have the content type in *allowed*
+ (see ``_require_content_type``): python-docx builds a document part
+ from a styles or settings target typed as one, whose own styles or
+ settings it then reads instead."""
+ largest = (0, 0)
+ for rel_type, target in rels.values():
+ if rel_type != reltype or target is None:
+ continue
+ root = _skeleton_xml(archive, target[1:])
+ if root is None:
+ continue
+ _require_content_type(types, target, allowed, what)
+ if len(root) > ceiling:
+ raise DecompressionBombError(
+ f"document {what} part has {len(root)} entries "
+ f"(ceiling {ceiling})"
+ )
+ attributes = sum(
+ len(child.attrib) for child in root if isinstance(child.tag, str)
+ )
+ largest = (
+ max(largest[0], len(root)),
+ max(largest[1], attributes),
+ )
+ return largest
diff --git a/src/local_deep_research/utilities/office_conversion.py b/src/local_deep_research/utilities/office_conversion.py
new file mode 100644
index 0000000000..00dff59687
--- /dev/null
+++ b/src/local_deep_research/utilities/office_conversion.py
@@ -0,0 +1,231 @@
+"""Bounded conversion of legacy office formats (.doc/.ppt).
+
+``.doc``/``.ppt`` uploads are OLE binaries; the loader path converts
+them to modern containers via a ``soffice`` subprocess before parsing.
+The upstream conversion (unstructured's ``convert_office_doc``) invokes
+``soffice`` with **no timeout**, so a hostile or pathological file can
+pin an indexing worker forever — for content up to the 3 GB upload cap.
+
+This module owns the conversion instead: only input carrying the OLE
+compound-file signature is handed to soffice, a real wall-clock timeout
+enforced with a process-group kill (``soffice`` spawns children that a
+bare ``subprocess.run(timeout=...)`` would leave alive), typed
+failures, output validation (expected file, size ceiling), soffice's
+stdio sent to ``/dev/null`` rather than buffered, a per-call
+``UserInstallation`` profile so concurrent conversions cannot collide
+on soffice's singleton profile lock, and full temp cleanup in
+``finally``. soffice's memory is not capped (it is bounded by the
+timeout only); the OLE-signature check keeps renamed zip containers
+and other formats from reaching it.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import shutil
+import signal
+import subprocess
+import tempfile
+import uuid
+from pathlib import Path
+from typing import Optional
+
+from loguru import logger
+
+#: Legacy extensions -> the modern container soffice produces.
+_LEGACY_TARGETS = {".doc": ".docx", ".ppt": ".pptx"}
+
+#: OLE compound-file signature: every genuine .doc/.ppt starts with it.
+OLE_MAGIC = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1"
+
+#: soffice binary candidates, resolved once per call via shutil.which.
+_SOFFICE_CANDIDATES = ("soffice", "libreoffice")
+
+#: Conversion wall clock. Generous for real documents (a 3 GB file is
+#: rejected by the upload cap long before this; honest conversions of
+#: large-but-legitimate documents finish in tens of seconds) while
+#: keeping a hung process tree from pinning a worker forever.
+DEFAULT_CONVERSION_TIMEOUT_S = 120
+
+#: Converted-output ceiling. A conversion that legitimately needs more
+#: than this was never going to be indexed usefully.
+DEFAULT_MAX_OUTPUT_BYTES = 512 * 1024 * 1024
+
+
+class OfficeConversionError(ValueError):
+ """A legacy-office conversion failed, timed out, or was refused."""
+
+
+def _normalized_ext(extension: str) -> str:
+ return (
+ extension.lower()
+ if extension.startswith(".")
+ else f".{extension.lower()}"
+ )
+
+
+def _kill_process_group(pid: int) -> None:
+ """Best-effort SIGKILL of *pid*'s whole process group.
+
+ On platforms without process groups (Windows) this falls back to
+ terminating *pid* alone: soffice's helper processes survive there.
+ """
+ with contextlib.suppress(ProcessLookupError, PermissionError):
+ if hasattr(os, "killpg"):
+ os.killpg(pid, signal.SIGKILL)
+ else: # pragma: no cover - Windows has no process groups
+ os.kill(pid, signal.SIGTERM)
+
+
+def convert_legacy_office_bytes(
+ content: bytes,
+ extension: str,
+ *,
+ output_dir: Optional[Path] = None,
+ timeout_s: int = DEFAULT_CONVERSION_TIMEOUT_S,
+ max_output_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,
+ input_stem: Optional[str] = None,
+) -> bytes:
+ """Convert legacy OLE office bytes to their modern container.
+
+ Returns the converted container's bytes. Raises
+ ``OfficeConversionError`` (a ``ValueError``) on timeout, non-zero
+ exit, missing/unexpected output, or an output over
+ ``max_output_bytes``. All temporary files are removed whether the
+ conversion succeeds or fails.
+ """
+ ext = _normalized_ext(extension)
+ target = _LEGACY_TARGETS.get(ext)
+ if target is None:
+ raise OfficeConversionError(f"not a legacy office extension: {ext}")
+
+ # soffice sniffs content, not the extension: anything else renamed
+ # .doc/.ppt (a zip bomb, an RTF, an HTML page) would reach a filter
+ # outside every other guard, with no memory cap on soffice. Only
+ # the OLE compound files these extensions denote are converted.
+ if not content.startswith(OLE_MAGIC):
+ raise OfficeConversionError(f"{ext} upload is not an OLE compound file")
+
+ soffice = next(
+ (name for name in _SOFFICE_CANDIDATES if shutil.which(name)), None
+ )
+ if soffice is None:
+ raise OfficeConversionError("soffice binary not available")
+
+ # mkdtemp is absolute by construction; a caller-supplied output_dir
+ # may be relative, which would break profile_dir.as_uri() below.
+ work_dir = (
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: mkdtemp creates a private server-owned directory
+ Path(tempfile.mkdtemp(prefix="ldr-office-"))
+ if output_dir is None
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: upload caller omits this optional trusted-code path
+ else Path(output_dir).resolve()
+ )
+
+ if input_stem is None:
+ # nosemgrep: semgrep.rules.sql-string-concatenation, reason: validated local filename stem; no SQL sink
+ stem = f"in_{uuid.uuid4().hex}"
+ elif input_stem and all(c.isalnum() or c in "-_" for c in input_stem):
+ stem = input_stem
+ else:
+ # A traversal-shaped stem must never escape the work dir.
+ raise OfficeConversionError("invalid conversion input stem")
+
+ in_path = work_dir / f"{stem}{ext}"
+ out_path = work_dir / f"{stem}{target}"
+ # Per-call profile: soffice serializes on a shared UserInstallation
+ # and concurrent conversions would block or corrupt each other.
+ profile_dir = work_dir / f"profile_{uuid.uuid4().hex}"
+
+ try:
+ in_path.write_bytes(content)
+ # Defensive pre-clean: a stale file at out_path from an earlier
+ # call in a shared output_dir must not fake a successful run.
+ out_path.unlink(missing_ok=True)
+
+ command = [
+ soffice,
+ "--headless",
+ "--norestore",
+ "--nolockcheck",
+ f"-env:UserInstallation={profile_dir.as_uri()}",
+ "--convert-to",
+ target.lstrip("."),
+ "--outdir",
+ str(work_dir),
+ str(in_path),
+ ]
+ try:
+ proc = subprocess.Popen( # noqa: S603 fixed argv, no shell
+ command,
+ # Nothing is read from soffice's streams: /dev/null
+ # keeps a chatty or hostile conversion from growing
+ # an in-memory pipe buffer in the worker.
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ try:
+ proc.communicate(timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ # start_new_session makes proc.pid the process-group
+ # id: kill the whole tree, then reap, then fail typed.
+ _kill_process_group(proc.pid)
+ proc.wait()
+ raise OfficeConversionError(
+ f"legacy office conversion timed out after {timeout_s}s"
+ ) from None
+ except OfficeConversionError:
+ raise
+ except OSError as exc:
+ raise OfficeConversionError(
+ f"could not launch soffice ({type(exc).__name__})"
+ ) from exc
+
+ if proc.returncode != 0:
+ raise OfficeConversionError(
+ f"legacy office conversion failed (exit {proc.returncode})"
+ )
+
+ if not out_path.exists():
+ raise OfficeConversionError(
+ "legacy office conversion produced no output"
+ )
+
+ output_size = out_path.stat().st_size
+ if output_size > max_output_bytes:
+ raise OfficeConversionError(
+ f"converted output is larger than {max_output_bytes} bytes"
+ )
+
+ converted = out_path.read_bytes()
+ logger.debug(
+ "legacy office conversion ok: {} -> {} ({} bytes)",
+ ext,
+ target,
+ output_size,
+ )
+ return converted
+ finally:
+ # Full temp hygiene on every path, success or failure: the
+ # caller's content, soffice's output, and the profile tree.
+ for path in (in_path, out_path):
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ logger.warning("could not remove conversion temp file")
+ shutil.rmtree(profile_dir, ignore_errors=True)
+ if output_dir is None:
+ shutil.rmtree(work_dir, ignore_errors=True)
+
+
+def is_legacy_office_extension(extension: str) -> bool:
+ """True when *extension* is one of the OLE formats needing conversion."""
+ return _normalized_ext(extension) in _LEGACY_TARGETS
+
+
+def converted_extension(extension: str) -> str:
+ """The modern container extension a legacy *extension* converts to."""
+ return _LEGACY_TARGETS[_normalized_ext(extension)]
diff --git a/src/local_deep_research/utilities/pandoc_conversion.py b/src/local_deep_research/utilities/pandoc_conversion.py
new file mode 100644
index 0000000000..d7d5b6727b
--- /dev/null
+++ b/src/local_deep_research/utilities/pandoc_conversion.py
@@ -0,0 +1,354 @@
+"""Bounded pandoc conversion for pandoc-backed uploads.
+
+Five upload formats convert through a ``pandoc`` subprocess before
+parsing: ``.rtf``/``.epub``/``.rst``/``.org`` through unstructured's
+``convert_file_to_html_text_using_pandoc`` and ``.odt`` through
+``partition_odt`` (odt -> docx), both ending in
+``pypandoc.convert_file`` -> ``Popen(...)`` + ``communicate()`` with
+**no timeout and no memory cap** — a hostile or pathological file pins
+an indexing worker indefinitely or grows pandoc's heap without limit.
+
+This module owns the conversion instead:
+
+- the binary is resolved the way pypandoc resolves it (the bundled
+ ``pypandoc-binary`` copy first), falling back to ``pandoc`` on PATH;
+- a wall-clock timeout enforced with a process-group kill (mirroring
+ the soffice wrapper in ``utilities/office_conversion.py``);
+- a memory cap on the pandoc child: a GHC RTS heap ceiling
+ (``+RTS -M<N>m -RTS``) when the binary accepts RTS options, otherwise
+ ``RLIMIT_AS`` in the child on Linux;
+- a ``--sandbox``ed argv with pandoc writing to an output file, whose
+ size is checked before it is read; pandoc's stdout/stderr go to
+ ``/dev/null`` so no diagnostic stream is buffered in the worker;
+- typed failures and full temp cleanup in ``finally``.
+
+Every extension converts straight to HTML, which the ``.html`` loader
+then parses.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import functools
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+from typing import Any, Callable, NamedTuple, Optional
+
+from loguru import logger
+
+try: # POSIX only; imported here so the forked child imports nothing.
+ import resource
+except ImportError: # pragma: no cover - Windows
+ resource = None # type: ignore[assignment]
+
+#: Every upload extension whose registered loader converts through
+#: pandoc; all of them are routed through this bounded wrapper instead.
+#: (.docx/.pptx/.xlsx are parsed in-process by python-docx/-pptx/
+#: openpyxl and never reach pandoc.)
+PANDOC_BACKED_EXTENSIONS = frozenset({".rtf", ".epub", ".rst", ".org", ".odt"})
+
+#: Conversion wall clock: real conversions of ordinary documents are
+#: sub-second to a few seconds; generous headroom keeps
+#: pathological-but-honest inputs from failing while a hung pandoc tree
+#: cannot outlive the worker's patience.
+DEFAULT_CONVERSION_TIMEOUT_S = 90
+
+#: Converted-HTML ceiling: extraction only needs text, and a larger
+#: "HTML" output signals amplification, not a real document.
+DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024 * 1024
+
+#: pandoc heap ceiling in MiB. Measured with the bundled pandoc 3.9,
+#: peak RSS is roughly 100-120x the document's text size (1 MB of rst
+#: -> ~200 MB, 5 MB -> ~570 MB), and 20 MB of text needs ~2 GB *and*
+#: more than the 90 s timeout. 2 GiB therefore admits what the timeout
+#: admits, while a decompression bomb (pandoc's zip reader does not
+#: trust declared entry sizes) becomes a prompt, typed failure instead
+#: of an OOM of the host.
+DEFAULT_MAX_HEAP_MB = 2048
+
+#: Extra address space granted over the heap ceiling when the cap has
+#: to be enforced with RLIMIT_AS (code, RTS bookkeeping, mmaps).
+_RLIMIT_AS_HEADROOM_MB = 512
+
+#: GHC runtimes exit with this status on "Heap exhausted" (and on
+#: "out of memory" when RLIMIT_AS refuses an allocation).
+_GHC_HEAP_EXHAUSTED_EXIT = 251
+
+#: How long a *failed* RTS probe is remembered before it is retried.
+#: Successes are remembered for the life of the process; failures
+#: (including a timed-out probe on a loaded host) are retried, but at
+#: most once per window so a broken binary does not add a probe to
+#: every conversion.
+_RTS_PROBE_FAILURE_TTL_S = 300.0
+
+#: Timeout of one RTS probe (``pandoc +RTS -M64m -RTS --version``).
+_RTS_PROBE_TIMEOUT_S = 30
+
+#: binary path -> (probe succeeded, time.monotonic() of the probe)
+_rts_probe_cache: dict[str, tuple[bool, float]] = {}
+
+
+class PandocConversionError(ValueError):
+ """A pandoc conversion failed, timed out, or was refused."""
+
+
+def _kill_process_group(pid: int) -> None:
+ """Best-effort SIGKILL of *pid*'s whole process group.
+
+ On platforms without process groups (Windows) this falls back to
+ terminating *pid* alone: grandchildren pandoc spawned survive there.
+ """
+ with contextlib.suppress(ProcessLookupError, PermissionError):
+ if hasattr(os, "killpg"):
+ os.killpg(pid, signal.SIGKILL)
+ else: # pragma: no cover - Windows has no process groups
+ os.kill(pid, signal.SIGTERM)
+
+
+def _normalized_ext(extension: str) -> str:
+ return (
+ extension.lower()
+ if extension.startswith(".")
+ else f".{extension.lower()}"
+ )
+
+
+def is_pandoc_backed_extension(extension: str) -> bool:
+ """True when *extension*'s loader path converts through pandoc."""
+ return _normalized_ext(extension) in PANDOC_BACKED_EXTENSIONS
+
+
+def resolve_pandoc_binary() -> Optional[str]:
+ """Locate the pandoc binary the way the rest of the app does.
+
+ The shipped dependency is ``pypandoc-binary``, which bundles pandoc
+ inside the package (``pypandoc/files/pandoc``) and puts nothing on
+ PATH, so ``pypandoc.get_pandoc_path()`` is the primary resolver
+ (it also honours ``PYPANDOC_PANDOC`` and picks the newest of the
+ bundled and PATH copies). ``shutil.which`` is the fallback for
+ installs without pypandoc.
+ """
+ try:
+ import pypandoc
+
+ path = pypandoc.get_pandoc_path()
+ if path:
+ return str(path)
+ except (ImportError, OSError, RuntimeError):
+ pass
+ return shutil.which("pandoc")
+
+
+def _probe_rts_heap_cap(pandoc: str) -> bool:
+ """Run one ``+RTS -M`` probe against *pandoc* (uncached)."""
+ try:
+ probe = subprocess.run( # noqa: S603 fixed argv, no shell
+ [pandoc, "+RTS", "-M64m", "-RTS", "--version"],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ timeout=_RTS_PROBE_TIMEOUT_S,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return False
+ return probe.returncode == 0
+
+
+def _pandoc_accepts_rts_heap_cap(pandoc: str) -> bool:
+ """Whether *pandoc* honours ``+RTS -M``.
+
+ Official pandoc builds (including the one pypandoc-binary bundles)
+ link with ``-rtsopts``; a build without it exits non-zero with
+ "Most RTS options are disabled". A success is cached for the
+ process; a failure only for ``_RTS_PROBE_FAILURE_TTL_S``, so a
+ transient failure (e.g. a probe timing out under load) does not
+ pin the process to the fallback cap for good.
+ """
+ now = time.monotonic()
+ cached = _rts_probe_cache.get(pandoc)
+ if cached is not None:
+ ok, probed_at = cached
+ if ok or now - probed_at < _RTS_PROBE_FAILURE_TTL_S:
+ return ok
+ ok = _probe_rts_heap_cap(pandoc)
+ _rts_probe_cache[pandoc] = (ok, now)
+ return ok
+
+
+def _set_address_space_limit(limit_bytes: int) -> None:
+ """Runs in the forked child before exec: ``setrlimit`` and nothing
+ else (``resource`` is imported by the parent at module load)."""
+ resource.setrlimit(resource.RLIMIT_AS, (limit_bytes, limit_bytes))
+
+
+class _MemoryCap(NamedTuple):
+ rts_args: list[str]
+ preexec_fn: Optional[Callable[[], None]]
+ #: Human-readable effective limit, used in the failure message.
+ description: str
+
+
+def _memory_cap(pandoc: str, max_heap_mb: int) -> _MemoryCap:
+ """Return how pandoc's memory is capped for this binary.
+
+ Preferred: a GHC RTS heap ceiling on the argv — no Python code runs
+ in the forked child, so it is safe in this multi-threaded server.
+ Fallback for binaries without ``-rtsopts``: ``RLIMIT_AS`` of the
+ heap ceiling plus ``_RLIMIT_AS_HEADROOM_MB`` set in a
+ ``preexec_fn`` that does nothing else; Linux only, since macOS does
+ not enforce RLIMIT_AS and Windows has neither mechanism.
+
+ A probe that wrongly reports RTS support (the binary then rejects
+ ``+RTS``) costs availability only: the conversion fails typed and
+ pandoc never runs uncapped.
+ """
+ if _pandoc_accepts_rts_heap_cap(pandoc):
+ return _MemoryCap(
+ ["+RTS", f"-M{max_heap_mb}m", "-RTS"],
+ None,
+ f"{max_heap_mb} MiB heap cap",
+ )
+ if resource is not None and sys.platform.startswith("linux"):
+ limit_mb = max_heap_mb + _RLIMIT_AS_HEADROOM_MB
+ return _MemoryCap(
+ [],
+ functools.partial(_set_address_space_limit, limit_mb * 1024 * 1024),
+ f"{limit_mb} MiB address-space limit "
+ f"({max_heap_mb} MiB heap + {_RLIMIT_AS_HEADROOM_MB} MiB "
+ "headroom)",
+ )
+ logger.warning(
+ "pandoc rejects RTS options and RLIMIT_AS is unavailable on this "
+ "platform; pandoc conversions are bounded by the timeout only"
+ )
+ return _MemoryCap([], None, "no memory cap")
+
+
+def pandoc_convert_bytes_to_html(
+ content: bytes,
+ extension: str,
+ *,
+ work_dir: Optional[Path] = None,
+ timeout_s: int = DEFAULT_CONVERSION_TIMEOUT_S,
+ max_output_bytes: int = DEFAULT_MAX_OUTPUT_BYTES,
+ max_heap_mb: int = DEFAULT_MAX_HEAP_MB,
+) -> bytes:
+ """Convert a pandoc-backed document to HTML bytes, bounded.
+
+ Returns the converted HTML. Raises ``PandocConversionError`` (a
+ ``ValueError``) on timeout, launch failure, memory-cap breach,
+ non-zero exit, missing output, or output over ``max_output_bytes``.
+ All temporary files are removed whether the conversion succeeds or
+ fails.
+ """
+ ext = _normalized_ext(extension)
+ if ext not in PANDOC_BACKED_EXTENSIONS:
+ raise PandocConversionError(f"not a pandoc-backed extension: {ext}")
+
+ pandoc = resolve_pandoc_binary()
+ if pandoc is None:
+ raise PandocConversionError("pandoc binary not available")
+
+ cap = _memory_cap(pandoc, max_heap_mb)
+
+ owned_dir = work_dir is None
+ scratch = (
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: mkdtemp creates a private server-owned directory
+ Path(tempfile.mkdtemp(prefix="ldr-pandoc-"))
+ if owned_dir
+ # nosemgrep: semgrep.rules.path-traversal-risk, reason: upload caller omits this optional trusted-code path
+ else Path(work_dir).resolve()
+ )
+ in_path = scratch / f"in_doc{ext}"
+ out_path = scratch / "out.html"
+
+ try:
+ in_path.write_bytes(content)
+ out_path.unlink(missing_ok=True)
+
+ # --sandbox restricts pandoc's own file access (same posture
+ # as pypandoc's sandbox=True); output goes to a file so the
+ # size ceiling can be checked before anything is read, and
+ # --quiet plus /dev/null keeps warning floods out of memory.
+ command = [
+ pandoc,
+ *cap.rts_args,
+ "--sandbox",
+ "--quiet",
+ "--from",
+ ext.lstrip("."),
+ "--to",
+ "html",
+ "-o",
+ str(out_path),
+ str(in_path),
+ ]
+ popen_kwargs: dict[str, Any] = {}
+ if cap.preexec_fn is not None:
+ popen_kwargs["preexec_fn"] = cap.preexec_fn
+ try:
+ proc = subprocess.Popen( # noqa: S603 fixed argv, no shell
+ command,
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ **popen_kwargs,
+ )
+ try:
+ proc.communicate(timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ # start_new_session makes proc.pid the process-group
+ # id: kill the whole tree, then reap, then fail typed.
+ _kill_process_group(proc.pid)
+ proc.wait()
+ raise PandocConversionError(
+ f"pandoc conversion timed out after {timeout_s}s"
+ ) from None
+ except PandocConversionError:
+ raise
+ except (OSError, subprocess.SubprocessError) as exc:
+ raise PandocConversionError(
+ f"could not launch pandoc ({type(exc).__name__})"
+ ) from exc
+
+ if proc.returncode == _GHC_HEAP_EXHAUSTED_EXIT:
+ raise PandocConversionError(
+ f"pandoc conversion ran out of memory ({cap.description})"
+ )
+ if proc.returncode != 0:
+ raise PandocConversionError(
+ f"pandoc conversion failed (exit {proc.returncode})"
+ )
+
+ if not out_path.exists():
+ raise PandocConversionError("pandoc conversion produced no output")
+
+ output_size = out_path.stat().st_size
+ if output_size > max_output_bytes:
+ raise PandocConversionError(
+ f"converted output is larger than {max_output_bytes} bytes"
+ )
+
+ converted = out_path.read_bytes()
+ logger.debug(
+ "pandoc conversion ok: {} -> html ({} bytes)",
+ ext,
+ output_size,
+ )
+ return converted
+ finally:
+ for path in (in_path, out_path):
+ try:
+ path.unlink(missing_ok=True)
+ except OSError:
+ logger.warning("could not remove conversion temp file")
+ if owned_dir:
+ shutil.rmtree(scratch, ignore_errors=True)
diff --git a/tests/document_loaders/test_loader_registry_full_coverage.py b/tests/document_loaders/test_loader_registry_full_coverage.py
index db0cd97e91..a4dfa7a327 100644
--- a/tests/document_loaders/test_loader_registry_full_coverage.py
+++ b/tests/document_loaders/test_loader_registry_full_coverage.py
@@ -114,15 +114,17 @@ class TestConditionalLoaderRegistration:
assert isinstance(HAS_IMAGE_LOADER, bool)
def test_odt_in_registry_iff_flag_and_dep(self):
- # ODT needs both the loader class and python-docx (the partitioner
- # imports python-docx and shells out to pandoc).
+ # ODT uploads convert through the bounded pandoc wrapper, so ODT
+ # is gated on the pandoc bridge like EPUB/RTF/RST/Org.
from local_deep_research.document_loaders.loader_registry import (
- HAS_DOCX_DEP,
HAS_ODT_LOADER,
+ HAS_PANDOC_DEP,
LOADER_REGISTRY,
)
- assert (".odt" in LOADER_REGISTRY) == (HAS_ODT_LOADER and HAS_DOCX_DEP)
+ assert (".odt" in LOADER_REGISTRY) == (
+ HAS_ODT_LOADER and HAS_PANDOC_DEP
+ )
def test_epub_in_registry_iff_flag_and_dep(self):
from local_deep_research.document_loaders.loader_registry import (
diff --git a/tests/document_loaders/test_office_format_extraction.py b/tests/document_loaders/test_office_format_extraction.py
index aa7663ef36..dd287d4587 100644
--- a/tests/document_loaders/test_office_format_extraction.py
+++ b/tests/document_loaders/test_office_format_extraction.py
@@ -55,8 +55,7 @@ class TestOfficeExtensionsRegistered:
and (mod.HAS_DOCX_DEP if ext == ".doc" else mod.HAS_PPTX_DEP)
)
- def test_odt_registered_when_docx_and_pandoc_present(self):
- pytest.importorskip("docx")
+ def test_odt_registered_when_pandoc_present(self):
pytest.importorskip("pypandoc")
from local_deep_research.document_loaders.loader_registry import (
@@ -284,13 +283,24 @@ class TestHonestDetection:
monkeypatch.setattr(importlib_util, "find_spec", fake_find_spec)
return _reload(REGISTRY_MODULE)
- def test_missing_python_docx_hides_word_and_odt(
- self, monkeypatch, restore_module
- ):
+ def test_missing_python_docx_hides_word(self, monkeypatch, restore_module):
reloaded = self._reload_without(monkeypatch, {"docx"})
assert reloaded.HAS_DOCX_DEP is False
- for ext in (".doc", ".docx", ".odt"):
+ for ext in (".doc", ".docx"):
+ assert ext not in reloaded.LOADER_REGISTRY
+ # ODT converts through pandoc, not python-docx.
+ assert (".odt" in reloaded.LOADER_REGISTRY) == (
+ reloaded.HAS_ODT_LOADER and reloaded.HAS_PANDOC_DEP
+ )
+
+ def test_missing_pypandoc_hides_every_pandoc_format(
+ self, monkeypatch, restore_module
+ ):
+ reloaded = self._reload_without(monkeypatch, {"pypandoc"})
+
+ assert reloaded.HAS_PANDOC_DEP is False
+ for ext in (".odt", ".epub", ".rtf", ".rst", ".org"):
assert ext not in reloaded.LOADER_REGISTRY
def test_missing_pptx_hides_powerpoint(self, monkeypatch, restore_module):
diff --git a/tests/security/test_eml_attachments_not_partitioned.py b/tests/security/test_eml_attachments_not_partitioned.py
new file mode 100644
index 0000000000..81a94ba89f
--- /dev/null
+++ b/tests/security/test_eml_attachments_not_partitioned.py
@@ -0,0 +1,146 @@
+"""Email uploads index the message body only, never its attachments.
+
+unstructured's ``partition_email`` (and ``partition_msg``, which
+``UnstructuredEmailLoader`` dispatches to when the content sniffs as an
+Outlook .msg) default to ``process_attachments=True`` and hand every
+attachment to ``unstructured.partition.auto.partition``. That recursion runs
+outside ``load_from_bytes`` and therefore outside every bound this module
+family adds: a .doc/.ppt attachment reaches soffice with no timeout, an
+.rtf/.rst/.org/.odt/.epub attachment reaches ``pypandoc.convert_file`` with
+no timeout or heap cap, and a .docx/.pptx/.xlsx attachment reaches its parser
+without the zip-container guard. The registry therefore passes
+``process_attachments=False`` for ``.eml``.
+"""
+
+from __future__ import annotations
+
+import io
+import struct
+from email.message import EmailMessage
+from unittest.mock import patch
+
+import pytest
+
+BODY_MARKER = "BODYMARKER quarterly numbers attached"
+
+
+def _minimal_ole_doc() -> bytes:
+ """A minimal well-formed CFB file holding a ``WordDocument`` stream.
+
+ unstructured's file-type sniffer opens the compound file and classifies
+ it as a legacy .doc by that stream name, routing it to ``partition_doc``
+ and from there to ``convert_office_doc`` (soffice).
+ """
+ end, free, fatsect = 0xFFFFFFFE, 0xFFFFFFFF, 0xFFFFFFFD
+ header = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" + b"\x00" * 16
+ header += struct.pack("<HHHHH", 0x3E, 3, 0xFFFE, 9, 6) + b"\x00" * 6
+ header += struct.pack("<IIIIIIIII", 0, 1, 1, 0, 4096, end, 0, end, 0)
+ header += struct.pack("<I", 0) + struct.pack("<I", free) * 108
+ # FAT: sector 0 is the FAT, 1 the directory, 2-9 the 4096-byte stream.
+ fat = [fatsect, end, *range(3, 10), end]
+ fat += [free] * (128 - len(fat))
+
+ def entry(name: str, kind: int, child: int, start: int, size: int):
+ raw = (name + "\x00").encode("utf-16-le")
+ return (
+ raw.ljust(64, b"\x00")
+ + struct.pack("<HBB", len(raw), kind, 1)
+ + struct.pack("<III", free, free, child)
+ + b"\x00" * 36
+ + struct.pack("<II", start, size)
+ + b"\x00" * 4
+ )
+
+ unused = b"\x00" * 64 + struct.pack("<HBBIII", 0, 0, 0, free, free, free)
+ unused += b"\x00" * 48
+ directory = (
+ entry("Root Entry", 5, 1, end, 0)
+ + entry("WordDocument", 2, free, 2, 4096)
+ + unused * 2
+ )
+ return header + struct.pack("<128I", *fat) + directory + b"\x00" * 4096
+
+
+def _docx_bytes() -> bytes:
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ document.add_paragraph("DOCXATTACHMENT")
+ buf = io.BytesIO()
+ document.save(buf)
+ return buf.getvalue()
+
+
+def _eml(attachment: bytes, subtype: str, filename: str) -> bytes:
+ msg = EmailMessage()
+ msg["From"] = "[email protected]"
+ msg["To"] = "[email protected]"
+ msg["Subject"] = "Report"
+ msg.set_content(BODY_MARKER)
+ msg.add_attachment(
+ attachment, maintype="application", subtype=subtype, filename=filename
+ )
+ return msg.as_bytes()
+
+
+class _Called(AssertionError):
+ pass
+
+
+def test_registry_disables_attachment_processing():
+ from local_deep_research.document_loaders.loader_registry import (
+ LOADER_REGISTRY,
+ )
+
+ assert (
+ LOADER_REGISTRY[".eml"]["loader_kwargs"].get("process_attachments")
+ is False
+ )
+
+
[email protected]("kind", ["rtf", "doc", "docx"])
+def test_attachment_converters_and_parsers_never_run(kind):
+ """Each attachment type reaches its unbounded converter on revert."""
+ pytest.importorskip("unstructured.partition.email")
+ pypandoc = pytest.importorskip("pypandoc")
+ docx = pytest.importorskip("docx")
+ udoc = pytest.importorskip("unstructured.partition.doc")
+ utext = pytest.importorskip("unstructured.partition.text")
+
+ from local_deep_research.document_loaders.bytes_loader import (
+ load_from_bytes,
+ )
+
+ attachments = {
+ "rtf": (b"{\\rtf1\\ansi RTFATTACHMENT}", "rtf", "notes.rtf"),
+ "doc": (_minimal_ole_doc(), "msword", "legacy.doc"),
+ "docx": (
+ _docx_bytes(),
+ "vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "modern.docx",
+ ),
+ }
+ payload = _eml(*attachments[kind])
+
+ calls: list[str] = []
+
+ def _record(name):
+ def _spy(*_a, **_k):
+ calls.append(name)
+ raise _Called(f"{name} was called for an email attachment")
+
+ return _spy
+
+ with (
+ # Classification is unrelated to attachment dispatch and would
+ # otherwise install a spaCy model in the test environment.
+ patch.object(utext, "is_possible_narrative_text", return_value=True),
+ patch.object(pypandoc, "convert_file", _record("convert_file")),
+ patch.object(udoc, "convert_office_doc", _record("convert_office_doc")),
+ patch.object(docx, "Document", _record("docx.Document")),
+ ):
+ docs = load_from_bytes(payload, ".eml", "report.eml")
+
+ assert calls == []
+ text = "\n".join(d.page_content for d in docs)
+ assert BODY_MARKER in text
+ assert "ATTACHMENT" not in text
diff --git a/tests/security/test_legacy_office_conversion_bounds.py b/tests/security/test_legacy_office_conversion_bounds.py
new file mode 100644
index 0000000000..6aa2b071c5
--- /dev/null
+++ b/tests/security/test_legacy_office_conversion_bounds.py
@@ -0,0 +1,641 @@
+"""Bounds for the legacy-office conversion path (.doc/.ppt uploads).
+
+``.doc``/``.ppt`` uploads are OLE binaries that get converted via a
+``soffice`` subprocess before parsing. The conversion runs on an
+indexing worker for content up to the 3 GB upload cap; an unbounded
+subprocess (unstructured's ``convert_office_doc`` calls
+``subprocess.run(command, capture_output=True)`` with **no timeout**)
+lets a hostile or pathological file pin the worker forever — and a
+bare per-child kill would leave soffice's grandchildren alive.
+
+These contracts pin the bounded seam: a wall-clock timeout that
+actually reaches the subprocess layer, a process-group kill on hang,
+typed failure, output-size validation, per-call isolation of
+soffice's singleton profile, temp hygiene, and correct ordering with
+the zip-container guard on the *converted* bytes.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import shutil
+import signal
+import subprocess
+import sys
+import time
+import zipfile
+from contextlib import contextmanager
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+
+def _conv():
+ from local_deep_research.utilities import office_conversion
+
+ return office_conversion
+
+
+#: A payload carrying the OLE compound-file signature, which the wrapper
+#: requires before it launches soffice.
+_OLE = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" + b"\x00" * 504
+
+
+@contextmanager
+def _soffice_available(conv):
+ """Resolve the binary even on soffice-less boxes."""
+ with patch.object(conv.shutil, "which", return_value="soffice"):
+ yield
+
+
+class _FakeProc:
+ """Minimal Popen double: records the timeout, optional side effect."""
+
+ pid = 4242
+ returncode = 0
+
+ def __init__(self, on_communicate=None, command=None, kwargs=None):
+ self._on_communicate = on_communicate
+ self.communicate_timeout = None
+ self.waited = False
+ self.command = command
+ self.kwargs = kwargs
+
+ def communicate(self, timeout=None):
+ self.communicate_timeout = timeout
+ if self._on_communicate is not None:
+ self._on_communicate()
+ return b"", b""
+
+ def wait(self):
+ self.waited = True
+ return 0
+
+
+def _recording_popen(on_communicate=None, write_output=None):
+ """Popen double recording argv + kwargs; ``write_output`` gets the
+ path soffice would write (``<stem>.docx`` beside the input)."""
+ launched: list[_FakeProc] = []
+
+ def fake_popen(command, **kwargs):
+ in_path = Path([a for a in command if str(a).endswith(".doc")][0])
+
+ def communicate():
+ if write_output is not None:
+ write_output(in_path.with_suffix(".docx"))
+ if on_communicate is not None:
+ on_communicate()
+
+ proc = _FakeProc(
+ on_communicate=communicate, command=command, kwargs=kwargs
+ )
+ launched.append(proc)
+ return proc
+
+ return fake_popen, launched
+
+
+class TestConversionBounds:
+ def test_the_timeout_reaches_the_subprocess(self, tmp_path):
+ """No timeout -> a hang pins the worker forever."""
+ conv = _conv()
+ proc = _FakeProc()
+
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", return_value=proc),
+ ):
+ try:
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+ except conv.OfficeConversionError:
+ pass # the fake writes no output; only timing matters
+
+ assert (
+ proc.communicate_timeout is not None
+ and proc.communicate_timeout >= 30
+ ), "soffice runs without a real wall-clock timeout"
+
+ def test_hanging_conversion_is_killed_by_group_and_fails_typed(
+ self, tmp_path
+ ):
+ """TimeoutExpired triggers a process-group kill and a typed
+ rejection — not a bare child kill that leaks grandchildren."""
+ conv = _conv()
+
+ def hang(timeout=None):
+ raise subprocess.TimeoutExpired(cmd="soffice", timeout=timeout)
+
+ proc = _FakeProc(on_communicate=hang)
+ kills: list = []
+
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", return_value=proc),
+ patch.object(conv, "_kill_process_group", side_effect=kills.append),
+ ):
+ with pytest.raises(conv.OfficeConversionError) as excinfo:
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+
+ assert "timed out" in str(excinfo.value).lower()
+ assert kills == [proc.pid], (
+ f"hung conversion not killed by process group: {kills}"
+ )
+ assert proc.waited, "killed process was never reaped"
+
+ def test_runaway_output_is_refused(self, tmp_path):
+ """A conversion whose output exceeds the ceiling is refused."""
+ conv = _conv()
+
+ def write_big():
+ (tmp_path / "upload.docx").write_bytes(b"\x00" * 1000)
+
+ with (
+ _soffice_available(conv),
+ patch.object(
+ conv.subprocess,
+ "Popen",
+ return_value=_FakeProc(on_communicate=write_big),
+ ),
+ ):
+ with pytest.raises(conv.OfficeConversionError) as excinfo:
+ conv.convert_legacy_office_bytes(
+ _OLE,
+ ".doc",
+ output_dir=tmp_path,
+ input_stem="upload",
+ max_output_bytes=100,
+ )
+
+ assert "larger than" in str(excinfo.value).lower()
+
+ def test_each_call_gets_its_own_soffice_profile(self, tmp_path):
+ """soffice is a singleton per profile; concurrent conversions
+ must not serialize or corrupt each other via a shared one."""
+ conv = _conv()
+ commands: list = []
+
+ def fake_popen(command, **kwargs):
+ commands.append(command)
+ return _FakeProc()
+
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ for payload in (_OLE + b"a", _OLE + b"b"):
+ try:
+ conv.convert_legacy_office_bytes(
+ payload, ".doc", output_dir=tmp_path
+ )
+ except conv.OfficeConversionError:
+ pass # the fake writes no output; only calls matter
+
+ profiles = [
+ " ".join(a for a in command if "UserInstallation" in str(a))
+ for command in commands
+ ]
+ assert len(commands) == 2, commands
+ assert all(profiles), f"no -env:UserInstallation passed: {commands}"
+ assert profiles[0] != profiles[1], (
+ "conversions share one soffice profile (singleton lock)"
+ )
+
+ def test_temp_input_is_cleaned_up(self, tmp_path):
+ """The OLE bytes written to disk for soffice must not linger."""
+ conv = _conv()
+ seen: list = []
+
+ def check_input():
+ seen.append(list(tmp_path.rglob("*.doc")))
+ assert seen[-1], "input file missing while soffice runs"
+
+ with (
+ _soffice_available(conv),
+ patch.object(
+ conv.subprocess,
+ "Popen",
+ return_value=_FakeProc(on_communicate=check_input),
+ ),
+ ):
+ with pytest.raises(conv.OfficeConversionError):
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+
+ leftovers = list(tmp_path.rglob("*"))
+ assert not leftovers, f"conversion left files behind: {leftovers}"
+
+ def test_traversal_shaped_input_stem_is_refused(self, tmp_path):
+ """An input_stem carrying separators must never escape the
+ work dir."""
+ conv = _conv()
+
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", return_value=_FakeProc()),
+ ):
+ with pytest.raises(conv.OfficeConversionError):
+ conv.convert_legacy_office_bytes(
+ _OLE,
+ ".doc",
+ output_dir=tmp_path,
+ input_stem="../../evil",
+ )
+
+
+class TestWiring:
+ def test_doc_upload_routes_through_conversion_then_zip_guard(
+ self, tmp_path
+ ):
+ """.doc bytes are converted, and the CONVERTED container is
+ zip-guarded — a bomb in the conversion output cannot pass."""
+ from local_deep_research.document_loaders.bytes_loader import (
+ load_from_bytes,
+ )
+ from local_deep_research.document_loaders.zip_container_guard import (
+ DecompressionBombError,
+ )
+
+ conv = _conv()
+ bomb = io.BytesIO()
+ with zipfile.ZipFile(bomb, "w") as zf:
+ for i in range(10_001):
+ zf.writestr(f"p{i}.xml", "x")
+
+ def fake_popen(command, **kwargs):
+ # Emulate soffice: <stem>.doc -> <stem>.docx beside it.
+ in_path = Path([a for a in command if str(a).endswith(".doc")][0])
+ in_path.with_suffix(".docx").write_bytes(bomb.getvalue())
+ return _FakeProc()
+
+ import local_deep_research.document_loaders.bytes_loader as bl
+
+ with (
+ _soffice_available(conv),
+ patch.object(bl, "is_extension_supported", return_value=True),
+ patch.object(
+ bl, "get_loader_class_for_extension", return_value=None
+ ),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(DecompressionBombError):
+ load_from_bytes(_OLE, ".doc", "hostile.doc")
+
+ @pytest.mark.skipif(
+ not (shutil.which("soffice") or shutil.which("libreoffice")),
+ reason="soffice not installed",
+ )
+ def test_live_round_trip(self, tmp_path):
+ """Control: garbage OLE fails cleanly (typed error), never hangs."""
+ conv = _conv()
+
+ with pytest.raises((conv.OfficeConversionError, ValueError)):
+ conv.convert_legacy_office_bytes(
+ _OLE + b"not really OLE", ".doc", output_dir=tmp_path
+ )
+
+
+class TestProcessIsolation:
+ """A hang must be killable as a tree, and nothing may be buffered."""
+
+ def _launch(self, conv, tmp_path, **popen_opts):
+ fake_popen, launched = _recording_popen(**popen_opts)
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ try:
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+ except conv.OfficeConversionError:
+ pass
+ assert launched, "soffice never launched"
+ return launched[0]
+
+ def test_soffice_runs_in_its_own_session(self, tmp_path):
+ """Without a new session, proc.pid is not a process-group id:
+ the group kill misses and ``proc.wait()`` blocks forever."""
+ conv = _conv()
+ kwargs = self._launch(conv, tmp_path).kwargs
+
+ assert (
+ kwargs.get("start_new_session") is True
+ or kwargs.get("process_group") == 0
+ ), f"soffice not started in its own process group: {kwargs}"
+
+ def test_stdio_goes_to_devnull_not_a_pipe(self, tmp_path):
+ conv = _conv()
+ kwargs = self._launch(conv, tmp_path).kwargs
+
+ for stream in ("stdout", "stderr"):
+ assert kwargs.get(stream) == subprocess.DEVNULL, (
+ f"soffice {stream} is buffered: {kwargs.get(stream)!r}"
+ )
+
+ @pytest.mark.skipif(
+ not hasattr(os, "killpg"), reason="no process groups here"
+ )
+ def test_timeout_kill_targets_the_process_group(self, tmp_path):
+ """soffice forks helpers; a bare child kill leaves them alive."""
+ conv = _conv()
+
+ def hang():
+ raise subprocess.TimeoutExpired(cmd="soffice", timeout=1)
+
+ fake_popen, launched = _recording_popen(on_communicate=hang)
+ group_kills: list = []
+ pid_kills: list = []
+
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ patch.object(
+ conv.os, "killpg", side_effect=lambda *a: group_kills.append(a)
+ ),
+ patch.object(
+ conv.os, "kill", side_effect=lambda *a: pid_kills.append(a)
+ ),
+ ):
+ with pytest.raises(conv.OfficeConversionError, match="timed out"):
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+
+ assert group_kills == [(launched[0].pid, signal.SIGKILL)], (
+ f"hung soffice not killed as a group: killpg={group_kills} "
+ f"kill={pid_kills}"
+ )
+ assert launched[0].waited, "killed process was never reaped"
+
+
+class TestDefaultsAndHygiene:
+ def test_default_timeout_is_bounded_and_reaches_the_subprocess(
+ self, tmp_path
+ ):
+ conv = _conv()
+ fake_popen, launched = _recording_popen()
+
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(conv.OfficeConversionError):
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+
+ assert launched[0].communicate_timeout == (
+ conv.DEFAULT_CONVERSION_TIMEOUT_S
+ )
+ assert 30 <= conv.DEFAULT_CONVERSION_TIMEOUT_S <= 300
+
+ def test_default_output_ceiling_refuses_one_byte_over(self, tmp_path):
+ """The default ceiling is 512 MiB and applies without kwargs; a
+ sparse file keeps the check cheap."""
+ conv = _conv()
+ assert conv.DEFAULT_MAX_OUTPUT_BYTES == 512 * 1024 * 1024
+
+ def sparse(out):
+ with out.open("wb") as fh:
+ fh.truncate(conv.DEFAULT_MAX_OUTPUT_BYTES + 1)
+
+ fake_popen, _ = _recording_popen(write_output=sparse)
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(conv.OfficeConversionError, match="larger"):
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+
+ def test_oversized_output_is_never_read(self, tmp_path):
+ """The size check must come BEFORE the read."""
+ conv = _conv()
+ reads: list = []
+ real_read_bytes = Path.read_bytes
+
+ def spy(self):
+ reads.append(self.suffix)
+ return real_read_bytes(self)
+
+ fake_popen, _ = _recording_popen(
+ write_output=lambda out: out.write_bytes(b"x" * 5000)
+ )
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ patch.object(Path, "read_bytes", spy),
+ ):
+ with pytest.raises(conv.OfficeConversionError, match="larger"):
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path, max_output_bytes=100
+ )
+
+ assert ".docx" not in reads, "oversized output was read"
+
+ @pytest.mark.parametrize("succeed", [True, False])
+ def test_owned_work_dir_is_removed(self, tmp_path, succeed):
+ """With no output_dir the wrapper owns a mkdtemp dir; it must be
+ gone afterwards on success and on failure."""
+ conv = _conv()
+ created: list[Path] = []
+ real_mkdtemp = conv.tempfile.mkdtemp
+
+ def recording_mkdtemp(*args, **kwargs):
+ path = real_mkdtemp(*args, dir=tmp_path, **kwargs)
+ created.append(Path(path))
+ return path
+
+ fake_popen, _ = _recording_popen(
+ write_output=(
+ (lambda out: out.write_bytes(b"PK")) if succeed else None
+ )
+ )
+ with (
+ _soffice_available(conv),
+ patch.object(conv.tempfile, "mkdtemp", recording_mkdtemp),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ if succeed:
+ assert conv.convert_legacy_office_bytes(_OLE, ".doc")
+ else:
+ with pytest.raises(conv.OfficeConversionError):
+ conv.convert_legacy_office_bytes(_OLE, ".doc")
+
+ assert len(created) == 1, created
+ assert not created[0].exists(), "owned work dir left behind"
+
+
+_FAKE_BINARY = """#!/bin/sh
+sleep 20 &
+echo $! > "{pidfile}"
+wait
+"""
+
+
+def _pid_alive(pid: int) -> bool:
+ try:
+ with open(f"/proc/{pid}/stat", encoding="utf-8") as fh:
+ state = fh.read().rsplit(")", 1)[1].split()[0]
+ except (FileNotFoundError, ProcessLookupError, IndexError):
+ return False
+ return state not in ("Z", "X")
+
+
+def _require_exec(directory: Path) -> None:
+ """Skip when *directory* is mounted noexec."""
+ probe = directory / "exec-probe"
+ probe.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ probe.chmod(0o755)
+ try:
+ subprocess.run([str(probe)], check=True, timeout=10)
+ except (OSError, subprocess.SubprocessError):
+ pytest.skip("tmp_path does not allow executing scripts")
+
+
+def _wait_for_pid(pidfile: Path, timeout_s: float = 5.0) -> int:
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ try:
+ text = pidfile.read_text(encoding="utf-8").strip()
+ except FileNotFoundError:
+ text = ""
+ if text:
+ return int(text)
+ time.sleep(0.05)
+ pytest.skip("child never reached its spawn point (loaded host)")
+
+
+ not sys.platform.startswith("linux"), reason="uses /proc and /bin/sh"
+)
+class TestRealProcessTree:
+ """A real child that spawns a sleeping grandchild: the timeout must
+ return promptly AND take the grandchild down with it."""
+
+ def test_timeout_kills_the_whole_tree(self, tmp_path):
+ conv = _conv()
+ pidfile = tmp_path / "grandchild.pid"
+ bin_dir = tmp_path / "bin"
+ bin_dir.mkdir()
+ _require_exec(bin_dir)
+ # The wrapper launches soffice by name, so the fake goes on PATH.
+ binary = bin_dir / "soffice"
+ binary.write_text(
+ _FAKE_BINARY.format(pidfile=pidfile), encoding="utf-8"
+ )
+ binary.chmod(0o755)
+ work = tmp_path / "work"
+ work.mkdir()
+ path = f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}"
+
+ grandchild = None
+ try:
+ with patch.dict(os.environ, {"PATH": path}):
+ started = time.monotonic()
+ with pytest.raises(conv.OfficeConversionError, match="timed"):
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=work, timeout_s=2
+ )
+ elapsed = time.monotonic() - started
+
+ assert elapsed < 12, f"timeout took {elapsed:.1f}s to return"
+ grandchild = _wait_for_pid(pidfile)
+ deadline = time.monotonic() + 5
+ while _pid_alive(grandchild) and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert not _pid_alive(grandchild), "grandchild survived the kill"
+ finally:
+ if grandchild is None and pidfile.exists():
+ text = pidfile.read_text(encoding="utf-8").strip()
+ grandchild = int(text) if text else None
+ if grandchild is not None:
+ try:
+ os.kill(grandchild, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+
+
+class TestOnlyOleInputReachesSoffice:
+ """soffice sniffs content, not the extension: a zip container (or an
+ RTF, or HTML) renamed .doc/.ppt would otherwise reach it unguarded."""
+
+ @pytest.mark.parametrize("ext", [".doc", ".ppt"])
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ pytest.param(b"PK\x03\x04" + b"\x00" * 64, id="zip"),
+ pytest.param(b"{\\rtf1 hello}", id="rtf"),
+ pytest.param(b"<html>hello</html>", id="html"),
+ pytest.param(b"", id="empty"),
+ ],
+ )
+ def test_non_ole_input_never_launches_soffice(self, tmp_path, ext, payload):
+ conv = _conv()
+ launched: list = []
+
+ with (
+ _soffice_available(conv),
+ patch.object(
+ conv.subprocess,
+ "Popen",
+ side_effect=lambda *a, **k: launched.append(a) or _FakeProc(),
+ ),
+ ):
+ with pytest.raises(conv.OfficeConversionError, match="OLE"):
+ conv.convert_legacy_office_bytes(
+ payload, ext, output_dir=tmp_path
+ )
+
+ assert launched == [], "non-OLE input was handed to soffice"
+
+ def test_ole_input_still_launches_soffice(self, tmp_path):
+ conv = _conv()
+ fake_popen, launched = _recording_popen()
+ with (
+ _soffice_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(conv.OfficeConversionError, match="no output"):
+ conv.convert_legacy_office_bytes(
+ _OLE, ".doc", output_dir=tmp_path
+ )
+
+ assert len(launched) == 1
+
+ def test_upload_path_refuses_a_zip_renamed_doc(self):
+ from local_deep_research.document_loaders.bytes_loader import (
+ extract_text_from_bytes,
+ load_from_bytes,
+ )
+
+ import local_deep_research.document_loaders.bytes_loader as bl
+
+ conv = _conv()
+ bomb = io.BytesIO()
+ with zipfile.ZipFile(bomb, "w", zipfile.ZIP_DEFLATED) as zf:
+ zf.writestr("word/document.xml", b"\x00" * 100_000)
+
+ with (
+ _soffice_available(conv),
+ patch.object(bl, "is_extension_supported", return_value=True),
+ patch.object(
+ conv.subprocess,
+ "Popen",
+ side_effect=AssertionError("soffice launched"),
+ ),
+ ):
+ with pytest.raises(conv.OfficeConversionError, match="OLE"):
+ load_from_bytes(bomb.getvalue(), ".doc", "renamed.doc")
+ assert (
+ extract_text_from_bytes(bomb.getvalue(), ".doc", "renamed.doc")
+ is None
+ )
diff --git a/tests/security/test_ooxml_decompression_caps.py b/tests/security/test_ooxml_decompression_caps.py
new file mode 100644
index 0000000000..51f8bd5475
--- /dev/null
+++ b/tests/security/test_ooxml_decompression_caps.py
@@ -0,0 +1,10808 @@
+"""Decompression-bomb ceilings for zip-container uploads.
+
+The rag upload route indexes arbitrary document types through
+``document_loaders``; ``.docx``/``.xlsx``/``.odt`` are zip containers
+of XML that the parsers (python-docx, openpyxl, unstructured) read
+entry-whole into memory (``archive.read(...)``). Upload caps bound the
+COMPRESSED body, not the uncompressed side: a modest ``.xlsx`` can
+decompress to gigabytes of ``sharedStrings`` and OOM the indexing
+worker — the same class as the OpenAlex partition caps and the PDF
+extraction ceilings.
+
+The guard checks the central directory's declarations (entry count,
+compression method — STORED/DEFLATE only, no encryption, compressed
+size consistent with the declared size, declared total), then inflates
+every entry in bounded steps and refuses any that produces more than
+it declares: zipfile truncates to the declared size only *after*
+inflating, so an unverified declaration bounds nothing. Verified sizes
+then face the per-kind ceilings. For the in-process Python parsers
+that bounds the bytes of each *read* (not their memory, which runs a
+multiple of it). pandoc's own zip reader is bounded separately (see
+test_pandoc_conversion_bounds.py).
+"""
+
+from __future__ import annotations
+
+import io
+import math
+import posixpath
+import random
+import re
+import struct
+import time
+import zipfile
+import zlib
+import contextlib
+import copy
+from contextlib import contextmanager
+from unittest.mock import patch
+
+import pytest
+
+
+def _zip_bytes(entries: dict[str, bytes]) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ for name, data in entries.items():
+ zf.writestr(name, data)
+ return buf.getvalue()
+
+
+def _guard():
+ from local_deep_research.document_loaders import zip_container_guard
+
+ return zip_container_guard
+
+
+def _ooxml_package(entries: dict[str, bytes], ext: str) -> dict[str, bytes]:
+ """*entries* plus, after them, what a .docx or .pptx needs for the
+ guard to accept its layout: a package relationship to a main part
+ that exists (and so a part name unstructured's sniffer reads as the
+ extension) of the content type the library loads it as. Entries
+ already present are kept."""
+ if ext == ".docx":
+ main = "word/document.xml"
+ body = f"<w:document xmlns:w='{_W_MAIN}'><w:body/></w:document>"
+ main_ct = "wordprocessingml.document.main+xml"
+ else:
+ main = "ppt/presentation.xml"
+ body = (
+ "<p:presentation xmlns:p='http://schemas.openxmlformats.org/"
+ "presentationml/2006/main'/>"
+ )
+ main_ct = "presentationml.presentation.main+xml"
+ skeleton = {
+ "[Content_Types].xml": (
+ "<Types xmlns='http://schemas.openxmlformats.org/package/2006/"
+ "content-types'><Override PartName='/"
+ + main
+ + "' ContentType='application/vnd.openxmlformats-officedocument."
+ + main_ct
+ + "'/></Types>"
+ ).encode(),
+ "_rels/.rels": _rels(("rId1", "officeDocument", main)).encode(),
+ main: body.encode(),
+ }
+ return {
+ **entries,
+ **{k: v for k, v in skeleton.items() if k not in entries},
+ }
+
+
+class TestOoxmlDecompressionCaps:
+ """Oversized zip-container uploads must be refused pre-parse."""
+
+ def test_oversized_declared_entry_is_refused(self):
+ guard = _guard()
+
+ bomb = _zip_bytes({"xl/sharedStrings.xml": b"\x00" * 5_000_000})
+
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(
+ bomb, ".xlsx", max_entry_bytes=1_000_000
+ )
+
+ def test_oversized_declared_total_is_refused(self):
+ guard = _guard()
+
+ bomb = _zip_bytes(
+ {
+ "xl/worksheets/sheet1.xml": b"\x00" * 900_000,
+ "xl/worksheets/sheet2.xml": b"\x00" * 900_000,
+ }
+ )
+
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(
+ bomb, ".xlsx", max_total_bytes=1_000_000
+ )
+
+ def test_entry_flood_is_refused(self):
+ guard = _guard()
+
+ flood = _zip_bytes({f"r/{i}.xml": b"x" for i in range(50)})
+
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(flood, ".docx", max_entries=10)
+
+ def test_load_from_bytes_applies_the_guard(self):
+ """The upload funnel refuses the bomb before any parser runs.
+
+ Uses the entry-count ceiling so the default knobs are exercised
+ without materializing a half-gigabyte entry in the test.
+ """
+ from local_deep_research.document_loaders.bytes_loader import (
+ load_from_bytes,
+ )
+
+ bomb = _zip_bytes({f"word/part{i}.xml": b"x" for i in range(10_001)})
+
+ with pytest.raises(ValueError) as excinfo:
+ load_from_bytes(bomb, ".docx", "hostile.docx")
+
+ assert "DecompressionBomb" in type(excinfo.value).__name__ or (
+ "entries" in str(excinfo.value).lower()
+ ), f"bomb reached the parser layer unguarded ({excinfo.value!r})"
+
+ def test_non_container_extensions_bypass_the_guard(self):
+ """Plain-text and PDF bytes never hit the zip check."""
+ guard = _guard()
+
+ guard.validate_zip_container(b"not a zip at all", ".txt")
+ guard.validate_zip_container(b"%PDF-not-a-zip", ".pdf")
+
+ @pytest.mark.parametrize("ext", [".pptx", ".epub"])
+ def test_every_registry_zip_container_is_guarded(self, ext):
+ """The guard's extension set must cover every zip-backed loader."""
+ guard = _guard()
+
+ bomb = _zip_bytes({"content/part.xml": b"\x00" * 5_000_000})
+
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(bomb, ext, max_entry_bytes=1_000_000)
+
+
+def _central_dir_offset(data: bytes) -> int:
+ """Offset of the first central-directory record."""
+ return data.index(b"PK\x01\x02")
+
+
+class TestCentralDirectorySpanIsBoundedPreParse:
+ """zipfile materialises every central-directory record before the
+ entry-count ceiling can count them, so the span the archive's end
+ records declare is refused first — no records need be packed."""
+
+ def test_huge_declared_span_is_refused_pre_parse(self):
+ """A stub container whose EOCD claims a 500 MB central
+ directory is refused on the declaration alone."""
+ guard = _guard()
+ data = bytearray(_zip_bytes({"word/document.xml": b"<w/>"}))
+ struct.pack_into(
+ "<I", data, data.rfind(b"PK\x05\x06") + 12, 500_000_000
+ )
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="central directory spans"
+ ):
+ guard.validate_zip_container(bytes(data), ".docx")
+
+ def test_scaled_ceiling_is_used(self):
+ guard = _guard()
+ data = bytearray(_zip_bytes({"word/document.xml": b"<w/>"}))
+ struct.pack_into("<I", data, data.rfind(b"PK\x05\x06") + 12, 11_001)
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="central directory spans"
+ ):
+ guard.validate_zip_container(bytes(data), ".docx", max_entries=10)
+
+ def test_zip64_declared_span_is_refused_pre_parse(self):
+ """A ZIP64 end record declaring the big span is refused too,
+ with the 32-bit EOCD declaring none: the ZIP64 record zipfile
+ follows governs."""
+ guard = _guard()
+ data = _record_flood(40, cd_size_in_eocd=0, zip64=True)
+
+ with _zipfile_must_not_be_constructed(guard):
+ with pytest.raises(guard.DecompressionBombError, match="1880"):
+ guard.validate_zip_container(data, ".docx", max_entries=1)
+
+ def test_honest_small_span_falls_through(self):
+ """An honest container's central directory is tiny; the
+ pre-parse bound must not fire and the guard still accepts it."""
+ guard = _guard()
+ package = _zip_bytes(_ooxml_package({}, ".docx"))
+
+ guard.validate_zip_container(package, ".docx")
+
+ def test_empty_archive_falls_through(self):
+ # The EOCD of an empty archive declares a zero-byte span.
+ _guard().validate_zip_container(_zip_bytes({}), ".epub")
+
+ def test_absent_eocd_is_refused_pre_parse(self):
+ """No end record zipfile can find: the bound fails closed itself
+ rather than standing aside for ZipFile."""
+ guard = _guard()
+
+ with _zipfile_must_not_be_constructed(guard):
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(b"PK\x03\x04 truncated", ".docx")
+
+ def test_end_record_zipfile_rejects_is_refused_pre_parse(self):
+ """A ZIP64 record zipfile refuses as corrupt (its offset plus
+ size miss the locator's offset) is refused before ZipFile."""
+ guard = _guard()
+ data = bytearray(_record_flood(2, cd_size_in_eocd=0, zip64=True))
+ zip64_at = data.rfind(b"PK\x06\x06")
+ struct.pack_into("<Q", data, zip64_at + 48, 7)
+
+ with _zipfile_must_not_be_constructed(guard):
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(bytes(data), ".docx")
+
+
+def _record_flood(
+ count: int,
+ *,
+ cd_size_in_eocd: int | None = None,
+ eocd_counts: bytes | None = None,
+ eocd_offset: int | None = None,
+ zip64: bool = False,
+ zip64_extensible: bytes = b"",
+ comment: bytes = b"",
+) -> bytes:
+ """A stub local header, then *count* 47-byte central-directory
+ records, then hand-packed end records — the shape of a record
+ flood, kept tiny (the tests lower ``max_entries`` instead)."""
+ local = b"PK\x03\x04" + b"\x00" * 26
+ record = b"PK\x01\x02" + struct.pack("<6H3L5H2L", *([0] * 16)) + b"a"
+ record = record[:28] + struct.pack("<H", 1) + record[30:]
+ cd = record * count
+ cd_offset = len(local)
+ out = local + cd
+ if zip64:
+ zip64_at = len(out)
+ out += (
+ b"PK\x06\x06"
+ + struct.pack(
+ "<Q2H2I4Q",
+ 44 + len(zip64_extensible),
+ 45,
+ 45,
+ 0,
+ 0,
+ count,
+ count,
+ len(cd),
+ cd_offset,
+ )
+ + zip64_extensible
+ + b"PK\x06\x07"
+ + struct.pack("<IQI", 0, zip64_at, 1)
+ )
+ counts = eocd_counts or struct.pack("<2H", count, count)
+ out += (
+ b"PK\x05\x06"
+ + struct.pack("<2H", 0, 0)
+ + counts
+ + struct.pack(
+ "<2LH",
+ len(cd) if cd_size_in_eocd is None else cd_size_in_eocd,
+ cd_offset if eocd_offset is None else eocd_offset,
+ len(comment),
+ )
+ + comment
+ )
+ return out
+
+
+@contextmanager
+def _zipfile_must_not_be_constructed(guard):
+ """The bound must refuse before zipfile walks any record."""
+ with patch.object(
+ guard.zipfile,
+ "ZipFile",
+ side_effect=AssertionError("ZipFile was constructed"),
+ ) as zip_file:
+ yield
+ assert not zip_file.called, "ZipFile walked the central directory"
+
+
+class TestEndRecordSelectionMatchesZipfile:
+ """The span is read from the end records zipfile itself selects;
+ a layout where a naive backwards search for the signatures picks a
+ different record (or none) must not slip past the bound. Each
+ archive holds 40 records (1880 bytes) against a 1 KiB limit."""
+
+ def test_signature_in_eocd_entry_count_fields_is_refused(self):
+ """zipfile takes the fixed 22-byte record at the end; the
+ signature written into its (ignored) entry counts must not
+ hide the record from the bound."""
+ guard = _guard()
+ data = _record_flood(40, eocd_counts=b"PK\x05\x06")
+ assert zipfile._EndRecData(io.BytesIO(data))[5] == 1880
+
+ with _zipfile_must_not_be_constructed(guard):
+ with pytest.raises(guard.DecompressionBombError, match="1880"):
+ guard.validate_zip_container(data, ".docx", max_entries=1)
+
+ def test_signature_in_eocd_offset_field_is_refused(self):
+ """The offset 0x06054b50 spells the signature; zipfile ignores
+ the offset when it locates the directory."""
+ guard = _guard()
+ data = _record_flood(40, eocd_offset=0x06054B50)
+ assert zipfile._EndRecData(io.BytesIO(data))[5] == 1880
+
+ with _zipfile_must_not_be_constructed(guard):
+ with pytest.raises(guard.DecompressionBombError, match="1880"):
+ guard.validate_zip_container(data, ".docx", max_entries=1)
+
+ def test_fake_zip64_record_in_comment_is_refused(self):
+ """A zeroed ZIP64 record in the archive comment declares no
+ span; zipfile follows the locator to the real one."""
+ guard = _guard()
+ fake = b"PK\x06\x06" + b"\x00" * 52
+ data = _record_flood(40, cd_size_in_eocd=0, zip64=True, comment=fake)
+ assert zipfile._EndRecData(io.BytesIO(data))[5] == 1880
+
+ with _zipfile_must_not_be_constructed(guard):
+ with pytest.raises(guard.DecompressionBombError, match="1880"):
+ guard.validate_zip_container(data, ".docx", max_entries=1)
+
+ def test_zip64_record_behind_extensible_data_is_refused(self):
+ """The ZIP64 record sits more than 64 KiB before its locator
+ (zip64 extensible data); zipfile follows the locator's offset
+ to it, so the bound must too."""
+ guard = _guard()
+ data = _record_flood(
+ 40,
+ cd_size_in_eocd=0,
+ zip64=True,
+ zip64_extensible=b"\x00" * 70_000,
+ )
+ if zipfile._EndRecData(io.BytesIO(data))[5] != 1880:
+ pytest.skip("this zipfile does not follow the ZIP64 locator")
+
+ with _zipfile_must_not_be_constructed(guard):
+ with pytest.raises(guard.DecompressionBombError, match="1880"):
+ guard.validate_zip_container(data, ".docx", max_entries=1)
+
+ def test_layouts_are_walked_by_zipfile_when_unbounded(self):
+ """Control: without the bound, zipfile really walks all 40
+ records of each layout — the refusals above are not an
+ artefact of malformed archives."""
+ layouts = [
+ _record_flood(40, eocd_counts=b"PK\x05\x06"),
+ _record_flood(40, eocd_offset=0x06054B50),
+ _record_flood(
+ 40,
+ cd_size_in_eocd=0,
+ zip64=True,
+ comment=b"PK\x06\x06" + b"\x00" * 52,
+ ),
+ ]
+ for data in layouts:
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ assert len(archive.infolist()) == 40
+
+
+class TestMalformedContainersFailClosed:
+ """Anything the stdlib cannot even list is refused as the guard's
+ own typed error — never passed on, never a stray exception."""
+
+ def test_not_a_zip_is_refused(self):
+ guard = _guard()
+
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(b"PK\x03\x04 truncated", ".docx")
+
+ def test_truncated_central_directory_is_refused(self):
+ guard = _guard()
+ data = _zip_bytes({"word/document.xml": b"<w/>"})
+
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(data[: len(data) - 30], ".docx")
+
+ def test_undecodable_utf8_entry_name_is_refused(self):
+ """Flag bit 11 promises UTF-8 names; invalid bytes make
+ ``infolist()`` raise UnicodeDecodeError."""
+ guard = _guard()
+ data = bytearray(_zip_bytes({"word/abc.xml": b"<w/>"}))
+ cd = _central_dir_offset(data)
+ flags = struct.unpack_from("<H", data, cd + 8)[0] | 0x800
+ struct.pack_into("<H", data, cd + 8, flags)
+ name_at = cd + 46
+ data[name_at + 5 : name_at + 8] = b"\xff\xfe\xfd"
+
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(bytes(data), ".docx")
+
+ def test_unsupported_zip_version_is_refused(self):
+ """An extract version above what zipfile supports makes
+ ``infolist()`` raise NotImplementedError."""
+ guard = _guard()
+ data = bytearray(_zip_bytes({"word/document.xml": b"<w/>"}))
+ cd = _central_dir_offset(data)
+ struct.pack_into("<B", data, cd + 6, 0xFF)
+
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(bytes(data), ".xlsx")
+
+
+_OLE_HEADER = b"\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" + b"\x00" * 504
+
+
+class TestContainerIsAnchoredAtOffsetZero:
+ """zipfile finds the central directory from the end of the file and
+ tolerates data in front of the archive; unstructured sniffs the
+ leading bytes. A legacy OLE file with a zip appended must not pass
+ as a container (it would be routed to an unbounded soffice)."""
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_ole_file_with_appended_zip_is_refused(self, ext):
+ guard = _guard()
+ data = _OLE_HEADER + _zip_bytes({"word/document.xml": b"<w/>"})
+ # Premise: zipfile alone accepts it.
+ assert zipfile.ZipFile(io.BytesIO(data)).namelist()
+
+ with pytest.raises(guard.DecompressionBombError, match="signature"):
+ guard.validate_zip_container(data, ext)
+
+ def test_prepended_junk_is_refused(self):
+ guard = _guard()
+ data = b"junk" * 16 + _zip_bytes({"word/document.xml": b"<w/>"})
+
+ with pytest.raises(guard.DecompressionBombError, match="signature"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_prepended_data_behind_a_zip_signature_is_refused(self):
+ """Junk that itself starts with a local-header signature still
+ shifts the first entry off offset 0."""
+ guard = _guard()
+ data = (
+ b"PK\x03\x04"
+ + b"\x00" * 60
+ + _zip_bytes({"word/document.xml": b"<w/>"})
+ )
+ assert zipfile.ZipFile(io.BytesIO(data)).namelist()
+
+ with pytest.raises(guard.DecompressionBombError, match="before its"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_normal_docx_is_accepted(self):
+ docx = pytest.importorskip("docx")
+
+ buf = io.BytesIO()
+ docx.Document().save(buf)
+
+ _guard().validate_zip_container(buf.getvalue(), ".docx")
+
+ @pytest.mark.parametrize("ext", [".odt", ".epub"])
+ def test_empty_archive_is_still_accepted(self, ext):
+ # An empty .docx/.pptx/.xlsx has no main part and is refused for
+ # that (TestPackageTypeMatchesTheExtension); the anchoring check
+ # itself accepts the end-of-central-directory record.
+ _guard().validate_zip_container(_zip_bytes({}), ext)
+
+
+_PNG = b"\x89PNG\r\n\x1a\n"
+
+#: Scaled-down ceilings so the tests never materialize real sizes.
+_SCALED = {
+ "max_entry_bytes": 1_000_000,
+ "max_total_bytes": 2_000_000,
+ "max_media_entry_bytes": 4_000_000,
+ "max_container_bytes": 7_000_000,
+}
+
+
+class TestMediaEntries:
+ """Binary media is parsed by nothing (~1x memory), so a large image
+ or video must not be refused by the parsed-part ceilings — while a
+ large XML part still is, whatever it is named."""
+
+ def test_large_media_entry_is_accepted(self):
+ guard = _guard()
+ doc = _zip_bytes(
+ _ooxml_package(
+ {
+ "ppt/slides/slide1.xml": b"<p:sld/>",
+ "ppt/media/image1.png": _PNG + b"\x00" * 3_000_000,
+ },
+ ".pptx",
+ )
+ )
+
+ guard.validate_zip_container(doc, ".pptx", **_SCALED)
+
+ def test_large_xml_entry_is_still_refused(self):
+ guard = _guard()
+ doc = _zip_bytes({"ppt/slides/slide1.xml": b"<a/>" * 750_000})
+
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(doc, ".pptx", **_SCALED)
+
+ def test_media_name_does_not_earn_the_media_ceiling(self):
+ """Names are attacker-chosen and parts dispatch by content
+ type: XML stored under ``media/*.png`` is still a parsed part."""
+ guard = _guard()
+ doc = _zip_bytes({"ppt/media/image1.png": b"<a/>" * 750_000})
+
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(doc, ".pptx", **_SCALED)
+
+ def test_markup_name_keeps_parsed_ceiling_despite_media_bytes(self):
+ guard = _guard()
+ doc = _zip_bytes({"word/document.xml": _PNG + b"\x00" * 3_000_000})
+
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(doc, ".docx", **_SCALED)
+
+ def test_media_entry_over_its_own_ceiling_is_refused(self):
+ guard = _guard()
+ doc = _zip_bytes(
+ {"word/media/v.mp4": b"\x00\x00\x00\x18ftyp" + b"\x00" * 5_000_000}
+ )
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="ceiling 4000000"
+ ):
+ guard.validate_zip_container(doc, ".docx", **_SCALED)
+
+ def test_media_does_not_count_toward_the_parsed_total(self):
+ guard = _guard()
+ doc = _zip_bytes(
+ _ooxml_package(
+ {
+ "ppt/media/a.png": _PNG + b"\x00" * 3_000_000,
+ "ppt/slides/slide1.xml": b"<a/>" * 200_000,
+ "ppt/slides/slide2.xml": b"<a/>" * 200_000,
+ },
+ ".pptx",
+ )
+ )
+
+ guard.validate_zip_container(doc, ".pptx", **_SCALED)
+
+ def test_container_total_still_holds_with_media(self):
+ guard = _guard()
+ doc = _zip_bytes(
+ {
+ "ppt/media/a.png": _PNG + b"\x00" * 3_000_000,
+ "ppt/media/b.png": _PNG + b"\x00" * 3_000_000,
+ "ppt/media/c.png": _PNG + b"\x00" * 3_000_000,
+ }
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="total"):
+ guard.validate_zip_container(doc, ".pptx", **_SCALED)
+
+ def test_corrupt_media_stream_fails_closed(self):
+ """Sniffing decompresses a few bytes; a corrupt deflate stream
+ must surface as the guard's typed rejection."""
+ guard = _guard()
+ data = bytearray(
+ _zip_bytes({"ppt/media/a.png": _PNG + b"\x00" * 200_000})
+ )
+ name_len, extra_len = struct.unpack_from("<HH", data, 26)
+ start = 30 + name_len + extra_len
+ data[start : start + 8] = b"\xff" * 8
+
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(bytes(data), ".pptx", **_SCALED)
+
+ def test_real_pptx_with_large_picture_is_accepted(self):
+ pptx = pytest.importorskip("pptx")
+ pil = pytest.importorskip("PIL.Image")
+ from pptx.util import Inches
+
+ tiny = io.BytesIO()
+ pil.new("RGB", (4, 4)).save(tiny, "PNG")
+ # PNG readers ignore trailing bytes: pad the picture past the
+ # scaled parsed-part ceiling.
+ picture = io.BytesIO(tiny.getvalue() + b"\x00" * 2_000_000)
+ deck = pptx.Presentation()
+ slide = deck.slides.add_slide(deck.slide_layouts[5])
+ slide.shapes.add_picture(picture, Inches(1), Inches(1))
+ buf = io.BytesIO()
+ deck.save(buf)
+
+ _guard().validate_zip_container(buf.getvalue(), ".pptx", **_SCALED)
+
+
+def _set_declared_size(data: bytes, name: str, size: int) -> bytes:
+ """Rewrite *name*'s uncompressed size in both headers (a lie)."""
+ out = bytearray(data)
+ encoded = name.encode()
+ local = 0
+ while True:
+ local = out.index(b"PK\x03\x04", local)
+ name_len = struct.unpack_from("<H", out, local + 26)[0]
+ if bytes(out[local + 30 : local + 30 + name_len]) == encoded:
+ struct.pack_into("<I", out, local + 22, size)
+ break
+ local += 4
+ central = 0
+ while True:
+ central = out.index(b"PK\x01\x02", central)
+ name_len = struct.unpack_from("<H", out, central + 28)[0]
+ if bytes(out[central + 46 : central + 46 + name_len]) == encoded:
+ struct.pack_into("<I", out, central + 24, size)
+ return bytes(out)
+ central += 4
+
+
+def _method_zip(method: int, payload: bytes) -> bytes:
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("word/document.xml", b"<w/>")
+ zf.writestr("word/media/blob.bin", payload, compress_type=method)
+ return buf.getvalue()
+
+
+def _optional_methods():
+ methods = [
+ pytest.param(zipfile.ZIP_BZIP2, id="bzip2"),
+ pytest.param(zipfile.ZIP_LZMA, id="lzma"),
+ ]
+ zstd = getattr(zipfile, "ZIP_ZSTANDARD", None)
+ if zstd is not None:
+ methods.append(pytest.param(zstd, id="zstd"))
+ return methods
+
+
+class TestCompressionMethodAndHonesty:
+ """zipfile decompresses BZIP2/LZMA/ZSTD with no output limit, and
+ truncates DEFLATE to the declared size only after inflating: the
+ guard allows only STORED/DEFLATE and verifies every declaration.
+
+ Payloads are 64 KiB of zeros, so a regression is detected by the
+ assertion, never by exhausting memory."""
+
+ @pytest.mark.parametrize("method", _optional_methods())
+ def test_non_deflate_methods_are_refused(self, method):
+ guard = _guard()
+ try:
+ data = _method_zip(method, b"\x00" * 65536)
+ except (RuntimeError, NotImplementedError):
+ pytest.skip("this Python cannot write that method")
+ # Lie about the size, as an attacker would.
+ data = _set_declared_size(data, "word/media/blob.bin", 100)
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="compression method"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_deflate_entry_inflating_past_its_declaration_is_refused(self):
+ guard = _guard()
+ data = _zip_bytes({"word/document.xml": b"\x00" * 65536})
+ data = _set_declared_size(data, "word/document.xml", 1000)
+
+ with pytest.raises(guard.DecompressionBombError, match="inflates past"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_stored_entry_with_mismatched_sizes_is_refused(self):
+ guard = _guard()
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_STORED) as zf:
+ zf.writestr("word/document.xml", b"x" * 5000)
+ # Within the DEFLATE slack, so only the STORED rule catches it.
+ data = _set_declared_size(buf.getvalue(), "word/document.xml", 4500)
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="compressed size"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_compressed_range_far_beyond_declaration_is_refused(self):
+ """A full read copies the whole compressed range; it must stay
+ within a small slack of the declared size."""
+ guard = _guard()
+ noise = random.Random(0).randbytes(20_000) # incompressible
+ data = _zip_bytes({"word/document.xml": noise})
+ data = _set_declared_size(data, "word/document.xml", 10)
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="compressed size"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_encrypted_entries_are_refused(self):
+ guard = _guard()
+ data = bytearray(_zip_bytes({"word/document.xml": b"<w/>"}))
+ cd = _central_dir_offset(bytes(data))
+ flags = struct.unpack_from("<H", data, cd + 8)[0] | 0x1
+ struct.pack_into("<H", data, cd + 8, flags)
+
+ with pytest.raises(guard.DecompressionBombError, match="encrypted"):
+ guard.validate_zip_container(bytes(data), ".docx")
+
+ def test_verification_inflates_in_bounded_steps(self):
+ guard = _guard()
+ calls: list = []
+ real = zlib.decompressobj
+
+ class _Recording:
+ def __init__(self, *args):
+ self._inner = real(*args)
+
+ def decompress(self, data, max_length=0):
+ calls.append(max_length)
+ return self._inner.decompress(data, max_length)
+
+ def __getattr__(self, name):
+ return getattr(self._inner, name)
+
+ data = _zip_bytes({"content.xml": b"<a/>" * 500_000})
+ with patch.object(guard.zlib, "decompressobj", _Recording):
+ guard.validate_zip_container(data, ".odt")
+
+ assert calls, "entries were not verified"
+ assert all(0 < n <= 4 * 1024 * 1024 for n in calls), calls
+
+ def test_honest_deflate_and_stored_entries_pass(self):
+ guard = _guard()
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("a.xml", b"<a/>" * 10_000, zipfile.ZIP_DEFLATED)
+ zf.writestr("b.xml", b"<b/>" * 10_000, zipfile.ZIP_STORED)
+ zf.writestr("c.bin", bytes(range(256)) * 100, zipfile.ZIP_DEFLATED)
+
+ guard.validate_zip_container(buf.getvalue(), ".odt")
+
+
+class TestOoxmlCapDefaults:
+ """Structural bounds: generous for real documents, hard ceilings."""
+
+ def test_defaults_hold_realistic_margins(self):
+ guard = _guard()
+
+ # Real office documents stay far below these; bombs from a
+ # 3 GB-compressed upload cap cannot expand past them.
+ # Python XML parse trees cost ~10-20x the XML they parse, so the
+ # entry ceiling must keep that product within a worker's memory.
+ # (It does not bound what loaders build from the tree, such as
+ # pandas' .xlsx grid padding; see the guard's "Known gaps".)
+ assert guard.MAX_ENTRY_BYTES <= 128 * 1024 * 1024
+ assert guard.MAX_TOTAL_BYTES <= 512 * 1024 * 1024
+ assert guard.MAX_ENTRY_BYTES <= guard.MAX_TOTAL_BYTES
+ assert guard.MAX_ENTRIES <= 10_000
+
+ def test_media_defaults_hold_realistic_margins(self):
+ """Media costs ~1x (measured), so it may be larger than a parsed
+ part — but the whole container stays bounded."""
+ guard = _guard()
+
+ assert (
+ guard.MAX_ENTRY_BYTES
+ < guard.MAX_MEDIA_ENTRY_BYTES
+ <= 512 * 1024 * 1024
+ )
+ assert (
+ guard.MAX_TOTAL_BYTES
+ <= guard.MAX_CONTAINER_BYTES
+ <= 1024 * 1024 * 1024
+ )
+ assert guard.MAX_MEDIA_ENTRY_BYTES <= guard.MAX_CONTAINER_BYTES
+
+ def test_benign_real_documents_pass_with_defaults(self):
+ """A genuine docx/xlsx sails through the default ceilings."""
+ docx = pytest.importorskip("docx")
+ from local_deep_research.document_loaders.bytes_loader import (
+ extract_text_from_bytes,
+ )
+
+ buf = io.BytesIO()
+ document = docx.Document()
+ document.add_paragraph("hello ooxml guard")
+ document.save(buf)
+
+ text = extract_text_from_bytes(buf.getvalue(), ".docx", "ok.docx")
+ assert text is not None and "hello ooxml guard" in text
+
+
+_XLSX_CT = (
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
+ '<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
+ '<Default Extension="xml" ContentType="application/xml"/>'
+ '<Default Extension="png" ContentType="image/png"/>'
+ '<Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/>'
+ '<Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/>'
+ '<Override PartName="/xl/chartsheets/sheet2.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml"/>'
+ '<Override PartName="/xl/drawings/drawing1.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"/>'
+ "</Types>"
+)
+_REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+_PKG_RELS = "http://schemas.openxmlformats.org/package/2006/relationships"
+
+
+def _rels(*rels: tuple[str, str, str]) -> str:
+ body = "".join(
+ f'<Relationship Id="{rid}" Type="{_REL_NS}/{kind}" Target="{target}"/>'
+ for rid, kind, target in rels
+ )
+ return f'<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="{_PKG_RELS}">{body}</Relationships>'
+
+
+def _xlsx_with_image_references(references: int, image: bytes) -> bytes:
+ """A chartsheet whose drawing references ONE image N times."""
+ anchor = (
+ '<xdr:absoluteAnchor><xdr:pos x="0" y="0"/><xdr:ext cx="1" cy="1"/>'
+ '<xdr:pic><xdr:nvPicPr><xdr:cNvPr id="{i}" name="p{i}"/><xdr:cNvPicPr/>'
+ '</xdr:nvPicPr><xdr:blipFill><a:blip r:embed="rId1"/></xdr:blipFill>'
+ "<xdr:spPr/></xdr:pic><xdr:clientData/></xdr:absoluteAnchor>"
+ )
+ parts = {
+ "[Content_Types].xml": _XLSX_CT,
+ "_rels/.rels": _rels(("rId1", "officeDocument", "xl/workbook.xml")),
+ "xl/workbook.xml": (
+ '<?xml version="1.0" encoding="UTF-8"?><workbook xmlns='
+ '"http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
+ f'xmlns:r="{_REL_NS}"><sheets>'
+ '<sheet name="S1" sheetId="1" r:id="rId1"/>'
+ '<sheet name="C1" sheetId="2" r:id="rId2"/></sheets></workbook>'
+ ),
+ "xl/_rels/workbook.xml.rels": _rels(
+ ("rId1", "worksheet", "worksheets/sheet1.xml"),
+ ("rId2", "chartsheet", "chartsheets/sheet2.xml"),
+ ),
+ "xl/worksheets/sheet1.xml": (
+ '<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns='
+ '"http://schemas.openxmlformats.org/spreadsheetml/2006/main">'
+ '<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>hello'
+ "</t></is></c></row></sheetData></worksheet>"
+ ),
+ "xl/chartsheets/sheet2.xml": (
+ '<?xml version="1.0" encoding="UTF-8"?><chartsheet xmlns='
+ '"http://schemas.openxmlformats.org/spreadsheetml/2006/main" '
+ f'xmlns:r="{_REL_NS}"><sheetViews><sheetView workbookViewId="0"/>'
+ '</sheetViews><drawing r:id="rId1"/></chartsheet>'
+ ),
+ "xl/chartsheets/_rels/sheet2.xml.rels": _rels(
+ ("rId1", "drawing", "../drawings/drawing1.xml")
+ ),
+ "xl/drawings/drawing1.xml": (
+ '<?xml version="1.0" encoding="UTF-8"?><xdr:wsDr xmlns:xdr='
+ '"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing" '
+ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" '
+ f'xmlns:r="{_REL_NS}">'
+ + "".join(anchor.format(i=i + 2) for i in range(references))
+ + "</xdr:wsDr>"
+ ),
+ "xl/drawings/_rels/drawing1.xml.rels": _rels(
+ ("rId1", "image", "../media/image1.png")
+ ),
+ }
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ for name, text in parts.items():
+ zf.writestr(name, text)
+ zf.writestr("xl/media/image1.png", image)
+ return buf.getvalue()
+
+
+def _small_png() -> bytes:
+ pil = pytest.importorskip("PIL.Image")
+ out = io.BytesIO()
+ pil.new("RGB", (2, 2)).save(out, "PNG")
+ return out.getvalue() + b"\x00" * 65536
+
+
+@contextmanager
+def _counting_reads(member: str):
+ reads: list = []
+ real = zipfile.ZipFile.read
+
+ def spy(self, name, *args, **kwargs):
+ target = name.filename if isinstance(name, zipfile.ZipInfo) else name
+ if target == member:
+ reads.append(target)
+ return real(self, name, *args, **kwargs)
+
+ with patch.object(zipfile.ZipFile, "read", spy):
+ yield reads
+
+
+class TestReferenceFanOut:
+ """One entry referenced N times must not be read N times.
+
+ openpyxl reads a drawing image once per reference and keeps every
+ copy, so a ~100 KB .xlsx referencing one large image N times costs
+ N times its size — no per-entry ceiling bounds that. The .xlsx path
+ disables openpyxl's drawing reader. python-pptx/python-docx load
+ each part once, so they are pinned here too."""
+
+ REFS = 8
+
+ def test_premise_openpyxl_reads_an_image_once_per_reference(self):
+ """Control: with openpyxl's own hook, reads scale with refs."""
+ openpyxl = pytest.importorskip("openpyxl")
+ import openpyxl.reader.excel as excel_reader
+ from openpyxl.reader.drawings import find_images
+
+ data = _xlsx_with_image_references(self.REFS, _small_png())
+ with (
+ patch.object(excel_reader, "find_images", find_images),
+ _counting_reads("xl/media/image1.png") as reads,
+ ):
+ openpyxl.load_workbook(io.BytesIO(data), read_only=True)
+
+ assert len(reads) == self.REFS
+
+ def test_xlsx_upload_never_reads_drawing_images(self):
+ pytest.importorskip("openpyxl")
+ import openpyxl.reader.excel as excel_reader
+ from openpyxl.reader.drawings import find_images
+
+ from local_deep_research.document_loaders import (
+ extract_text_from_bytes,
+ )
+ from local_deep_research.document_loaders.loader_registry import (
+ LOADER_REGISTRY,
+ )
+
+ if ".xlsx" not in LOADER_REGISTRY:
+ pytest.skip(".xlsx not registered in this environment")
+ data = _xlsx_with_image_references(self.REFS, _small_png())
+ # Start from openpyxl's own hook so the upload path must apply
+ # the hardening itself.
+ with (
+ patch.object(excel_reader, "find_images", find_images),
+ _counting_reads("xl/media/image1.png") as reads,
+ ):
+ text = extract_text_from_bytes(data, ".xlsx", "amp.xlsx")
+
+ assert text is not None and "hello" in text
+ assert reads == [], f"image read {len(reads)}x for {self.REFS} refs"
+
+ def test_xlsx_upload_rejects_when_drawing_hook_disappears(
+ self, monkeypatch
+ ):
+ """An openpyxl upgrade must not restore unbounded drawing reads."""
+ pytest.importorskip("openpyxl")
+ import openpyxl.reader.excel as excel_reader
+
+ from local_deep_research.document_loaders.bytes_loader import (
+ load_from_bytes,
+ )
+ from local_deep_research.document_loaders.zip_container_guard import (
+ DecompressionBombError,
+ )
+
+ data = _xlsx_with_image_references(1, _small_png())
+ monkeypatch.delattr(excel_reader, "find_images")
+ with pytest.raises(
+ DecompressionBombError, match="drawing guard unavailable"
+ ):
+ load_from_bytes(data, ".xlsx", "untrusted.xlsx")
+
+ def test_openpyxl_still_exposes_the_hook(self):
+ """Pin the openpyxl drawing hook used by this hardening."""
+ pytest.importorskip("openpyxl")
+ import openpyxl.reader.excel as excel_reader
+
+ from local_deep_research.document_loaders import openpyxl_hardening
+
+ assert hasattr(excel_reader, "find_images")
+ assert openpyxl_hardening.disable_openpyxl_drawing_reads() is True
+
+ @pytest.mark.parametrize("ext", [".pptx", ".docx"])
+ def test_pptx_and_docx_read_a_shared_image_once(self, ext):
+ from local_deep_research.document_loaders import (
+ extract_text_from_bytes,
+ )
+
+ png = _small_png()
+ buf = io.BytesIO()
+ if ext == ".pptx":
+ pptx = pytest.importorskip("pptx")
+ from pptx.util import Inches
+
+ deck = pptx.Presentation()
+ for i in range(self.REFS):
+ slide = deck.slides.add_slide(deck.slide_layouts[5])
+ slide.shapes.title.text = f"slide {i}"
+ slide.shapes.add_picture(io.BytesIO(png), Inches(1), Inches(1))
+ deck.save(buf)
+ member = "ppt/media/image1.png"
+ else:
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ for i in range(self.REFS):
+ document.add_paragraph(f"para {i}")
+ document.add_picture(io.BytesIO(png))
+ document.save(buf)
+ member = "word/media/image1.png"
+
+ with _counting_reads(member) as reads:
+ text = extract_text_from_bytes(buf.getvalue(), ext, f"x{ext}")
+
+ assert text is not None
+ assert len(reads) <= 1, f"{member} read {len(reads)}x"
+
+
+_SHEET_MAIN = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
+_WORKBOOK_CT = (
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"
+)
+
+
+def _external(rels_xml: str, rel_ids: frozenset[str]) -> str:
+ """Mark the given relationship ids ``TargetMode="External"``."""
+ for rel_id in rel_ids:
+ rels_xml = rels_xml.replace(
+ f'Id="{rel_id}" ', f'Id="{rel_id}" TargetMode="External" '
+ )
+ return rels_xml
+
+
+def _xlsx_with_sheets(
+ sheet_ids: list[str],
+ rels: list[tuple[str, str]],
+ workbook: str = "xl/workbook.xml",
+ override: bool = True,
+ external: frozenset[str] = frozenset(),
+ workbook_decl: str = '<?xml version="1.0" encoding="UTF-8"?>',
+) -> bytes:
+ """Workbook whose ``<sheet>`` r:ids and relationship targets are
+ given explicitly; ``xl/worksheets/sheet{1,2}.xml`` exist."""
+ sheets = "".join(
+ f'<sheet name="S{i}" sheetId="{i + 1}" r:id="{rid}"/>'
+ for i, rid in enumerate(sheet_ids)
+ )
+ worksheet = (
+ '<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="{ns}">'
+ '<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>{text}</t>'
+ "</is></c></row></sheetData></worksheet>"
+ )
+ parts = {
+ "[Content_Types].xml": (
+ '<?xml version="1.0" encoding="UTF-8"?><Types xmlns='
+ '"http://schemas.openxmlformats.org/package/2006/content-types">'
+ '<Default Extension="rels" ContentType="application/'
+ 'vnd.openxmlformats-package.relationships+xml"/>'
+ '<Default Extension="xml" ContentType="application/xml"/>'
+ + (
+ f'<Override PartName="/{workbook}" ContentType="{_WORKBOOK_CT}"/>'
+ if override
+ else ""
+ )
+ + "</Types>"
+ ),
+ "_rels/.rels": _rels(("rId1", "officeDocument", workbook)),
+ workbook: (
+ f'{workbook_decl}<workbook xmlns="{_SHEET_MAIN}" '
+ f'xmlns:r="{_REL_NS}"><sheets>{sheets}</sheets></workbook>'
+ ),
+ posixpath.join(
+ posixpath.dirname(workbook),
+ "_rels",
+ posixpath.basename(workbook) + ".rels",
+ ): _external(
+ _rels(*((rid, "worksheet", target) for rid, target in rels)),
+ external,
+ ),
+ "xl/worksheets/sheet1.xml": worksheet.format(
+ ns=_SHEET_MAIN, text="one"
+ ),
+ "xl/worksheets/sheet2.xml": worksheet.format(
+ ns=_SHEET_MAIN, text="two"
+ ),
+ }
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ for name, text in parts.items():
+ zf.writestr(name, text)
+ return buf.getvalue()
+
+
+class TestSheetFanOut:
+ """openpyxl converts a worksheet once per ``<sheet>`` that resolves
+ to it: N entries sharing one part multiply parsing work and text by
+ N. Genuine workbooks never share a sheet part, so it is refused."""
+
+ def test_repeated_rid_is_refused(self):
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1"] * 4, [("rId1", "worksheets/sheet1.xml")]
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="same sheet"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ @pytest.mark.parametrize(
+ "second_target",
+ [
+ "worksheets/sheet1.xml",
+ "/xl/worksheets/sheet1.xml",
+ "./worksheets/../worksheets/sheet1.xml",
+ ],
+ )
+ def test_distinct_rels_to_one_target_are_refused(self, second_target):
+ """openpyxl resolves each relationship target itself (relative,
+ ``/``-rooted, ``./..`` forms); two that resolve to the same
+ member name are one part read twice."""
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1", "rId2"],
+ [("rId1", "worksheets/sheet1.xml"), ("rId2", second_target)],
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="same sheet"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_workbook_located_through_content_types_is_checked(self):
+ """openpyxl finds the workbook by content type, so a workbook at
+ a non-default path is checked too."""
+ guard = _guard()
+ # With an xl/workbook.xml that openpyxl does not read, which
+ # pandas needs to pick openpyxl at all.
+ data = _rewrite_zip(
+ _xlsx_with_sheets(
+ ["rId1"] * 3,
+ [("rId1", "worksheets/sheet1.xml")],
+ workbook="xl/book.xml",
+ ),
+ add={"xl/workbook.xml": b"<unread/>"},
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="same sheet"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_workbook_without_a_workbook_override_is_refused(self):
+ """openpyxl cannot locate this workbook (no workbook content
+ type), so the guard cannot resolve its sheets: fail closed."""
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1"] * 3, [("rId1", "worksheets/sheet1.xml")], override=False
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_repeated_relationship_id_is_refused(self):
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1", "rId2"],
+ [
+ ("rId1", "worksheets/sheet1.xml"),
+ ("rId1", "worksheets/sheet2.xml"),
+ ("rId2", "worksheets/sheet2.xml"),
+ ],
+ )
+
+ # openpyxl keeps the last duplicate Id, so both sheets resolve
+ # to sheet2.xml.
+ with pytest.raises(guard.DecompressionBombError, match="same sheet"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_distinct_sheets_are_accepted(self):
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1", "rId2"],
+ [
+ ("rId1", "worksheets/sheet1.xml"),
+ ("rId2", "worksheets/sheet2.xml"),
+ ],
+ )
+
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_upload_path_refuses_fan_out_and_keeps_real_workbooks(self):
+ openpyxl = pytest.importorskip("openpyxl")
+ from local_deep_research.document_loaders import (
+ extract_text_from_bytes,
+ )
+ from local_deep_research.document_loaders.loader_registry import (
+ LOADER_REGISTRY,
+ )
+
+ if ".xlsx" not in LOADER_REGISTRY:
+ pytest.skip(".xlsx not registered in this environment")
+
+ fan_out = _xlsx_with_sheets(
+ ["rId1"] * 4, [("rId1", "worksheets/sheet1.xml")]
+ )
+ assert extract_text_from_bytes(fan_out, ".xlsx", "fan.xlsx") is None
+
+ workbook = openpyxl.Workbook()
+ workbook.active["A1"] = "alpha"
+ for i in range(3):
+ workbook.create_sheet(f"S{i}")["A1"] = f"beta{i}"
+ buf = io.BytesIO()
+ workbook.save(buf)
+ text = extract_text_from_bytes(buf.getvalue(), ".xlsx", "ok.xlsx")
+ assert text is not None
+ assert "alpha" in text and "beta2" in text
+
+
+class TestSheetFanOutExternalAndEncoding:
+ def test_external_rel_naming_the_internal_part_is_refused(self):
+ """openpyxl keeps an External target unresolved and still loads
+ it when the raw string names a package part."""
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1", "rId2"],
+ [
+ ("rId1", "worksheets/sheet1.xml"),
+ ("rId2", "xl/worksheets/sheet1.xml"),
+ ],
+ external=frozenset({"rId2"}),
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="same sheet"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_bogus_xml_encoding_fails_closed(self):
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1"],
+ [("rId1", "worksheets/sheet1.xml")],
+ workbook_decl='<?xml version="1.0" encoding="no-such-codec"?>',
+ )
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+
+def _document_zip(name: str, body: bytes) -> bytes:
+ return _zip_bytes(
+ _ooxml_package(
+ {"word/_rels/document.xml.rels": b"<r/>", name: body}, ".docx"
+ )
+ )
+
+
+class TestMediaClassifierIsAnchored:
+ """Only bytes no XML parser accepts as a document start may earn
+ the media ceiling."""
+
+ MARKUP = b"<w:document>" + b"<w:p>payload</w:p>" * 200_000
+
+ @pytest.mark.parametrize(
+ "head",
+ [
+ pytest.param(b"<!--ftyp-->", id="comment-ftyp"),
+ pytest.param(b" \n<?xml version='1.0'?>", id="whitespace-decl"),
+ pytest.param(b"\xef\xbb\xbf<", id="utf8-bom"),
+ pytest.param("<!--x-->".encode("utf-16-le"), id="utf16le-no-bom"),
+ pytest.param("<a".encode("utf-16-be"), id="utf16be-bom"),
+ pytest.param("<a".encode("utf-32-le"), id="utf32le-no-bom"),
+ ],
+ )
+ def test_markup_head_stays_a_parsed_part(self, head):
+ guard = _guard()
+ data = _document_zip("word/document.bin", head + self.MARKUP)
+
+ with pytest.raises(guard.DecompressionBombError, match="ceiling"):
+ guard.validate_zip_container(data, ".docx", **_SCALED)
+
+ def test_ftyp_needs_a_plausible_box_size(self):
+ guard = _guard()
+ head = b"\x00\x00\x00\x04ftypisom" # box size 4 < 8
+ data = _document_zip("word/media/v.mp4", head + b"\x00" * 3_000_000)
+
+ with pytest.raises(guard.DecompressionBombError, match="ceiling"):
+ guard.validate_zip_container(data, ".docx", **_SCALED)
+
+ def test_ftyp_without_a_box_shape_is_not_media(self):
+ """``ftyp`` at offset 4 alone is not enough: the head must start
+ with the two zero bytes of a plausible box size."""
+ guard = _guard()
+ data = _document_zip(
+ "word/media/v.mp4", b"ABCDftypisom" + b"\x00" * 3_000_000
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="ceiling"):
+ guard.validate_zip_container(data, ".docx", **_SCALED)
+
+ def test_mp4_with_a_60_byte_ftyp_box_is_media(self):
+ """00 00 00 3C reads as "<" in UTF-32BE, but "ftyp" as UCS-4 is
+ above U+10FFFF, so no XML parser accepts this head: it must keep
+ the media ceiling."""
+ guard = _guard()
+ head = b"\x00\x00\x00\x3cftypisom"
+ data = _document_zip("word/media/v.mp4", head + b"\x00" * 3_000_000)
+
+ guard.validate_zip_container(data, ".docx", **_SCALED)
+
+ def test_real_mp4_head_is_still_media(self):
+ guard = _guard()
+ head = b"\x00\x00\x00\x18ftypisom"
+ data = _document_zip("word/media/v.mp4", head + b"\x00" * 3_000_000)
+
+ guard.validate_zip_container(data, ".docx", **_SCALED)
+
+
+class TestDeclarationChecksBeforeInflation:
+ def test_oversized_declaration_is_refused_without_inflating(self):
+ guard = _guard()
+ data = _zip_bytes({"word/media/a.png": _PNG + b"\x00" * 5_000_000})
+
+ def boom(*args, **kwargs):
+ raise AssertionError("entry inflated before its size was checked")
+
+ with patch.object(guard, "_inflate_head", boom):
+ with pytest.raises(guard.DecompressionBombError, match="ceiling"):
+ guard.validate_zip_container(data, ".docx", **_SCALED)
+
+ def test_entries_sharing_a_local_header_are_refused(self):
+ guard = _guard()
+ data = bytearray(
+ _zip_bytes({"word/a.xml": b"<a/>", "word/b.xml": b"<b/>"})
+ )
+ first = data.index(b"PK\x01\x02")
+ second = data.index(b"PK\x01\x02", first + 4)
+ offset = struct.unpack_from("<I", data, first + 42)[0]
+ struct.pack_into("<I", data, second + 42, offset)
+
+ with pytest.raises(guard.DecompressionBombError, match="local header"):
+ guard.validate_zip_container(bytes(data), ".docx")
+
+ def test_local_extra_field_is_honoured(self):
+ """The data offset uses the LOCAL header's extra length, which
+ may differ from the central directory's (as zipfile reads it)."""
+ guard = _guard()
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ info = zipfile.ZipInfo("word/document.xml")
+ info.compress_type = zipfile.ZIP_DEFLATED
+ info.extra = struct.pack("<HH", 0xCAFE, 12) + b"x" * 12
+ zf.writestr(info, b"<w:document>" + b"<w:p/>" * 5000)
+ data = bytearray(buf.getvalue())
+ # Drop the extra field from the central record only: 16 bytes in
+ # the local header, 0 in the central directory.
+ central = data.index(b"PK\x01\x02")
+ name_len, extra_len = struct.unpack_from("<HH", data, central + 28)
+ assert extra_len == 16
+ struct.pack_into("<H", data, central + 30, 0)
+ start = central + 46 + name_len
+ del data[start : start + extra_len]
+ eocd = data.rindex(b"PK\x05\x06")
+ size = struct.unpack_from("<I", data, eocd + 12)[0]
+ struct.pack_into("<I", data, eocd + 12, size - extra_len)
+ assert (
+ zipfile.ZipFile(io.BytesIO(bytes(data)))
+ .read("word/document.xml")
+ .startswith(b"<w:document>")
+ )
+
+ # .odt: a lone .docx part without its package is refused for
+ # its layout (TestPackageTypeMatchesTheExtension).
+ guard.validate_zip_container(bytes(data), ".odt")
+
+
+class TestHardeningIdempotence:
+ def test_reloaded_hook_is_patched_again(self):
+ """Identity, not a flag: a restored original hook (as after a
+ reload of openpyxl) is replaced again."""
+ pytest.importorskip("openpyxl")
+ import openpyxl.reader.excel as excel_reader
+ from openpyxl.reader.drawings import find_images
+
+ from local_deep_research.document_loaders import openpyxl_hardening
+
+ openpyxl_hardening.disable_openpyxl_drawing_reads()
+ with patch.object(excel_reader, "find_images", find_images):
+ assert openpyxl_hardening.disable_openpyxl_drawing_reads() is True
+ assert excel_reader.find_images is openpyxl_hardening._no_drawings
+
+
+def _openpyxl_shaped_xlsx(
+ sheets_xml: str,
+ rels_xml: str,
+ workbook_entry: str = "xl/workbook.xml",
+ workbook_partname: str = "/xl/workbook.xml",
+ rels_prefix: bytes = b"",
+ extra: dict | None = None,
+) -> bytes:
+ """Hand-built workbook with full control over tags and paths."""
+ parts = {
+ "[Content_Types].xml": (
+ '<?xml version="1.0" encoding="UTF-8"?><Types xmlns='
+ '"http://schemas.openxmlformats.org/package/2006/content-types">'
+ '<Default Extension="rels" ContentType="application/'
+ 'vnd.openxmlformats-package.relationships+xml"/>'
+ '<Default Extension="xml" ContentType="application/xml"/>'
+ f'<Override PartName="{workbook_partname}" '
+ f'ContentType="{_WORKBOOK_CT}"/></Types>'
+ ).encode(),
+ "_rels/.rels": (
+ f'<Relationships xmlns="{_PKG_RELS}"><Relationship Id="rId1" '
+ f'Type="{_REL_NS}/officeDocument" Target="{workbook_entry}"/>'
+ "</Relationships>"
+ ).encode(),
+ workbook_entry: (
+ f'<workbook xmlns="{_SHEET_MAIN}" xmlns:r="{_REL_NS}">'
+ f"<sheets>{sheets_xml}</sheets></workbook>"
+ ).encode(),
+ posixpath.join(
+ posixpath.dirname(workbook_entry),
+ "_rels",
+ posixpath.basename(workbook_entry) + ".rels",
+ ): rels_prefix
+ + f'<Relationships xmlns="{_PKG_RELS}">{rels_xml}</Relationships>'.encode(),
+ }
+ sheet = (
+ f'<worksheet xmlns="{_SHEET_MAIN}"><sheetData><row r="1"><c r="A1" '
+ 't="inlineStr"><is><t>{}</t></is></c></row></sheetData></worksheet>'
+ )
+ parts["xl/worksheets/sheet1.xml"] = sheet.format("one").encode()
+ parts["xl/worksheets/sheet2.xml"] = sheet.format("two").encode()
+ parts.update(extra or {})
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
+ for name, body in parts.items():
+ zf.writestr(name, body)
+ return buf.getvalue()
+
+
+def _ws_rel(rel_id: str, target: str, tag: str = "Relationship") -> str:
+ return (
+ f'<{tag} Id="{rel_id}" Type="{_REL_NS}/worksheet" Target="{target}"/>'
+ )
+
+
+def _sheet(n: int, rel_id: str, attr: str = "r:id", tag: str = "sheet") -> str:
+ return f'<{tag} name="s{n}" sheetId="{n}" {attr}="{rel_id}"/>'
+
+
+class TestSheetFanOutFollowsOpenpyxl:
+ """Shapes where a re-implemented parser and openpyxl disagreed: the
+ guard now asks openpyxl itself which part each sheet names."""
+
+ @staticmethod
+ def _assert_refused(data: bytes) -> None:
+ guard = _guard()
+ with pytest.raises(guard.DecompressionBombError, match="same sheet"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_relationship_child_with_any_tag(self):
+ pytest.importorskip("openpyxl")
+ self._assert_refused(
+ _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1") + _sheet(2, "rId2"),
+ _ws_rel("rId1", "worksheets/sheet1.xml")
+ + _ws_rel("rId2", "worksheets/sheet1.xml", tag="Foo"),
+ )
+ )
+
+ def test_sheet_child_with_any_tag(self):
+ pytest.importorskip("openpyxl")
+ self._assert_refused(
+ _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1") + _sheet(2, "rId1", tag="foo"),
+ _ws_rel("rId1", "worksheets/sheet1.xml"),
+ )
+ )
+
+ def test_plain_id_attribute(self):
+ pytest.importorskip("openpyxl")
+ self._assert_refused(
+ _openpyxl_shaped_xlsx(
+ "".join(_sheet(i, "rId1", attr="id") for i in range(1, 5)),
+ _ws_rel("rId1", "worksheets/sheet1.xml"),
+ )
+ )
+
+ def test_workbook_partname_without_leading_slash(self):
+ """openpyxl derives the part as ``PartName[1:]``."""
+ pytest.importorskip("openpyxl")
+ self._assert_refused(
+ _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1") + _sheet(2, "rId1"),
+ _ws_rel("rId1", "/xl/worksheets/sheet1.xml"),
+ workbook_entry="l/workbook.xml",
+ workbook_partname="xl/workbook.xml",
+ # Read by pandas' engine choice only, not by openpyxl.
+ extra={"xl/workbook.xml": b"<unread/>"},
+ )
+ )
+
+ def test_bom_and_declared_encoding_disagree(self):
+ """UTF-8 BOM with a Latin-1 declaration: the relationships part
+ is refused for its declared encoding before openpyxl parses it
+ (an encoding other than UTF-8 is refused in every part openpyxl
+ parses)."""
+ pytest.importorskip("openpyxl")
+ guard = _guard()
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(
+ self._bom_and_latin1_workbook(), ".xlsx"
+ )
+
+ @staticmethod
+ def _bom_and_latin1_workbook() -> bytes:
+ return _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1") + _sheet(2, "rId2"),
+ _ws_rel("rId1", "worksheets/&#233;.xml")
+ + _ws_rel("rId2", "worksheets/\u00e9.xml"),
+ rels_prefix=(
+ b'\xef\xbb\xbf<?xml version="1.0" encoding="ISO-8859-1"?>'
+ ),
+ extra={
+ "xl/worksheets/\u00e9.xml": (
+ f'<worksheet xmlns="{_SHEET_MAIN}"><sheetData/></worksheet>'
+ ).encode()
+ },
+ )
+
+ def test_openpyxl_failure_is_refused_as_malformed(self):
+ pytest.importorskip("openpyxl")
+ guard = _guard()
+ data = _openpyxl_shaped_xlsx(
+ _sheet(1, "rId9"), _ws_rel("rId1", "worksheets/sheet1.xml")
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(data, ".xlsx")
+
+
+class TestSheetFanOutCheckReadsOnlyThePackageSkeleton:
+ def test_no_worksheet_drawing_or_string_part_is_opened(self):
+ """The fan-out check parses [Content_Types].xml, the workbook
+ and its relationships, and streams the styles part — nothing a
+ sheet could amplify. (The namespace scan before it streams every
+ member once, building no tree; see TestXlsxReadPathStringWork.)"""
+ openpyxl = pytest.importorskip("openpyxl")
+ workbook = openpyxl.Workbook()
+ workbook.active["A1"] = "alpha"
+ workbook.create_sheet("S1")["A1"] = "beta"
+ buf = io.BytesIO()
+ workbook.save(buf)
+ guard = _guard()
+
+ opened: list = []
+ real_open = zipfile.ZipFile.open
+
+ def spy(self, name, *args, **kwargs):
+ opened.append(
+ name.filename if isinstance(name, zipfile.ZipInfo) else name
+ )
+ return real_open(self, name, *args, **kwargs)
+
+ # The guard's own verification inflates entries from the raw
+ # bytes, so every ZipFile.open during validation is openpyxl's.
+ with (
+ patch.object(zipfile.ZipFile, "open", spy),
+ patch.object(guard, "_check_xlsx_namespaces", lambda *_a: None),
+ ):
+ guard.validate_zip_container(buf.getvalue(), ".xlsx")
+
+ assert set(opened) <= {
+ "[Content_Types].xml",
+ "xl/workbook.xml",
+ "xl/_rels/workbook.xml.rels",
+ "xl/styles.xml",
+ }, opened
+
+
+class TestCanonicalMemberNames:
+ """Member names that readers normalise onto another path are
+ refused before anything is inflated; real writers never emit them."""
+
+ @pytest.mark.parametrize(
+ "name",
+ [
+ pytest.param("xl//worksheets/sheet3.xml", id="double-slash"),
+ pytest.param("xl/./worksheets/sheet3.xml", id="dot-segment"),
+ pytest.param("xl/../xl/worksheets/sheet3.xml", id="dotdot"),
+ pytest.param("/xl/worksheets/sheet3.xml", id="leading-slash"),
+ pytest.param("xl\\worksheets\\sheet3.xml", id="backslash"),
+ ],
+ )
+ def test_non_canonical_name_is_refused(self, name):
+ guard = _guard()
+ data = _zip_bytes({"word/document.xml": b"<w/>", name: b"<a/>"})
+
+ with pytest.raises(guard.DecompressionBombError, match="non-canonical"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_duplicate_member_name_is_refused(self):
+ guard = _guard()
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("word/document.xml", b"<w/>")
+ with pytest.warns(UserWarning):
+ zf.writestr("word/document.xml", b"<w2/>")
+
+ with pytest.raises(guard.DecompressionBombError, match="same name"):
+ guard.validate_zip_container(buf.getvalue(), ".docx")
+
+ def test_directory_entries_are_allowed(self):
+ guard = _guard()
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("OEBPS/", b"")
+ zf.writestr("OEBPS/c.xhtml", b"<html/>")
+
+ guard.validate_zip_container(buf.getvalue(), ".epub")
+
+ @pytest.mark.parametrize("fmt", ["docx", "pptx", "odt", "epub"])
+ def test_pandoc_written_containers_pass(self, fmt, tmp_path):
+ pypandoc = pytest.importorskip("pypandoc")
+ try:
+ pypandoc.get_pandoc_path()
+ except OSError:
+ pytest.skip("pandoc not available")
+ out = tmp_path / f"doc.{fmt}"
+ pypandoc.convert_text(
+ "# Title\n\nhello\n", fmt, format="md", outputfile=str(out)
+ )
+
+ _guard().validate_zip_container(out.read_bytes(), f".{fmt}")
+
+
+class TestSheetRelationshipsPartsAreUnique:
+ def test_sheets_sharing_one_rels_part_are_refused(self):
+ """openpyxl finds each sheet's relationships via get_rels_path,
+ which can map distinct targets onto one part; the check uses
+ that same function. (Pass 1 already refuses the member names
+ that could produce this, so it is isolated here.)"""
+ pytest.importorskip("openpyxl")
+ guard = _guard()
+ data = _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1") + _sheet(2, "rId2"),
+ _ws_rel("rId1", "worksheets/sheet1.xml")
+ + _ws_rel("rId2", "worksheets/sheet2.xml"),
+ )
+ from openpyxl.packaging import relationship
+
+ with patch.object(
+ relationship,
+ "get_rels_path",
+ lambda path: "xl/worksheets/_rels/shared.xml.rels",
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="relationships part"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+
+class TestMediaCeilingIsOoxmlOnly:
+ def test_epub_entry_with_media_head_stays_a_parsed_part(self):
+ """pandoc reads an EPUB chapter by its manifest media type, not
+ its bytes, so no EPUB/ODT entry earns the media ceiling."""
+ guard = _guard()
+ chapter = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 3_000_000
+ data = _zip_bytes(
+ {"mimetype": b"application/epub+zip", "c.bin": chapter}
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="ceiling"):
+ guard.validate_zip_container(data, ".epub", **_SCALED)
+
+ def test_same_entry_in_ooxml_is_media(self):
+ guard = _guard()
+ chapter = b"\x00\x00\x00\x18ftypisom" + b"\x00" * 3_000_000
+ data = _zip_bytes(
+ _ooxml_package({"word/media/v.mp4": chapter}, ".docx")
+ )
+
+ guard.validate_zip_container(data, ".docx", **_SCALED)
+
+
+class TestXlsxSkeletonCeiling:
+ @pytest.mark.parametrize(
+ ("part", "unparsed_step"),
+ [
+ ("[Content_Types].xml", "read_manifest"),
+ ("xl/workbook.xml", "read_workbook"),
+ ("xl/_rels/workbook.xml.rels", "read_workbook"),
+ ],
+ )
+ def test_each_oversized_skeleton_part_is_refused_before_parsing(
+ self, part, unparsed_step
+ ):
+ """Only *part* is padded past the ceiling (the other two stay
+ under it), and the openpyxl step that would parse it never runs."""
+ pytest.importorskip("openpyxl")
+ from openpyxl.reader.excel import ExcelReader
+
+ guard = _guard()
+ base = _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1"), _ws_rel("rId1", "worksheets/sheet1.xml")
+ )
+ padding = b"<!--" + b"x" * 10_000 + b"-->"
+ src = zipfile.ZipFile(io.BytesIO(base))
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as out:
+ for info in src.infolist():
+ body = src.read(info)
+ if info.filename == part:
+ body += padding
+ out.writestr(info.filename, body)
+ data = buf.getvalue()
+ sizes = {
+ i.filename: i.file_size
+ for i in zipfile.ZipFile(io.BytesIO(data)).infolist()
+ }
+ ceiling = 5_000
+ skeleton = [
+ "[Content_Types].xml",
+ "xl/workbook.xml",
+ "xl/_rels/workbook.xml.rels",
+ ]
+ assert sizes[part] > ceiling
+ assert all(
+ sizes[other] < ceiling for other in skeleton if other != part
+ )
+
+ calls: list = []
+ real_step = getattr(ExcelReader, unparsed_step)
+
+ def recording(self, *args, **kwargs):
+ calls.append(unparsed_step)
+ return real_step(self, *args, **kwargs)
+
+ with (
+ patch.object(guard, "MAX_XLSX_SKELETON_PART_BYTES", ceiling),
+ patch.object(ExcelReader, unparsed_step, recording),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="larger than"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ assert calls == [], f"{unparsed_step} parsed the oversized {part}"
+
+ def test_skeleton_ceiling_is_generous_for_real_workbooks(self):
+ guard = _guard()
+
+ assert 1024 * 1024 <= guard.MAX_XLSX_SKELETON_PART_BYTES
+ assert guard.MAX_XLSX_SKELETON_PART_BYTES <= guard.MAX_ENTRY_BYTES // 4
+
+
+class TestFanOutCheckImportPlacement:
+ def test_missing_openpyxl_helper_refuses_rather_than_skips(
+ self, monkeypatch
+ ):
+ """The helper imports sit inside the fail-closed block: if an
+ openpyxl upgrade drops one, .xlsx uploads are refused as
+ malformed instead of the fan-out check silently switching off."""
+ pytest.importorskip("openpyxl")
+ from openpyxl.packaging import relationship
+
+ guard = _guard()
+ data = _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1") + _sheet(2, "rId2"),
+ _ws_rel("rId1", "worksheets/sheet1.xml")
+ + _ws_rel("rId2", "worksheets/sheet2.xml"),
+ )
+ guard.validate_zip_container(data, ".xlsx") # control: accepted
+
+ monkeypatch.delattr(relationship, "get_rels_path")
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(data, ".xlsx")
+
+
+# --- Local header vs central directory ------------------------------------
+#
+# pandoc's zip reader takes an entry's method and compressed size from
+# the LOCAL header, zipfile from the central directory. An entry whose
+# two headers disagree is checked here as one stream and inflated by
+# pandoc as another, so the headers must agree and the DEFLATE stream
+# must end exactly at its declared compressed size.
+
+#: Local file header field offsets (APPNOTE 4.3.7).
+_LH_FLAGS, _LH_METHOD, _LH_CRC, _LH_CSIZE, _LH_USIZE = 6, 8, 14, 18, 22
+#: Central directory record field offsets (APPNOTE 4.3.12).
+_CD_CRC, _CD_CSIZE, _CD_USIZE = 16, 20, 24
+
+
+def _noisy_xml(n: int = 4000) -> bytes:
+ """Poorly compressible markup (KB-scale), so a prefix of its
+ DEFLATE stream is a genuinely truncated stream."""
+ rng = random.Random(6515)
+ return b"<p>" + bytes(rng.randrange(97, 123) for _ in range(n)) + b"</p>"
+
+
+def _single_entry(name: str, payload: bytes) -> bytearray:
+ return bytearray(_zip_bytes({name: payload}))
+
+
+def _inflated_len(stream: bytes) -> int:
+ return len(zlib.decompressobj(-zlib.MAX_WBITS).decompress(stream))
+
+
+class TestLocalHeaderAgreesWithCentralDirectory:
+ def _data_start(self, data: bytes) -> int:
+ name_len, extra_len = struct.unpack_from("<HH", data, 26)
+ return 30 + name_len + extra_len
+
+ def test_central_prefix_of_a_longer_local_stream_is_refused(self):
+ """The reviewer's shape: an honest-looking central record that
+ covers only a prefix of the stream the local header declares."""
+ guard = _guard()
+ data = _single_entry("content.xml", _noisy_xml())
+ cd = _central_dir_offset(data)
+ start = self._data_start(data)
+ prefix = 400
+ produced = _inflated_len(bytes(data[start : start + prefix]))
+ struct.pack_into("<I", data, cd + _CD_CSIZE, prefix)
+ struct.pack_into("<I", data, cd + _CD_USIZE, produced)
+
+ with pytest.raises(guard.DecompressionBombError, match="disagrees"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+ def test_stream_truncated_inside_its_range_is_refused(self):
+ """Both headers agree on a range that cuts the stream short:
+ verification must require the end of the DEFLATE stream."""
+ guard = _guard()
+ data = _single_entry("content.xml", _noisy_xml())
+ cd = _central_dir_offset(data)
+ start = self._data_start(data)
+ prefix = 400
+ produced = _inflated_len(bytes(data[start : start + prefix]))
+ for base, csize, usize in (
+ (0, _LH_CSIZE, _LH_USIZE),
+ (cd, _CD_CSIZE, _CD_USIZE),
+ ):
+ struct.pack_into("<I", data, base + csize, prefix)
+ struct.pack_into("<I", data, base + usize, produced)
+
+ with pytest.raises(guard.DecompressionBombError, match="truncated"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+ def test_trailing_bytes_inside_the_range_are_refused(self):
+ guard = _guard()
+ data = _single_entry("content.xml", b"<p>hello</p>")
+ cd = _central_dir_offset(data)
+ for base, csize in ((0, _LH_CSIZE), (cd, _CD_CSIZE)):
+ old = struct.unpack_from("<I", data, base + csize)[0]
+ struct.pack_into("<I", data, base + csize, old + 2)
+
+ with pytest.raises(guard.DecompressionBombError, match="ends before"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+ def test_short_stream_is_refused(self):
+ """Fewer bytes than declared means the declaration is a lie."""
+ guard = _guard()
+ data = _single_entry("content.xml", b"<p>hello</p>")
+ cd = _central_dir_offset(data)
+ for base, usize in ((0, _LH_USIZE), (cd, _CD_USIZE)):
+ old = struct.unpack_from("<I", data, base + usize)[0]
+ struct.pack_into("<I", data, base + usize, old + 10)
+
+ with pytest.raises(guard.DecompressionBombError, match="less than"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+ @pytest.mark.parametrize(
+ "offset, fmt, value",
+ [
+ pytest.param(_LH_METHOD, "<H", zipfile.ZIP_STORED, id="method"),
+ pytest.param(_LH_FLAGS, "<H", 0x0800, id="flags"),
+ pytest.param(_LH_CRC, "<I", 0x12345678, id="crc"),
+ pytest.param(_LH_USIZE, "<I", 9_999_999, id="uncompressed"),
+ pytest.param(30, "<B", ord("X"), id="name"),
+ ],
+ )
+ def test_local_field_disagreeing_with_central_is_refused(
+ self, offset, fmt, value
+ ):
+ guard = _guard()
+ data = _single_entry("content.xml", b"<p>hello</p>")
+ struct.pack_into(fmt, data, offset, value)
+
+ with pytest.raises(guard.DecompressionBombError, match="disagrees"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+ def test_crc_mismatch_in_both_headers_is_refused(self):
+ guard = _guard()
+ data = _single_entry("content.xml", b"<p>hello</p>")
+ cd = _central_dir_offset(data)
+ struct.pack_into("<I", data, _LH_CRC, 1)
+ struct.pack_into("<I", data, cd + _CD_CRC, 1)
+
+ with pytest.raises(guard.DecompressionBombError, match="CRC"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+
+_MIB = 1024 * 1024
+
+
+class TestStreamEndAtOutputStepBoundary:
+ """Verification inflates in 1 MiB output steps. A step that hits
+ that cap can consume the last compressed byte while zlib still
+ holds output (and the end-of-stream marker), so the verifier must
+ drain it rather than call a complete stream truncated. Payloads are
+ zeros, so each archive stays a few KiB."""
+
+ @pytest.mark.parametrize("level", [1, 6, 9])
+ @pytest.mark.parametrize(
+ "size",
+ [
+ pytest.param(base * _MIB + delta, id=f"{base}MiB{delta:+d}")
+ for base in (1, 2, 3)
+ for delta in (-1, 0, 1, 50, 100, 200, 400)
+ ],
+ )
+ def test_complete_stream_near_an_output_step_is_accepted(self, size, level):
+ guard = _guard()
+ buf = io.BytesIO()
+ with zipfile.ZipFile(
+ buf, "w", zipfile.ZIP_DEFLATED, compresslevel=level
+ ) as zf:
+ entries = _ooxml_package(
+ {"word/media/image1.bmp": b"BM" + bytes(size - 2)}, ".docx"
+ )
+ for name, payload in entries.items():
+ zf.writestr(name, payload)
+
+ guard.validate_zip_container(buf.getvalue(), ".docx")
+
+
+def _streamed_zip(entries: dict[str, bytes], **open_kwargs) -> bytes:
+ """A zip written to a non-seekable stream: zipfile then sets flag
+ bit 3 and writes data descriptors (as LibreOffice and Java do)."""
+
+ class _Sink(io.RawIOBase):
+ def __init__(self):
+ self.data = bytearray()
+
+ def writable(self):
+ return True
+
+ def write(self, chunk):
+ self.data += chunk
+ return len(chunk)
+
+ sink = _Sink()
+ with zipfile.ZipFile(sink, "w", zipfile.ZIP_DEFLATED) as zf:
+ for name, payload in entries.items():
+ with zf.open(name, "w", **open_kwargs) as fh:
+ fh.write(payload)
+ return bytes(sink.data)
+
+
+class TestDataDescriptors:
+ def test_streamed_entries_with_descriptors_are_accepted(self):
+ data = _streamed_zip({"content.xml": b"<p>hello</p>", "empty": b""})
+ assert struct.unpack_from("<H", data, _LH_FLAGS)[0] & 0x8
+
+ _guard().validate_zip_container(data, ".odt")
+
+ def test_zip64_descriptors_are_accepted(self):
+ data = _streamed_zip({"content.xml": b"<p>hello</p>"}, force_zip64=True)
+
+ _guard().validate_zip_container(data, ".odt")
+
+ def test_descriptor_disagreeing_with_central_is_refused(self):
+ guard = _guard()
+ data = bytearray(_streamed_zip({"content.xml": b"<p>hello</p>"}))
+ descriptor = data.index(b"PK\x07\x08")
+ size = struct.unpack_from("<I", data, descriptor + 12)[0]
+ struct.pack_into("<I", data, descriptor + 12, size + 1_000_000)
+
+ with pytest.raises(guard.DecompressionBombError, match="descriptor"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+ def test_nonzero_local_size_under_bit_3_must_match(self):
+ guard = _guard()
+ data = bytearray(_streamed_zip({"content.xml": b"<p>hello</p>"}))
+ struct.pack_into("<I", data, _LH_USIZE, 9_999_999)
+
+ with pytest.raises(guard.DecompressionBombError, match="disagrees"):
+ guard.validate_zip_container(bytes(data), ".odt")
+
+
+# --- Reference fan-out in .pptx / .docx -----------------------------------
+
+
+def _rewrite_zip(data: bytes, changes=None, add=None) -> bytes:
+ changes, add = changes or {}, add or {}
+ out = io.BytesIO()
+ with (
+ zipfile.ZipFile(io.BytesIO(data)) as zin,
+ zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zout,
+ ):
+ for info in zin.infolist():
+ payload = zin.read(info)
+ if info.filename in changes:
+ payload = changes[info.filename](payload)
+ zout.writestr(info.filename, payload)
+ for name, payload in add.items():
+ zout.writestr(name, payload)
+ return out.getvalue()
+
+
+def _deck(slides: int = 1) -> bytes:
+ pptx = pytest.importorskip("pptx")
+ deck = pptx.Presentation()
+ for n in range(slides):
+ slide = deck.slides.add_slide(deck.slide_layouts[5])
+ slide.shapes.title.text = f"slide {n}"
+ buf = io.BytesIO()
+ deck.save(buf)
+ return buf.getvalue()
+
+
+_SLD_ID = re.compile(rb'<p:sldId id="(\d+)" r:id="([^"]+)"/>')
+_SLIDE_REL = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"
+)
+
+
+def _repeat_first_slide(data: bytes, copies: int, *, distinct_rels: bool):
+ """List the first slide part *copies* times in sldIdLst, through one
+ rId or through *copies* distinct relationships to the same part."""
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ presentation = zf.read("ppt/presentation.xml")
+ rel_id = _SLD_ID.search(presentation).group(2).decode()
+
+ def sld_ids(xml: bytes) -> bytes:
+ ids = b"".join(
+ b'<p:sldId id="%d" r:id="%s"/>'
+ % (300 + n, (f"rIdFan{n}" if distinct_rels else rel_id).encode())
+ for n in range(copies)
+ )
+ return _SLD_ID.sub(b"", xml).replace(
+ b"<p:sldIdLst>", b"<p:sldIdLst>" + ids, 1
+ )
+
+ def rels(xml: bytes) -> bytes:
+ if not distinct_rels:
+ return xml
+ extra = "".join(
+ f'<Relationship Id="rIdFan{n}" Type="{_SLIDE_REL}" '
+ 'Target="slides/slide1.xml"/>'
+ for n in range(copies)
+ )
+ return xml.replace(
+ b"</Relationships>", extra.encode() + b"</Relationships>"
+ )
+
+ return _rewrite_zip(
+ data,
+ {
+ "ppt/presentation.xml": sld_ids,
+ "ppt/_rels/presentation.xml.rels": rels,
+ },
+ )
+
+
+class TestPptxSlideFanOut:
+ def test_premise_python_pptx_yields_a_shared_slide_per_entry(self):
+ pptx = pytest.importorskip("pptx")
+ data = _repeat_first_slide(_deck(), 5, distinct_rels=False)
+
+ slides = list(pptx.Presentation(io.BytesIO(data)).slides)
+ assert len(slides) == 5
+ assert len({id(slide.part) for slide in slides}) == 1
+
+ @pytest.mark.parametrize("distinct_rels", [False, True])
+ def test_one_slide_listed_repeatedly_is_refused(self, distinct_rels):
+ guard = _guard()
+ data = _repeat_first_slide(_deck(), 5, distinct_rels=distinct_rels)
+
+ with pytest.raises(guard.DecompressionBombError, match="same slide"):
+ guard.validate_zip_container(data, ".pptx")
+
+ def test_rid_redefined_to_a_missing_part_is_resolved_like_pptx(self):
+ """python-pptx drops a relationship whose target is missing
+ before later duplicates win, so rIdA -> slide1 followed by
+ rIdA -> missing still resolves to slide1."""
+ pptx = pytest.importorskip("pptx")
+ guard = _guard()
+ data = _repeat_first_slide(_deck(), 3, distinct_rels=True)
+
+ def shadow(xml: bytes) -> bytes:
+ extra = "".join(
+ f'<Relationship Id="rIdFan{n}" Type="{_SLIDE_REL}" '
+ f'Target="slides/missing{n}.xml"/>'
+ for n in range(3)
+ )
+ return xml.replace(
+ b"</Relationships>", extra.encode() + b"</Relationships>"
+ )
+
+ data = _rewrite_zip(data, {"ppt/_rels/presentation.xml.rels": shadow})
+ # Premise: python-pptx still yields the shared slide three times.
+ assert len(list(pptx.Presentation(io.BytesIO(data)).slides)) == 3
+
+ with pytest.raises(guard.DecompressionBombError, match="same slide"):
+ guard.validate_zip_container(data, ".pptx")
+
+ def test_unresolvable_slide_entry_is_refused(self):
+ guard = _guard()
+
+ def dangling(xml: bytes) -> bytes:
+ return xml.replace(
+ b"</p:sldIdLst>",
+ b'<p:sldId id="999" r:id="rIdNowhere"/></p:sldIdLst>',
+ 1,
+ )
+
+ data = _rewrite_zip(_deck(), {"ppt/presentation.xml": dangling})
+ with pytest.raises(
+ guard.DecompressionBombError, match="cannot resolve"
+ ):
+ guard.validate_zip_container(data, ".pptx")
+
+ def test_distinct_slides_are_accepted(self):
+ _guard().validate_zip_container(_deck(slides=3), ".pptx")
+
+ def test_upload_path_refuses_the_fan_out(self):
+ from local_deep_research.document_loaders.bytes_loader import (
+ load_from_bytes,
+ )
+
+ guard = _guard()
+ data = _repeat_first_slide(_deck(), 5, distinct_rels=False)
+ with pytest.raises(guard.DecompressionBombError):
+ load_from_bytes(data, ".pptx", "fan.pptx")
+
+
+_W_MAIN = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+_HEADER_REL = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header"
+)
+_HEADER_CT = (
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"
+)
+
+
+def _docx_with_sections(
+ sections: int, *, header: bytes | None = b"HEADER", rel_id: str = "rIdHdr"
+) -> bytes:
+ """A python-docx document whose body holds *sections* one-paragraph
+ sections, each (with *header*) referencing one shared header part."""
+ docx = pytest.importorskip("docx")
+ buf = io.BytesIO()
+ docx.Document().save(buf)
+ ref = (
+ f'<w:headerReference w:type="default" r:id="{rel_id}"/>'.encode()
+ if header is not None
+ else b""
+ )
+ body = b"".join(
+ b"<w:p><w:pPr><w:sectPr>%s</w:sectPr></w:pPr>"
+ b"<w:r><w:t>p%d</w:t></w:r></w:p>" % (ref, n)
+ for n in range(sections)
+ )
+ changes = {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:body>", b"<w:body>" + body, 1
+ )
+ }
+ add = {}
+ if header is not None:
+ changes["word/_rels/document.xml.rels"] = lambda xml: xml.replace(
+ b"</Relationships>",
+ f'<Relationship Id="rIdHdr" Type="{_HEADER_REL}" '
+ 'Target="header1.xml"/></Relationships>'.encode(),
+ )
+ changes["[Content_Types].xml"] = lambda xml: xml.replace(
+ b"</Types>",
+ f'<Override PartName="/word/header1.xml" '
+ f'ContentType="{_HEADER_CT}"/></Types>'.encode(),
+ )
+ add["word/header1.xml"] = (
+ f'<w:hdr xmlns:w="{_W_MAIN}"><w:p><w:r><w:t>'.encode()
+ + header
+ + b"</w:t></w:r></w:p></w:hdr>"
+ )
+ return _rewrite_zip(buf.getvalue(), changes, add)
+
+
+class TestDocxSectionFanOut:
+ def test_premise_python_docx_repeats_a_shared_header_per_section(self):
+ docx = pytest.importorskip("docx")
+ data = _docx_with_sections(4)
+
+ sections = list(docx.Document(io.BytesIO(data)).sections)
+ assert len(sections) == 5 # four paragraph sections + the body's
+ headers = [
+ s.header for s in sections if not s.header.is_linked_to_previous
+ ]
+ assert len(headers) == 4
+ assert {h.part.partname for h in headers} == {"/word/header1.xml"}
+
+ def test_shared_header_references_over_the_budget_are_refused(self):
+ guard = _guard()
+ data = _docx_with_sections(20, header=b"H" * 1000)
+
+ with patch.object(guard, "MAX_DOCX_HEADER_FOOTER_BYTES", 10_000):
+ with pytest.raises(guard.DecompressionBombError, match="header"):
+ guard.validate_zip_container(data, ".docx")
+ with patch.object(guard, "MAX_DOCX_HEADER_FOOTER_BYTES", 100_000):
+ guard.validate_zip_container(data, ".docx") # control
+
+ def test_section_work_over_the_ceiling_is_refused(self):
+ guard = _guard()
+ data = _docx_with_sections(30, header=None)
+
+ with patch.object(guard, "MAX_DOCX_SECTION_WORK", 500):
+ with pytest.raises(guard.DecompressionBombError, match="sections"):
+ guard.validate_zip_container(data, ".docx")
+ with patch.object(guard, "MAX_DOCX_SECTION_WORK", 5_000):
+ guard.validate_zip_container(data, ".docx") # control
+
+ @pytest.mark.parametrize("node", [b"<w:r/>", b"<!---->", b"<?x?>"])
+ def test_section_xpath_nodes_count_toward_the_work(self, node):
+ # python-docx recomputes ``_sectPrs`` (an absolute XPath that
+ # visits every child of every body-level w:p) once per section,
+ # so a few sections over one paragraph of many runs is as costly
+ # as many body elements: the body-element product alone missed it.
+ guard = _guard()
+ sections = 10
+ data = _docx_with_sections(sections, header=None)
+ wide = _rewrite_zip(
+ data,
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:body>", b"<w:body><w:p>" + node * 5_000 + b"</w:p>", 1
+ )
+ },
+ )
+
+ with zipfile.ZipFile(io.BytesIO(wide)) as archive:
+ from docx.opc.packuri import PackURI
+
+ stats = guard._docx_section_stats(archive, PackURI)
+ counted = stats.sections
+ assert counted == sections + 1 # plus the body's own w:sectPr
+ assert stats.xpath_nodes >= 5_000
+ assert counted * stats.body_nodes < 500 # what the old metric saw
+ with patch.object(guard, "MAX_DOCX_SECTION_WORK", 500):
+ with pytest.raises(guard.DecompressionBombError, match="sections"):
+ guard.validate_zip_container(wide, ".docx")
+ guard.validate_zip_container(data, ".docx") # control
+
+ def test_ordinary_multi_section_document_stays_well_under_the_ceiling(
+ self,
+ ):
+ # Styled, multi-run paragraphs as python-docx writes them,
+ # measured small and extrapolated to 20 equal sections over
+ # 6,000 such paragraphs.
+ docx = pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ guard = _guard()
+ document = docx.Document()
+ paragraphs_per_section, sections = 20, 5
+ for n in range(sections):
+ for m in range(paragraphs_per_section):
+ paragraph = document.add_paragraph(style="List Bullet")
+ paragraph.add_run(f"section {n} ")
+ paragraph.add_run(f"paragraph {m}").bold = True
+ paragraph.add_run(" text")
+ document.add_section()
+ buf = io.BytesIO()
+ document.save(buf)
+ data = buf.getvalue()
+
+ guard.validate_zip_container(data, ".docx")
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ stats = guard._docx_section_stats(archive, PackURI)
+ assert stats.sections == sections + 1
+ assert stats.union_pairs == sections # N1 = sections, N2 = 1
+ nodes_per_paragraph = stats.xpath_nodes / (
+ paragraphs_per_section * sections
+ )
+ big_sections, big_paragraphs = 20, 6_000
+ # Section k ends after k/20 of the paragraphs.
+ big_block_work = (
+ sum(k * big_paragraphs // big_sections for k in range(1, 21))
+ * big_paragraphs
+ )
+ big_work = (
+ big_sections * big_paragraphs
+ + big_sections
+ * int(big_paragraphs * nodes_per_paragraph)
+ // guard.DOCX_SECTION_XPATH_NODES_PER_UNIT
+ + big_sections
+ * big_sections
+ // guard.DOCX_SECTION_UNION_PAIRS_PER_UNIT
+ )
+ assert big_block_work <= guard.MAX_DOCX_SECTION_BLOCK_WORK
+ assert big_work <= guard.MAX_DOCX_SECTION_WORK
+
+ def test_section_union_pairs_count_toward_the_work(self):
+ # The ``_sectPrs`` XPath is a union, and libxml2 drops duplicates
+ # by comparing every w:sectPr inside paragraph properties with
+ # every body-level w:sectPr, once per section: one w:pPr holding
+ # thousands of w:sectPr beside hundreds of body-level ones took
+ # minutes from a 36 KB file while the body-element and
+ # visited-node terms stayed under the ceiling.
+ pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ guard = _guard()
+ in_ppr, at_body = 600, 300 # under MAX_DOCX_SECTIONS together
+ data = _docx_with_sections(1, header=None)
+ packed = _rewrite_zip(
+ data,
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:body>",
+ b"<w:body><w:p><w:pPr>"
+ + b"<w:sectPr/>" * in_ppr
+ + b"</w:pPr></w:p>"
+ + b"<w:sectPr/>" * at_body,
+ 1,
+ )
+ },
+ )
+
+ with zipfile.ZipFile(io.BytesIO(packed)) as archive:
+ stats = guard._docx_section_stats(archive, PackURI)
+ counted = stats.sections
+ # plus the fixture's own paragraph and body-level w:sectPr
+ assert counted == (in_ppr + 1) + (at_body + 1)
+ assert stats.union_pairs == (in_ppr + 1) * (at_body + 1)
+ old_work = (
+ counted * stats.body_nodes
+ + counted
+ * stats.xpath_nodes
+ // guard.DOCX_SECTION_XPATH_NODES_PER_UNIT
+ )
+ # A ceiling the metric without the pair term just meets.
+ with patch.object(guard, "MAX_DOCX_SECTION_WORK", old_work):
+ with pytest.raises(guard.DecompressionBombError, match="pairs"):
+ guard.validate_zip_container(packed, ".docx")
+ guard.validate_zip_container(data, ".docx") # control
+
+ def test_many_ordinary_sections_add_few_union_pairs(self):
+ # Word-shaped: one body-level w:sectPr, one paragraph w:sectPr
+ # per section break, so the pair term grows only linearly.
+ pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ guard = _guard()
+ sections = 300
+ data = _docx_with_sections(sections, header=None)
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ stats = guard._docx_section_stats(archive, PackURI)
+ assert stats.sections == sections + 1
+ assert stats.union_pairs == sections
+ guard.validate_zip_container(data, ".docx")
+
+ def test_unresolvable_header_reference_is_refused(self):
+ guard = _guard()
+ data = _docx_with_sections(2, rel_id="rIdNowhere")
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="cannot resolve"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_real_multi_section_document_is_accepted(self):
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ for n in range(5):
+ document.add_paragraph(f"section {n}")
+ document.add_section()
+ document.sections[0].header.paragraphs[0].text = "running head"
+ buf = io.BytesIO()
+ document.save(buf)
+
+ _guard().validate_zip_container(buf.getvalue(), ".docx")
+
+ def test_defaults_accept_ordinary_documents_of_a_few_thousand_paragraphs(
+ self,
+ ):
+ # The ceilings refuse long documents, not only hostile ones (see
+ # "Known gaps" in the guard's docstring): measured on documents
+ # python-docx builds, a single section of more than about 11,300
+ # one-run paragraphs, or a Word-like document (300 styles, five
+ # sections, a table) of more than about 5,250-5,850 paragraphs
+ # of 5-10 formatted runs, is refused. One of 5,000 such
+ # paragraphs is accepted and one of 7,000 refused.
+ guard = _guard()
+ guard.validate_zip_container(_ordinary_document(5_000), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="budget"):
+ guard.validate_zip_container(_ordinary_document(7_000), ".docx")
+
+ def test_defaults_accept_many_sections_rels_settings_and_styles(self):
+ # A few hundred sections, thousands of images or hyperlinks, and
+ # settings and styles parts of a few hundred entries, each on
+ # its own, are far from their caps.
+ guard = _guard()
+ assert guard.MAX_DOCX_SECTIONS >= 1_000
+ assert guard.MAX_PART_RELATIONSHIPS >= 10_000
+ assert guard.MAX_DOCX_SETTINGS_CHILDREN >= 5_000
+ assert guard.MAX_DOCX_STYLES >= 5_000
+ assert guard.MAX_DOCX_HEADER_FOOTER_BYTES >= 8 * 1024 * 1024
+ data = _docx_with_sections(300, header=b"running head")
+ data = _pad_rels(data, "word/_rels/document.xml.rels", 2_000)
+ data = _pad_styles(data, 400)
+ guard.validate_zip_container(data, ".docx")
+
+
+def _ordinary_document(paragraphs: int) -> bytes:
+ """A Word-like document python-docx builds: 300 styles, five
+ sections, five formatted runs per paragraph, and a 10 x 4 table."""
+ docx = pytest.importorskip("docx")
+ from docx.enum.style import WD_STYLE_TYPE
+
+ document = docx.Document()
+ names = []
+ while len(document.styles.element) < 300:
+ style = document.styles.add_style(
+ f"Custom {len(names)}", WD_STYLE_TYPE.PARAGRAPH
+ )
+ style.base_style = document.styles["Normal"]
+ names.append(style.name)
+ sections = 5
+ for section in range(sections):
+ for n in range(paragraphs // sections):
+ paragraph = document.add_paragraph(style=names[n % len(names)])
+ for r in range(5):
+ run = paragraph.add_run(f"word{r} text ")
+ run.bold = r % 2 == 0
+ run.italic = r % 3 == 0
+ if section == 1:
+ table = document.add_table(rows=10, cols=4)
+ for row in table.rows:
+ for cell in row.cells:
+ cell.text = "cell"
+ if section < sections - 1:
+ document.add_section()
+ buf = io.BytesIO()
+ document.save(buf)
+ return buf.getvalue()
+
+
+_HYPERLINK_REL = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
+ "hyperlink"
+)
+_SETTINGS_REL = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"
+ "settings"
+)
+
+
+def _count_children(data: bytes, member: str) -> int:
+ from lxml import etree
+
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ return len(etree.fromstring(zf.read(member)))
+
+
+def _pad_rels(data: bytes, member: str, total: int) -> bytes:
+ """Add external hyperlink relationships to *member* until it has
+ *total* entries."""
+ extra = total - _count_children(data, member)
+ assert extra >= 0
+ rels = "".join(
+ f'<Relationship Id="rPad{n}" Type="{_HYPERLINK_REL}" '
+ f'Target="https://example.com/{n}" TargetMode="External"/>'
+ for n in range(extra)
+ ).encode()
+ return _rewrite_zip(
+ data,
+ {
+ member: lambda xml: xml.replace(
+ b"</Relationships>", rels + b"</Relationships>"
+ )
+ },
+ )
+
+
+def _pad_settings(data: bytes, total: int, member: str = "word/settings.xml"):
+ """Add empty children to the settings root until it has *total*."""
+ extra = total - _count_children(data, member)
+ assert extra >= 0
+ return _rewrite_zip(
+ data,
+ {
+ member: lambda xml: re.sub(
+ rb"(<w:settings\b[^>]*>)",
+ lambda m: m.group(1) + b"<w:pad/>" * extra,
+ xml,
+ count=1,
+ )
+ },
+ )
+
+
+def _with_body_prefix(data: bytes, prefix: bytes) -> bytes:
+ return _rewrite_zip(
+ data,
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:body>", b"<w:body>" + prefix, 1
+ )
+ },
+ )
+
+
+_DOCX_WORK_CEILINGS = (
+ "MAX_DOCX_SECTION_BLOCK_WORK",
+ "MAX_DOCX_SECTION_WORK",
+ "MAX_DOCX_HEADER_FOOTER_BYTES",
+ "MAX_DOCX_STYLE_WORK",
+ "MAX_DOCX_PAGE_BREAK_WORK",
+ "MAX_DOCX_RUN_WORK",
+ "MAX_DOCX_COPIED_BYTES",
+)
+
+
+@contextmanager
+def _isolated(guard, keep: str | None):
+ """Lift every .docx work ceiling but *keep* (all of them for None),
+ so that a document at *keep*'s ceiling is not refused for the small
+ shares of the others in the combined budget."""
+ with contextlib.ExitStack() as stack:
+ for name in _DOCX_WORK_CEILINGS:
+ if name != keep:
+ stack.enter_context(patch.object(guard, name, 10**30))
+ yield
+
+
+def _body_paragraphs(paragraphs: int) -> bytes:
+ """python-docx's blank document (one body-level w:sectPr) with
+ *paragraphs* empty body-level paragraphs."""
+ return _with_body_prefix(
+ _docx_with_sections(0, header=None), b"<w:p/>" * paragraphs
+ )
+
+
+class TestDocxPerSectionCaps:
+ # python-docx and unstructured repeat work once per section that
+ # the section-work count did not see (unstructured reads
+ # ``settings.odd_and_even_pages_header_footer`` twice per section: a
+ # Python scan of every document relationship, then a search of the
+ # settings root's children; each ``_sectPrs`` evaluation returns
+ # every w:sectPr). Rather than model each, the section count, the
+ # relationships per part and the settings root are capped.
+
+ def test_section_cap_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ limit = guard.MAX_DOCX_SECTIONS
+ # n paragraph sections plus the body's own w:sectPr
+ with _isolated(guard, None):
+ guard.validate_zip_container(
+ _docx_with_sections(limit - 1, header=None), ".docx"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="sections"):
+ guard.validate_zip_container(
+ _docx_with_sections(limit, header=None), ".docx"
+ )
+
+ def test_every_sectpr_counts_toward_the_section_cap(self):
+ # One nested in a table cell's paragraph: python-docx does not
+ # enumerate it as a section, but the cap counts it anyway.
+ guard = _guard()
+ limit = guard.MAX_DOCX_SECTIONS
+ nested = (
+ b"<w:tbl><w:tr><w:tc><w:p><w:pPr><w:sectPr/></w:pPr></w:p>"
+ b"</w:tc></w:tr></w:tbl>"
+ )
+ # body-level w:sectPr, so that no section has paragraphs
+ at_limit = _with_body_prefix(
+ _docx_with_sections(0, header=None),
+ b"<w:sectPr/>" * (limit - 2) + nested,
+ )
+ guard.validate_zip_container(at_limit, ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="sections"):
+ guard.validate_zip_container(
+ _with_body_prefix(at_limit, b"<w:sectPr/>"), ".docx"
+ )
+
+ @pytest.mark.parametrize(
+ "in_ppr, at_body", [(14_600, 421), (3_000, 150), (1_001, 0)]
+ )
+ def test_sectpr_packed_into_one_paragraph_is_refused(self, in_ppr, at_body):
+ # The reviewers' shapes: thousands of w:sectPr in one w:pPr,
+ # beside body-level ones (14,600 beside 421, a 36 KB file, took
+ # ~190 s in partition_docx).
+ guard = _guard()
+ data = _with_body_prefix(
+ _docx_with_sections(0, header=None),
+ b"<w:p><w:pPr>"
+ + b"<w:sectPr/>" * in_ppr
+ + b"</w:pPr></w:p>"
+ + b"<w:sectPr/>" * at_body,
+ )
+ with pytest.raises(guard.DecompressionBombError, match="sections"):
+ guard.validate_zip_container(data, ".docx")
+
+ @pytest.mark.parametrize(
+ "member", ["word/_rels/document.xml.rels", "_rels/.rels"]
+ )
+ def test_relationships_cap_accepts_the_limit_and_refuses_one_more(
+ self, member
+ ):
+ guard = _guard()
+ limit = guard.MAX_PART_RELATIONSHIPS
+ data = _docx_with_sections(3)
+
+ guard.validate_zip_container(_pad_rels(data, member, limit), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="relationships"):
+ guard.validate_zip_container(
+ _pad_rels(data, member, limit + 1), ".docx"
+ )
+
+ def test_presentation_relationships_are_capped_too(self):
+ guard = _guard()
+ member = "ppt/_rels/presentation.xml.rels"
+ guard.validate_zip_container(
+ _pad_rels(_deck(1), member, guard.MAX_PART_RELATIONSHIPS), ".pptx"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="relationships"):
+ guard.validate_zip_container(
+ _pad_rels(_deck(1), member, guard.MAX_PART_RELATIONSHIPS + 1),
+ ".pptx",
+ )
+
+ def test_settings_cap_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ limit = guard.MAX_DOCX_SETTINGS_CHILDREN
+ data = _docx_with_sections(3)
+
+ guard.validate_zip_container(_pad_settings(data, limit), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="settings"):
+ guard.validate_zip_container(
+ _pad_settings(data, limit + 1), ".docx"
+ )
+
+ def test_settings_part_is_found_through_its_relationship(self):
+ # python-docx resolves settings by relationship type, not by
+ # name: a padded settings part under another name is refused.
+ docx = pytest.importorskip("docx")
+ guard = _guard()
+ data = _rewrite_zip(
+ _docx_with_sections(3),
+ {
+ "word/_rels/document.xml.rels": lambda xml: xml.replace(
+ b'Target="settings.xml"', b'Target="custom/prefs.xml"'
+ ),
+ "[Content_Types].xml": lambda xml: xml.replace(
+ b'PartName="/word/settings.xml"',
+ b'PartName="/word/custom/prefs.xml"',
+ ),
+ },
+ )
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ moved = {
+ (
+ "word/custom/prefs.xml"
+ if i.filename == "word/settings.xml"
+ else i.filename
+ ): zf.read(i)
+ for i in zf.infolist()
+ }
+ data = _zip_bytes(moved)
+ document_part = docx.Document(io.BytesIO(data)).part
+ # premise: python-docx follows the relationship to the moved part
+ assert document_part._settings_part.partname == "/word/custom/prefs.xml"
+
+ guard.validate_zip_container(data, ".docx") # control
+ padded = _pad_settings(
+ data,
+ guard.MAX_DOCX_SETTINGS_CHILDREN + 1,
+ member="word/custom/prefs.xml",
+ )
+ with pytest.raises(guard.DecompressionBombError, match="settings"):
+ guard.validate_zip_container(padded, ".docx")
+
+ def test_settings_part_gets_the_skeleton_treatment(self):
+ guard = _guard()
+ data = _docx_with_sections(3)
+ size = len(zipfile.ZipFile(io.BytesIO(data)).read("word/settings.xml"))
+ with patch.object(guard, "MAX_OPC_SKELETON_PART_BYTES", size - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="larger than"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ with_dtd = _rewrite_zip(
+ data,
+ {
+ "word/settings.xml": _with_doctype(
+ b"<!DOCTYPE w:settings>", b"<w:settings"
+ )
+ },
+ )
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(with_dtd, ".docx")
+
+ def test_every_count_cap_at_its_limit_together_is_accepted(self):
+ # Sections at the limit as body-level w:sectPr (python-docx
+ # enumerates each as a section), since a thousand sections each
+ # holding a paragraph exceed MAX_DOCX_SECTION_BLOCK_WORK.
+ guard = _guard()
+ data = _with_body_prefix(
+ _docx_with_sections(0, header=None),
+ b"<w:p><w:r><w:t>text</w:t></w:r></w:p>"
+ + b"<w:sectPr/>" * (guard.MAX_DOCX_SECTIONS - 1),
+ )
+ data = _pad_rels(
+ data,
+ "word/_rels/document.xml.rels",
+ guard.MAX_PART_RELATIONSHIPS,
+ )
+ data = _pad_settings(data, guard.MAX_DOCX_SETTINGS_CHILDREN)
+ data = _pad_styles(data, guard.MAX_DOCX_STYLES)
+ stats = _docx_stats(data)
+ assert stats.sect_prs == stats.sections == guard.MAX_DOCX_SECTIONS
+ guard.validate_zip_container(data, ".docx")
+
+
+class TestDocxSectionBlockWork:
+ # python-docx finds each section's paragraphs and tables with
+ # ``preceding-sibling::*[self::w:p | self::w:tbl]``; libxml2 sorts
+ # that reverse-axis result with comparisons that walk sibling links
+ # to the end of the body, so one section costs about (blocks it
+ # returns) x (body nodes): a single-section body of 100,000 empty
+ # paragraphs took ~66 s, and 100 sections after 18,000 paragraphs
+ # ~86 s, while the body-element count saw 100 x 18,000 units.
+
+ def test_single_section_body_at_the_limit_is_accepted(self):
+ pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ guard = _guard()
+ limit = guard.MAX_DOCX_SECTION_BLOCK_WORK
+ # blocks = n, body nodes = n + 1 (the body's w:sectPr)
+ n = int((limit) ** 0.5)
+ while n * (n + 1) > limit:
+ n -= 1
+ while (n + 1) * (n + 2) <= limit:
+ n += 1
+ data = _body_paragraphs(n)
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ stats = guard._docx_section_stats(archive, PackURI)
+ assert stats.block_work == n * (n + 1) <= limit
+
+ with _isolated(guard, "MAX_DOCX_SECTION_BLOCK_WORK"):
+ guard.validate_zip_container(data, ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="block"):
+ guard.validate_zip_container(_body_paragraphs(n + 1), ".docx")
+
+ def test_sections_after_many_paragraphs_are_refused(self):
+ # 100 one-paragraph sections after 18,000 paragraphs: within the
+ # section cap and (at 100 x 18,101 units) the section-work
+ # ceiling, but ~86 s in partition_docx.
+ guard = _guard()
+ data = _with_body_prefix(
+ _docx_with_sections(100, header=None), b"<w:p/>" * 18_000
+ )
+ with pytest.raises(guard.DecompressionBombError, match="block"):
+ guard.validate_zip_container(data, ".docx")
+ guard.validate_zip_container( # control
+ _docx_with_sections(100, header=None), ".docx"
+ )
+
+ def test_body_nodes_after_the_sections_count(self):
+ # Each comparison walks to the end of the body, so nodes after
+ # a section's blocks cost as much as the blocks themselves: 100
+ # sections after 1,000 paragraphs, then 50,000 bookmarks before
+ # the body's w:sectPr: a 39 KB file that took ~62 s in
+ # partition_docx. The squared-blocks sum and the section-work
+ # ceiling both miss it.
+ pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ guard = _guard()
+ data = _with_body_prefix(
+ _docx_with_sections(100, header=None), b"<w:p/>" * 1_000
+ )
+
+ def pad_before_body_sectpr(xml: bytes) -> bytes:
+ at = xml.rindex(b"<w:sectPr") # the body-level one
+ return xml[:at] + b"<w:bookmarkStart/>" * 50_000 + xml[at:]
+
+ trailing = _rewrite_zip(
+ data, {"word/document.xml": pad_before_body_sectpr}
+ )
+ with zipfile.ZipFile(io.BytesIO(trailing)) as archive:
+ stats = guard._docx_section_stats(archive, PackURI)
+ assert stats.sections == 101
+ prefixes = [1_000 + k for k in range(1, 101)] + [1_100]
+ assert sum(p * p for p in prefixes) < guard.MAX_DOCX_SECTION_BLOCK_WORK
+ assert (
+ stats.sections * stats.body_nodes
+ + stats.sections
+ * stats.xpath_nodes
+ // guard.DOCX_SECTION_XPATH_NODES_PER_UNIT
+ < guard.MAX_DOCX_SECTION_WORK
+ )
+ assert stats.block_work == sum(prefixes) * stats.body_nodes
+ with pytest.raises(guard.DecompressionBombError, match="block"):
+ guard.validate_zip_container(trailing, ".docx")
+ guard.validate_zip_container(data, ".docx") # control
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ b"<w:p/>" * 5,
+ b"x<w:p/>" * 5 + b"y",
+ b"<!---->z" * 3 + b"<w:p/>",
+ b"<?pi?><w:p/>",
+ b"lead<w:tbl/>",
+ ],
+ )
+ def test_body_nodes_match_python_docx_tree(self, body):
+ # Non-whitespace text between body-level elements is a node
+ # python-docx keeps and the comparisons walk.
+ docx = pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ guard = _guard()
+ data = _with_body_prefix(_docx_with_sections(0, header=None), body)
+ tree = docx.Document(io.BytesIO(data)).element.body
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ stats = guard._docx_section_stats(archive, PackURI)
+ assert stats.body_nodes == len(tree.xpath("node()"))
+
+ def test_attribute_heavy_body_is_priced_at_its_worst_layout(self):
+ # The sibling walk costs more per step when the nodes walked
+ # carry attributes (about 16 ns for a bare element, ~48 ns with
+ # three attributes, ~100 ns with forty): 1,240 paragraphs before
+ # 2 million three-attribute bookmarks, a 234 KiB file at 0.993
+ # of the old 2.5 billion ceiling, took ~121 s in partition_docx.
+ # The ceiling now prices every step at the worst layout, so the
+ # same shape at a fifth of the size is refused.
+ pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ guard = _guard()
+ bookmark = b'<w:bookmarkEnd w:id="1" w:a="2" w:b="3"/>'
+ data = _with_body_prefix(
+ _docx_with_sections(0, header=None),
+ b"<w:p/>" * 1_240 + bookmark * 400_000,
+ )
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ stats = guard._docx_section_stats(archive, PackURI)
+ # the blank document's body ends in its own w:sectPr
+ assert stats.block_work == 1_240 * (1_240 + 400_000 + 1)
+ assert stats.block_work < 2_500_000_000 # the old ceiling
+ with pytest.raises(guard.DecompressionBombError, match="block"):
+ guard.validate_zip_container(data, ".docx")
+
+
+def _pad_styles(data: bytes, total: int, member: str = "word/styles.xml"):
+ """Add paragraph styles to the styles root until it has *total*
+ children."""
+ extra = total - _count_children(data, member)
+ assert extra >= 0
+ styles = b"".join(
+ b'<w:style w:type="paragraph" w:styleId="pad%d"/>' % n
+ for n in range(extra)
+ )
+ return _rewrite_zip(
+ data,
+ {
+ member: lambda xml: xml.replace(
+ b"</w:styles>", styles + b"</w:styles>"
+ )
+ },
+ )
+
+
+def _text_paragraphs(paragraphs: int, run: bytes = b"<w:t>text</w:t>"):
+ """python-docx's blank document with *paragraphs* body-level
+ paragraphs of one run each (holding *run*)."""
+ return _with_body_prefix(
+ _docx_with_sections(0, header=None),
+ (b"<w:p><w:r>" + run + b"</w:r></w:p>") * paragraphs,
+ )
+
+
+def _docx_stats(data: bytes):
+ pytest.importorskip("docx")
+ from docx.opc.packuri import PackURI
+
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ return _guard()._docx_section_stats(archive, PackURI)
+
+
+def _style_work(stats) -> int:
+ guard = _guard()
+ return stats.styled_paragraphs * (
+ stats.style_entries
+ + stats.style_attributes // guard.DOCX_STYLE_ATTRIBUTES_PER_ENTRY
+ + stats.relationships // guard.DOCX_RELATIONSHIPS_PER_STYLE_ENTRY
+ )
+
+
+class TestDocxStyleLookupWork:
+ # unstructured reads ``paragraph.style`` about four times per
+ # non-empty paragraph (and per fragment of one split at a rendered
+ # page break). Each read scans every relationship of the document
+ # part in Python (``part_related_by``) and, for a paragraph with no
+ # style of its own (or one that does not resolve), loops over every
+ # ``w:style`` in Python (``default_for``): 50 paragraphs beside
+ # 300,000 styles, an 805 KB file, took ~132 s in partition_docx.
+
+ def test_premise_unstructured_reads_the_style_per_paragraph(self):
+ docx = pytest.importorskip("docx")
+ udocx = pytest.importorskip("unstructured.partition.docx")
+ from docx.text.paragraph import Paragraph
+
+ reads = []
+ style = Paragraph.style
+
+ def counting(paragraph):
+ reads.append(paragraph)
+ return style.fget(paragraph)
+
+ data = _text_paragraphs(5)
+ assert len(docx.Document(io.BytesIO(data)).paragraphs) == 5
+ with patch.object(Paragraph, "style", property(counting)):
+ udocx.partition_docx(file=io.BytesIO(data))
+ assert len(reads) == 4 * 5
+ assert _docx_stats(data).styled_paragraphs == 5
+
+ def test_a_missing_styles_part_counts_python_docx_default(self):
+ # Without a styles relationship python-docx creates its default
+ # styles part, which the style lookup then scans.
+ docx = pytest.importorskip("docx")
+ guard = _guard()
+ data = _rewrite_zip(
+ _text_paragraphs(3),
+ {
+ "word/_rels/document.xml.rels": lambda xml: re.sub(
+ rb"<Relationship [^>]*relationships/styles\"[^>]*/>",
+ b"",
+ xml,
+ )
+ },
+ )
+ styles = docx.Document(io.BytesIO(data)).styles.element
+ assert len(styles) == guard.DOCX_DEFAULT_STYLES_ENTRIES
+ assert _docx_stats(data).style_entries == len(styles)
+
+ def test_styles_cap_accepts_the_limit_and_refuses_one_more(self):
+ # No text paragraphs, so the style work stays at zero.
+ guard = _guard()
+ limit = guard.MAX_DOCX_STYLES
+ blank = _docx_with_sections(0, header=None)
+
+ guard.validate_zip_container(_pad_styles(blank, limit), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="styles"):
+ guard.validate_zip_container(_pad_styles(blank, limit + 1), ".docx")
+
+ def test_styles_part_is_found_through_its_relationship(self):
+ docx = pytest.importorskip("docx")
+ guard = _guard()
+ data = _rewrite_zip(
+ _docx_with_sections(0, header=None),
+ {
+ "word/_rels/document.xml.rels": lambda xml: xml.replace(
+ b'Target="styles.xml"', b'Target="custom/look.xml"'
+ ),
+ "[Content_Types].xml": lambda xml: xml.replace(
+ b'PartName="/word/styles.xml"',
+ b'PartName="/word/custom/look.xml"',
+ ),
+ },
+ )
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ moved = {
+ (
+ "word/custom/look.xml"
+ if i.filename == "word/styles.xml"
+ else i.filename
+ ): zf.read(i)
+ for i in zf.infolist()
+ }
+ data = _zip_bytes(moved)
+ document_part = docx.Document(io.BytesIO(data)).part
+ # premise: python-docx follows the relationship to the moved part
+ assert document_part._styles_part.partname == "/word/custom/look.xml"
+
+ guard.validate_zip_container(data, ".docx") # control
+ padded = _pad_styles(
+ data, guard.MAX_DOCX_STYLES + 1, member="word/custom/look.xml"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="styles"):
+ guard.validate_zip_container(padded, ".docx")
+
+ def test_styles_part_gets_the_skeleton_treatment(self):
+ guard = _guard()
+ data = _docx_with_sections(0, header=None)
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ sizes = {i.filename: i.file_size for i in zf.infolist()}
+ # premise: the styles part is the largest skeleton part read
+ assert sizes["word/styles.xml"] > max(
+ size
+ for name, size in sizes.items()
+ if name.endswith(".rels") or name == "word/settings.xml"
+ )
+ with patch.object(
+ guard, "MAX_OPC_SKELETON_PART_BYTES", sizes["word/styles.xml"] - 1
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="larger than"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ with_dtd = _rewrite_zip(
+ data,
+ {
+ "word/styles.xml": _with_doctype(
+ b"<!DOCTYPE w:styles>", b"<w:styles"
+ )
+ },
+ )
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(with_dtd, ".docx")
+
+ def test_style_work_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ limit = guard.MAX_DOCX_STYLE_WORK
+ styled = _pad_styles(_text_paragraphs(1), guard.MAX_DOCX_STYLES)
+ per_paragraph = _style_work(_docx_stats(styled))
+ n = limit // per_paragraph
+
+ def document(paragraphs: int) -> bytes:
+ return _pad_styles(
+ _text_paragraphs(paragraphs), guard.MAX_DOCX_STYLES
+ )
+
+ at_limit = document(n)
+ assert _style_work(_docx_stats(at_limit)) == n * per_paragraph
+ with _isolated(guard, "MAX_DOCX_STYLE_WORK"):
+ guard.validate_zip_container(at_limit, ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="style"):
+ guard.validate_zip_container(document(n + 1), ".docx")
+
+ def test_relationships_count_toward_the_style_work(self):
+ # Each style read also scans every relationship: paragraphs
+ # times 10,000 relationships cost about as much as paragraphs
+ # times 312 styles part entries.
+ guard = _guard()
+ paragraphs = 8_000
+ data = _text_paragraphs(paragraphs)
+ stats = _docx_stats(data)
+ assert _style_work(stats) <= guard.MAX_DOCX_STYLE_WORK
+ guard.validate_zip_container(data, ".docx") # control
+
+ padded = _pad_rels(
+ data, "word/_rels/document.xml.rels", guard.MAX_PART_RELATIONSHIPS
+ )
+ assert _docx_stats(padded).relationships == (
+ guard.MAX_PART_RELATIONSHIPS
+ )
+ with pytest.raises(guard.DecompressionBombError, match="style"):
+ guard.validate_zip_container(padded, ".docx")
+
+ @pytest.mark.parametrize(
+ "paragraph, styled",
+ [
+ (b"<w:p/>", 0),
+ (b"<w:p><w:pPr/></w:p>", 0),
+ (b"<w:p><w:r/></w:p>", 1),
+ (b"<w:p><w:hyperlink/></w:p>", 1),
+ # each rendered page break can split off one more fragment
+ (
+ b"<w:p><w:r><w:t>a</w:t><w:lastRenderedPageBreak/>"
+ b"<w:t>b</w:t><w:lastRenderedPageBreak/><w:t>c</w:t>"
+ b"</w:r></w:p>",
+ 3,
+ ),
+ # paragraphs inside a table are not looked up
+ (b"<w:tbl><w:tr><w:tc><w:p><w:r/></w:p></w:tc></w:tr></w:tbl>", 0),
+ ],
+ )
+ def test_styled_paragraphs_counts_fragments_that_can_have_text(
+ self, paragraph, styled
+ ):
+ data = _with_body_prefix(_docx_with_sections(0, header=None), paragraph)
+ assert _docx_stats(data).styled_paragraphs == styled
+
+
+def _page_break_paragraph(breaks: int, gap: int = 1) -> bytes:
+ """One body-level paragraph of one run holding *breaks* rendered
+ page breaks, with *gap* text elements before, between and after
+ them."""
+ text = b"<w:t>a</w:t>" * gap
+ return (
+ b"<w:p><w:r>"
+ + text
+ + (b"<w:lastRenderedPageBreak/>" + text) * breaks
+ + b"</w:r></w:p>"
+ )
+
+
+def _blank_with(body: bytes) -> bytes:
+ return _with_body_prefix(_docx_with_sections(0, header=None), body)
+
+
+class TestDocxPageBreakWork:
+ # unstructured splits a paragraph at each ``w:lastRenderedPageBreak``
+ # (python-docx's ``preceding/following_paragraph_fragment``): every
+ # split deep-copies the paragraph and evaluates sibling-axis XPath
+ # (``precedes_all_content`` and the fragment builders) whose
+ # reverse-axis results libxml2 sorts with sibling walks, once per
+ # break, recursing into the rest. One paragraph of one run with 600
+ # breaks (a 37 KB file) ran for over 180 s; one break after 55,000
+ # elements of one run took ~34-61 s.
+
+ def test_premise_unstructured_splits_a_paragraph_per_page_break(self):
+ udocx = pytest.importorskip("unstructured.partition.docx")
+ data = _blank_with(_page_break_paragraph(3))
+ elements = udocx.partition_docx(file=io.BytesIO(data))
+ assert [type(e).__name__ for e in elements].count("PageBreak") == 3
+
+ @pytest.mark.parametrize(
+ "paragraph",
+ [
+ _page_break_paragraph(2),
+ _page_break_paragraph(3, gap=4),
+ b"<w:p><w:pPr><w:jc w:val='left'/></w:pPr>"
+ b"<w:hyperlink><w:r><w:t>a</w:t><w:lastRenderedPageBreak/>"
+ b"<w:t>b</w:t></w:r></w:hyperlink><!--c-->x<w:r/></w:p>",
+ ],
+ )
+ def test_work_matches_python_docx_tree(self, paragraph):
+ # S and N are counted from the stream as python-docx's tree has
+ # them (elements, comments, processing instructions and text).
+ docx = pytest.importorskip("docx")
+ guard = _guard()
+ data = _blank_with(paragraph)
+ p = docx.Document(io.BytesIO(data)).element.body[0]
+ breaks = len(p.xpath(".//w:lastRenderedPageBreak"))
+ nodes = len(p.xpath(".//node()"))
+ widest = max(len(e.xpath("node()")) for e in p.iter())
+ runs = p.xpath(".//w:r")
+ # The paragraph's w:r | w:hyperlink union, counted when both are
+ # present (the runs here hold one text-branch kind each, so their
+ # own unions count nothing).
+ branches = [p.xpath("w:r"), p.xpath("w:hyperlink")]
+ union = 0
+ if all(branches):
+ union = -(
+ -sum(map(len, branches))
+ * len(p.xpath("node()"))
+ * guard.DOCX_UNION_READS
+ // guard.DOCX_UNION_STEPS_PER_RUN_WORK_UNIT
+ )
+ stats = _docx_stats(data)
+ assert stats.page_break_work == breaks * (breaks + 3) * widest**2
+ assert (
+ stats.run_work
+ == (breaks + 1)
+ * (
+ guard.DOCX_RUN_WORK_ITEM_WEIGHT * len(runs)
+ + sum(len(r.xpath("node()")) for r in runs)
+ + union
+ )
+ + breaks * nodes // guard.DOCX_FRAGMENT_NODES_PER_RUN_WORK_UNIT
+ )
+
+ def test_page_break_work_accepts_the_limit_and_refuses_one_more(self):
+ # One break after n elements of one run: K = 1 and S = n + 1.
+ guard = _guard()
+
+ def document(n: int) -> bytes:
+ return _blank_with(
+ b"<w:p><w:r>"
+ + b"<w:t>a</w:t>" * n
+ + b"<w:lastRenderedPageBreak/></w:r></w:p>"
+ )
+
+ assert _docx_stats(document(10)).page_break_work == 4 * 11**2
+ n = math.isqrt(guard.MAX_DOCX_PAGE_BREAK_WORK // 4) - 1
+ with _isolated(guard, "MAX_DOCX_PAGE_BREAK_WORK"):
+ guard.validate_zip_container(document(n), ".docx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="page breaks"
+ ):
+ guard.validate_zip_container(document(n + 1), ".docx")
+
+ def test_paragraphs_without_page_breaks_cost_no_page_break_work(self):
+ data = _blank_with(_page_break_paragraph(0, 5_000))
+ assert _docx_stats(data).page_break_work == 0
+
+
+class TestDocxRunWork:
+ # unstructured reads each fragment's text several times (about five
+ # ``run.text`` evaluations per run, each an XPath plus a Python loop
+ # over the run's children) and walks table rows and cells: 120
+ # paragraphs of 2,479 one-character runs, a 76 KB file, took ~40 s,
+ # and the cost was bounded only by the 128 MiB part ceiling.
+
+ def test_run_work_accepts_the_limit_and_refuses_one_more(self):
+ # One paragraph of n one-child runs: (weight + 1) units a run.
+ guard = _guard()
+ per_run = guard.DOCX_RUN_WORK_ITEM_WEIGHT + 1
+
+ def document(runs: int) -> bytes:
+ return _blank_with(
+ b"<w:p>" + b"<w:r><w:t>a</w:t></w:r>" * runs + b"</w:p>"
+ )
+
+ assert _docx_stats(document(10)).run_work == 10 * per_run
+ n = guard.MAX_DOCX_RUN_WORK // per_run
+ with _isolated(guard, "MAX_DOCX_RUN_WORK"):
+ guard.validate_zip_container(document(n), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="runs"):
+ guard.validate_zip_container(document(n + 1), ".docx")
+
+ def test_table_rows_and_cells_count(self):
+ guard = _guard()
+ cell = b"<w:tc><w:p><w:r><w:t>a</w:t></w:r></w:p></w:tc>"
+ data = _blank_with(
+ b"<w:tbl>" + (b"<w:tr>" + cell * 3 + b"</w:tr>") * 2 + b"</w:tbl>"
+ )
+ # 2 rows, 6 cells and 6 runs, each run with one child, and the
+ # cells' 6 paragraphs
+ assert _docx_stats(data).run_work == (
+ guard.DOCX_RUN_WORK_ITEM_WEIGHT * (2 + 6 + 6)
+ + 6
+ + 6 * guard.DOCX_CELL_BLOCK_ITEM_WEIGHT
+ )
+
+ def test_page_breaks_multiply_the_run_work(self):
+ # Each fragment's text is read again, and each split copies the
+ # paragraph.
+ one = _docx_stats(_blank_with(_page_break_paragraph(0, 10))).run_work
+ three = _docx_stats(_blank_with(_page_break_paragraph(2, 10)))
+ assert three.run_work > 3 * one
+
+ def test_runs_outside_body_blocks_are_not_counted(self):
+ # python-docx reads only body-level paragraphs and tables.
+ data = _blank_with(
+ b"<w:sdt><w:sdtContent><w:p><w:r><w:t>a</w:t></w:r></w:p>"
+ b"</w:sdtContent></w:sdt>"
+ )
+ assert _docx_stats(data).run_work == 0
+
+
+class TestDocxWorkBudget:
+ def test_work_kinds_share_one_budget(self):
+ # Two kinds each at 60% of their ceilings: either alone is
+ # accepted, together they are refused.
+ guard = _guard()
+ styled = _text_paragraphs(100)
+ stats = _docx_stats(styled)
+ style_ceiling = _style_work(stats) * 10 // 6
+ run_ceiling = stats.run_work * 10 // 6
+ with patch.object(guard, "MAX_DOCX_STYLE_WORK", style_ceiling):
+ with pytest.raises(guard.DecompressionBombError, match="budget"):
+ with patch.object(guard, "MAX_DOCX_RUN_WORK", run_ceiling):
+ guard.validate_zip_container(styled, ".docx")
+ with patch.object(guard, "MAX_DOCX_RUN_WORK", 10**12):
+ guard.validate_zip_container(styled, ".docx")
+ with patch.object(guard, "MAX_DOCX_RUN_WORK", run_ceiling):
+ with patch.object(guard, "MAX_DOCX_STYLE_WORK", 10**12):
+ guard.validate_zip_container(styled, ".docx")
+
+ def test_header_references_are_priced_by_default(self):
+ # Header text is read once per reference, at up to ~3.5 us per
+ # byte (empty runs, paragraphs or cells): 20 references to a
+ # 1.2 MB header of empty runs took ~73 s, well under the old
+ # 128 MiB budget.
+ guard = _guard()
+ hostile = _docx_with_sections(20, header=b"a" * 1_200_000)
+ with pytest.raises(guard.DecompressionBombError, match="header"):
+ guard.validate_zip_container(hostile, ".docx")
+ guard.validate_zip_container( # control
+ _docx_with_sections(20, header=b"a" * 200_000), ".docx"
+ )
+
+
+def _spanned_table(span: int, text: bytes = b"x", rows: int = 1) -> bytes:
+ """A body-level table of *rows* rows, each one cell spanning *span*
+ grid columns and holding one run of *text*."""
+ cell = (
+ b"<w:tc><w:tcPr><w:gridSpan w:val='%d'/></w:tcPr>"
+ b"<w:p><w:r><w:t>%s</w:t></w:r></w:p></w:tc>" % (span, text)
+ )
+ return b"<w:tbl>" + (b"<w:tr>" + cell + b"</w:tr>") * rows + b"</w:tbl>"
+
+
+def _grid_value_table(tag: bytes, value: bytes) -> bytes:
+ """A one-cell table whose cell (gridSpan) or row (gridBefore,
+ gridAfter) carries *value*."""
+ if tag == b"gridSpan":
+ return (
+ b"<w:tbl><w:tr><w:tc><w:tcPr><w:gridSpan w:val='%s'/></w:tcPr>"
+ b"<w:p/></w:tc></w:tr></w:tbl>" % value
+ )
+ return (
+ b"<w:tbl><w:tr><w:trPr><w:%s w:val='%s'/></w:trPr>"
+ b"<w:tc><w:p/></w:tc></w:tr></w:tbl>" % (tag, value)
+ )
+
+
+class TestDocxGridSpans:
+ # python-docx's ``_Row.cells`` yields a cell once per grid column it
+ # spans and unstructured's ``_convert_table_to_html`` re-reads the
+ # cell's text for each yield (and pads a row with one empty string
+ # per gridBefore/gridAfter column), so the span multiplies the
+ # cell's work and the text it keeps: a 950-byte file with one cell
+ # spanning 400,000 columns took 53 s and was accepted, and at
+ # 2**31 - 1 python-docx would build a ~17 GB tuple.
+
+ def test_premise_python_docx_yields_a_cell_per_spanned_column(self):
+ docx = pytest.importorskip("docx")
+ data = _blank_with(_spanned_table(7))
+ table = docx.Document(io.BytesIO(data)).tables[0]
+ assert len(table.rows[0].cells) == 7
+
+ def test_premise_unstructured_rereads_the_cell_per_yield(self):
+ pytest.importorskip("docx")
+ udocx = pytest.importorskip("unstructured.partition.docx")
+ from docx.table import _Cell
+
+ reads = []
+ inner = _Cell.iter_inner_content
+
+ def counting(cell):
+ reads.append(cell)
+ return inner(cell)
+
+ data = _blank_with(_spanned_table(7))
+ with patch.object(_Cell, "iter_inner_content", counting):
+ udocx.partition_docx(file=io.BytesIO(data))
+ assert len(reads) >= 7
+
+ def test_hostile_span_is_refused_by_default(self):
+ guard = _guard()
+ with pytest.raises(guard.DecompressionBombError, match="grid"):
+ guard.validate_zip_container(
+ _blank_with(_spanned_table(400_000)), ".docx"
+ )
+
+ @pytest.mark.parametrize("tag", [b"gridSpan", b"gridBefore", b"gridAfter"])
+ def test_grid_values_at_the_cap_are_accepted_and_one_more_refused(
+ self, tag
+ ):
+ guard = _guard()
+ cap = guard.MAX_DOCX_GRID_SPAN
+ guard.validate_zip_container(
+ _blank_with(_grid_value_table(tag, b"%d" % cap)), ".docx"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="grid"):
+ guard.validate_zip_container(
+ _blank_with(_grid_value_table(tag, b"%d" % (cap + 1))),
+ ".docx",
+ )
+
+ def test_cap_is_well_above_real_table_widths(self):
+ # Word's tables are at most 63 columns wide.
+ assert _guard().MAX_DOCX_GRID_SPAN >= 15 * 63
+
+ @pytest.mark.parametrize(
+ "tag,value",
+ [
+ (tag, value)
+ for tag in (b"gridSpan", b"gridBefore", b"gridAfter")
+ for value in (b"x", b"", b"1.5", b"0x10", b"7 7")
+ ],
+ )
+ def test_values_python_docx_cannot_read_are_refused(self, tag, value):
+ guard = _guard()
+ with pytest.raises(guard.DecompressionBombError, match="cannot read"):
+ guard.validate_zip_container(
+ _blank_with(_grid_value_table(tag, value)), ".docx"
+ )
+
+ def test_premise_python_docx_cannot_read_those_values(self):
+ docx = pytest.importorskip("docx")
+ for value in (b"x", b"", b"1.5", b"0x10", b"7 7"):
+ data = _blank_with(_grid_value_table(b"gridSpan", value))
+ table = docx.Document(io.BytesIO(data)).tables[0]
+ with pytest.raises(ValueError):
+ table.rows[0].cells # noqa: B018
+
+ @pytest.mark.parametrize("value", [b"9" * 40, b"0" * 40 + b"5"])
+ def test_overlong_values_are_refused_unparsed(self, value):
+ # Word writes at most a few digits; int() of a long digit string
+ # is not linear, so the guard does not parse one.
+ guard = _guard()
+ with pytest.raises(guard.DecompressionBombError, match="characters"):
+ guard.validate_zip_container(
+ _blank_with(_grid_value_table(b"gridSpan", value)), ".docx"
+ )
+
+ def test_missing_value_is_refused(self):
+ guard = _guard()
+ data = _blank_with(
+ b"<w:tbl><w:tr><w:tc><w:tcPr><w:gridSpan/></w:tcPr>"
+ b"<w:p/></w:tc></w:tr></w:tbl>"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="cannot read"):
+ guard.validate_zip_container(data, ".docx")
+
+ @pytest.mark.parametrize(
+ "value",
+ [b" 7 ", b"+7", b"0_7", b"\xd9\xa7"], # Arabic-Indic 7
+ )
+ def test_values_are_read_as_python_docx_reads_them(self, value):
+ # python-docx converts the attribute with int(), which accepts
+ # surrounding whitespace, a sign, underscores and Unicode digits:
+ # a span the guard read differently would escape its weight.
+ docx = pytest.importorskip("docx")
+ data = _blank_with(_grid_value_table(b"gridSpan", value))
+ table = docx.Document(io.BytesIO(data)).tables[0]
+ assert len(table.rows[0].cells) == 7
+ plain = _blank_with(_grid_value_table(b"gridSpan", b"7"))
+ assert _docx_stats(data).run_work == _docx_stats(plain).run_work
+
+ def test_negative_values_span_and_pad_nothing(self):
+ guard = _guard()
+ for tag in (b"gridSpan", b"gridBefore", b"gridAfter"):
+ data = _blank_with(_grid_value_table(tag, b"-5"))
+ guard.validate_zip_container(data, ".docx")
+ assert (
+ _docx_stats(
+ _blank_with(_grid_value_table(b"gridSpan", b"-5"))
+ ).run_work
+ == _docx_stats(
+ _blank_with(_grid_value_table(b"gridSpan", b"1"))
+ ).run_work
+ )
+
+ @pytest.mark.parametrize("span", [1, 2, 40, 1_000])
+ def test_a_cell_counts_once_per_spanned_column(self, span):
+ # A row (one item), and per yield of the cell: the cell, its
+ # paragraph, its run and the run's one child.
+ weight = _guard().DOCX_RUN_WORK_ITEM_WEIGHT
+ item = _guard().DOCX_CELL_BLOCK_ITEM_WEIGHT
+ stats = _docx_stats(_blank_with(_spanned_table(span)))
+ assert stats.run_work == weight + span * (2 * weight + item + 1)
+
+ def test_nested_spans_multiply(self):
+ weight = _guard().DOCX_RUN_WORK_ITEM_WEIGHT
+ inner = _spanned_table(4)
+ data = _blank_with(
+ b"<w:tbl><w:tr><w:tc><w:tcPr><w:gridSpan w:val='3'/></w:tcPr>"
+ + inner
+ + b"<w:p/></w:tc></w:tr></w:tbl>"
+ )
+ guard = _guard()
+ item = guard.DOCX_CELL_BLOCK_ITEM_WEIGHT
+ inner_work = weight + 4 * (2 * weight + item + 1)
+ # The outer cell holds a table and a paragraph (two items) among
+ # three child nodes, so its union is counted: 2 x 3 steps.
+ union = -(
+ -2
+ * 3
+ * guard.DOCX_UNION_READS
+ // guard.DOCX_UNION_STEPS_PER_RUN_WORK_UNIT
+ )
+ assert _docx_stats(data).run_work == weight + 3 * (
+ weight + 2 * item + union + inner_work
+ )
+
+ def test_row_padding_counts(self):
+ guard = _guard()
+ weight = guard.DOCX_RUN_WORK_ITEM_WEIGHT
+ per_unit = guard.DOCX_GRID_PADDING_PER_RUN_WORK_UNIT
+ data = _blank_with(
+ b"<w:tbl><w:tr><w:trPr><w:gridBefore w:val='%d'/>"
+ b"<w:gridAfter w:val='%d'/></w:trPr><w:tc><w:p/></w:tc>"
+ b"</w:tr></w:tbl>" % (3 * per_unit, 2 * per_unit)
+ )
+ assert (
+ _docx_stats(data).run_work
+ == 2 * weight + 5 + guard.DOCX_CELL_BLOCK_ITEM_WEIGHT
+ )
+
+ def test_many_rows_of_capped_spans_are_refused(self):
+ # Each value under the cap, but the spans add up.
+ guard = _guard()
+ cap = guard.MAX_DOCX_GRID_SPAN
+ weight = guard.DOCX_RUN_WORK_ITEM_WEIGHT
+ rows = guard.MAX_DOCX_RUN_WORK // (cap * (2 * weight + 1)) + 1
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(
+ _blank_with(_spanned_table(cap, rows=rows)), ".docx"
+ )
+
+ def test_spanned_cell_text_counts_as_copies(self):
+ text = b"t" * 10_000
+ for span in (1, 50):
+ stats = _docx_stats(_blank_with(_spanned_table(span, text)))
+ assert stats.copied_bytes == (span - 1) * _cell_copy(text)
+
+ def test_ordinary_merged_cells_are_accepted(self):
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ table = document.add_table(rows=6, cols=5)
+ table.cell(0, 0).merge(table.cell(0, 4)) # a header across
+ table.cell(1, 0).merge(table.cell(5, 0)) # a column down
+ for row in table.rows[1:]:
+ for cell in row.cells[1:]:
+ cell.text = "value"
+ buf = io.BytesIO()
+ document.save(buf)
+ _guard().validate_zip_container(buf.getvalue(), ".docx")
+
+
+def _merged_column(root_text: bytes, continuing: int) -> bytes:
+ """A one-column table: a vertically merged cell holding
+ *root_text*, continued by *continuing* rows."""
+ return (
+ b"<w:tbl><w:tblGrid><w:gridCol/></w:tblGrid><w:tr><w:tc><w:tcPr>"
+ b"<w:vMerge w:val='restart'/></w:tcPr><w:p><w:r><w:t>"
+ + root_text
+ + b"</w:t></w:r></w:p></w:tc></w:tr>"
+ + b"<w:tr><w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p/></w:tc></w:tr>"
+ * continuing
+ + b"</w:tbl>"
+ )
+
+
+#: tcPr encodings of a cell, and what python-docx reads as its vMerge.
+_VMERGE_ENCODINGS = {
+ "none": None,
+ "val_x": "x",
+ "restart_then_bare": "restart",
+ "second_tcpr": "restart",
+ "first_tcpr_without_vmerge": None,
+ "bare": "continue",
+ "continue": "continue",
+ "continue_then_restart": "continue",
+}
+
+
+def _vmerge_table(
+ encoding: str,
+ span: int,
+ *,
+ text: bytes = b"x",
+ rows: int = 1,
+ restart_first: bool = False,
+) -> bytes:
+ """A one-column table of *rows* rows, each one cell spanning *span*
+ columns, holding *text* and carrying the vMerge *encoding* (but for
+ a first row that restarts a merge, with *restart_first*)."""
+ grid = b"<w:gridSpan w:val='%d'/>" % span
+ tc_pr = {
+ "none": b"<w:tcPr>" + grid + b"</w:tcPr>",
+ "val_x": b"<w:tcPr>" + grid + b"<w:vMerge w:val='x'/></w:tcPr>",
+ "restart_then_bare": b"<w:tcPr>"
+ + grid
+ + b"<w:vMerge w:val='restart'/><w:vMerge/></w:tcPr>",
+ "second_tcpr": b"<w:tcPr>"
+ + grid
+ + b"<w:vMerge w:val='restart'/></w:tcPr><w:tcPr><w:vMerge/></w:tcPr>",
+ "first_tcpr_without_vmerge": b"<w:tcPr>"
+ + grid
+ + b"</w:tcPr><w:tcPr><w:vMerge/></w:tcPr>",
+ "bare": b"<w:tcPr>" + grid + b"<w:vMerge/></w:tcPr>",
+ "continue": b"<w:tcPr>"
+ + grid
+ + b"<w:vMerge w:val='continue'/></w:tcPr>",
+ "continue_then_restart": b"<w:tcPr>"
+ + grid
+ + b"<w:vMerge w:val='continue'/><w:vMerge w:val='restart'/></w:tcPr>",
+ }[encoding]
+ content = b"<w:p><w:r><w:t>" + text + b"</w:t></w:r></w:p>"
+ restart = (
+ b"<w:tr><w:tc><w:tcPr>"
+ + grid
+ + b"<w:vMerge w:val='restart'/></w:tcPr>"
+ + content
+ + b"</w:tc></w:tr>"
+ )
+ row = b"<w:tr><w:tc>" + tc_pr + content + b"</w:tc></w:tr>"
+ rows_xml = restart + row * (rows - 1) if restart_first else row * rows
+ return (
+ b"<w:tbl><w:tblGrid><w:gridCol/></w:tblGrid>" + rows_xml + b"</w:tbl>"
+ )
+
+
+def _declaration_bytes(prefix: str, uri: str) -> int:
+ """What one copied namespace declaration counts."""
+ return _guard().DOCX_COPIED_BYTES_PER_NODE + len(prefix) + len(uri)
+
+
+def _cell_copy(text: bytes) -> int:
+ """What one extra copy of a table cell holding *text* counts."""
+ return _guard().DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE * len(text)
+
+
+class TestDocxCopiedBytes:
+ # Fan-outs that turn one bounded paragraph or cell into many copies
+ # of its bytes: unstructured keeps two deep copies of the rest of a
+ # paragraph per rendered page break, namespace declarations and the
+ # text after the paragraph included (80 breaks before 3 MB of text,
+ # a 40 KB file, kept ~230 MB more than without them), re-extracts a
+ # spanned cell's text per spanned column, and a continuing merged
+ # cell's merge-start text per row (300 rows under a 1 MB cell, a
+ # 38 KB file, kept ~930 MB).
+
+ def test_premise_each_page_break_deep_copies_the_paragraph(self):
+ pytest.importorskip("docx")
+ udocx = pytest.importorskip("unstructured.partition.docx")
+ from docx.oxml.ns import qn
+ from docx.oxml.text import pagebreak
+
+ copies = []
+ deepcopy = pagebreak.copy.deepcopy
+
+ def counting(element, *args):
+ if getattr(element, "tag", None) == qn("w:p"):
+ copies.append(element)
+ return deepcopy(element, *args)
+
+ data = _blank_with(_page_break_paragraph(5))
+ with patch.object(pagebreak.copy, "deepcopy", counting):
+ udocx.partition_docx(file=io.BytesIO(data))
+ assert len(copies) >= 5
+
+ def test_premise_a_continuing_merged_cell_yields_the_merge_start(self):
+ docx = pytest.importorskip("docx")
+ data = _blank_with(_merged_column(b"root", 3))
+ table = docx.Document(io.BytesIO(data)).tables[0]
+ assert [row.cells[0].text for row in table.rows] == ["root"] * 4
+
+ def test_page_breaks_count_two_copies_of_the_paragraph_per_break(self):
+ guard = _guard()
+ text = b"t" * 100_000
+ for breaks in (1, 7):
+ data = _blank_with(
+ b"<w:p><w:r>"
+ + b"<w:lastRenderedPageBreak/>" * breaks
+ + b"</w:r><w:r><w:t>"
+ + text
+ + b"</w:t></w:r></w:p>"
+ )
+ copied = _docx_stats(data).copied_bytes
+ # Per copy: the text, 4 + breaks nodes (w:p, two w:r, w:t,
+ # the breaks), and the w: declaration of w:document, which
+ # libxml2 re-declares on the copy.
+ nodes = 4 + breaks
+ assert copied == 2 * breaks * (
+ len(text)
+ + nodes * guard.DOCX_COPIED_BYTES_PER_NODE
+ + _declaration_bytes("w", _W_MAIN)
+ )
+
+ def test_attribute_values_and_nodes_count(self):
+ guard = _guard()
+ name = b"n" * 50_000
+ data = _blank_with(
+ b"<w:p><w:r><w:lastRenderedPageBreak/></w:r>"
+ b"<w:bookmarkStart w:id='1' w:name='"
+ + name
+ + b"'/>"
+ + b"<w:bookmarkEnd w:id='1'/>" * 1_000
+ + b"<w:r><w:t>x</w:t></w:r></w:p>"
+ )
+ copied = _docx_stats(data).copied_bytes
+ assert copied >= len(name) + 1_000 * guard.DOCX_COPIED_BYTES_PER_NODE
+
+ def test_paragraphs_and_tables_without_fan_out_copy_nothing(self):
+ data = _blank_with(
+ _text_paragraphs_body(50) + _spanned_table(1, b"cell", rows=5)
+ )
+ assert _docx_stats(data).copied_bytes == 0
+
+ def test_continuing_merged_cells_count_the_largest_earlier_cell(self):
+ text = b"r" * 10_000
+ stats = _docx_stats(_blank_with(_merged_column(text, 12)))
+ assert stats.copied_bytes == 12 * _cell_copy(text)
+
+ def test_hostile_page_break_paragraph_is_refused_by_default(self):
+ # 80 breaks before 3 MB of text: ~230 MB kept, from 40 KB.
+ guard = _guard()
+ data = _blank_with(
+ b"<w:p><w:r>"
+ + b"<w:lastRenderedPageBreak/>" * 80
+ + b"</w:r>"
+ + b"<w:r><w:t>"
+ + b"ab " * 1_000_000
+ + b"</w:t></w:r></w:p>"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="copy"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_hostile_merged_column_is_refused_by_default(self):
+ guard = _guard()
+ data = _blank_with(_merged_column(b"ab " * 350_000, 300))
+ with pytest.raises(guard.DecompressionBombError, match="copy"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_copied_bytes_accept_the_limit_and_refuse_one_more(self):
+ guard = _guard()
+ data = _blank_with(_page_break_paragraph(3, gap=50))
+ copied = _docx_stats(data).copied_bytes
+ assert copied > 0
+ with _isolated(guard, "MAX_DOCX_COPIED_BYTES"):
+ with patch.object(guard, "MAX_DOCX_COPIED_BYTES", copied):
+ guard.validate_zip_container(data, ".docx")
+ with patch.object(guard, "MAX_DOCX_COPIED_BYTES", copied - 1):
+ with pytest.raises(guard.DecompressionBombError, match="copy"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_copied_bytes_share_the_budget(self):
+ guard = _guard()
+ data = _blank_with(_page_break_paragraph(3, gap=50))
+ stats = _docx_stats(data)
+ copied_ceiling = stats.copied_bytes * 10 // 6
+ run_ceiling = stats.run_work * 10 // 6
+ with _isolated(guard, None):
+ with patch.object(guard, "MAX_DOCX_COPIED_BYTES", copied_ceiling):
+ guard.validate_zip_container(data, ".docx")
+ with patch.object(guard, "MAX_DOCX_RUN_WORK", run_ceiling):
+ with pytest.raises(
+ guard.DecompressionBombError, match="budget"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ # python-docx's and unstructured's ``tc.vMerge == "continue"`` reads
+ # the first w:vMerge of the cell's first w:tcPr, and a missing w:val
+ # means "continue"; any other cell is an ordinary one, yielded once
+ # per spanned column.
+
+ def test_premise_python_docx_reads_the_first_vmerge_of_the_first_tcpr(
+ self,
+ ):
+ docx = pytest.importorskip("docx")
+ for encoding, value in _VMERGE_ENCODINGS.items():
+ data = _blank_with(
+ _vmerge_table(encoding, 7, rows=2, restart_first=True)
+ )
+ table = docx.Document(io.BytesIO(data)).tables[0]
+ tc = table._tbl.tr_lst[1].tc_lst[0]
+ assert tc.vMerge == value, encoding
+ if value != "continue":
+ assert len(table.rows[1].cells) == 7, encoding
+
+ @pytest.mark.parametrize(
+ "encoding",
+ [e for e, value in _VMERGE_ENCODINGS.items() if value != "continue"],
+ )
+ def test_a_cell_python_docx_does_not_continue_counts_per_column(
+ self, encoding
+ ):
+ text = b"c" * 10_000
+ stats = _docx_stats(_blank_with(_vmerge_table(encoding, 7, text=text)))
+ plain = _docx_stats(_blank_with(_vmerge_table("none", 7, text=text)))
+ assert stats.copied_bytes == plain.copied_bytes == 6 * _cell_copy(text)
+ assert stats.run_work == plain.run_work
+
+ @pytest.mark.parametrize(
+ "encoding",
+ [e for e, value in _VMERGE_ENCODINGS.items() if value == "continue"],
+ )
+ def test_a_cell_python_docx_continues_counts_the_largest_earlier_cell(
+ self, encoding
+ ):
+ text = b"c" * 10_000
+ data = _blank_with(
+ _vmerge_table(encoding, 7, text=text, rows=2, restart_first=True)
+ )
+ # The restart row: 6 extra copies; the continuing row: the
+ # largest earlier cell (its text times its 7 columns).
+ assert _docx_stats(data).copied_bytes == (6 + 7) * _cell_copy(text)
+
+ @pytest.mark.parametrize(
+ "encoding",
+ [e for e, value in _VMERGE_ENCODINGS.items() if value != "continue"],
+ )
+ def test_hostile_spanned_cell_with_a_vmerge_python_docx_ignores(
+ self, encoding
+ ):
+ # Two rows of one 100 KB cell spanning 1,000 columns with a
+ # w:vMerge python-docx does not read as "continue": it yields
+ # each cell 1,000 times (~200 MB of text kept, ~13 GB at 1 MB
+ # cells), and the guard used to count no copies at all.
+ guard = _guard()
+ data = _blank_with(
+ _vmerge_table(encoding, 1_000, text=b"ab " * 33_000, rows=2)
+ )
+ with pytest.raises(guard.DecompressionBombError, match="copy"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_premise_a_deep_copy_carries_declarations_and_tail(self):
+ from lxml import etree
+
+ root = etree.fromstring(
+ b"<d xmlns:w='urn:w' xmlns:u='urn:used' xmlns:x='urn:unused'>"
+ b"<w:body><w:p xmlns:p='urn:own'><w:r u:a='1'/></w:p>TAIL"
+ b"</w:body></d>"
+ )
+ copied = copy.deepcopy(root[0][0])
+ assert copied.tail == "TAIL"
+ assert copied.nsmap == {"p": "urn:own", "w": "urn:w", "u": "urn:used"}
+
+ def test_namespace_declarations_in_a_paragraph_count(self):
+ uri = "urn:" + "u" * (_guard().MAX_DOCX_NAMESPACE_URI_CHARS - 4)
+ base = _docx_stats(_blank_with(_page_break_paragraph(3))).copied_bytes
+ for declared in (
+ _page_break_paragraph(3).replace(
+ b"<w:r>", b"<w:r xmlns:z='%s'>" % uri.encode(), 1
+ ),
+ _page_break_paragraph(3).replace(
+ b"<w:p>", b"<w:p xmlns:z='%s'>" % uri.encode(), 1
+ ),
+ ):
+ copied = _docx_stats(_blank_with(declared)).copied_bytes
+ assert copied - base == 2 * 3 * _declaration_bytes("z", uri)
+
+ def test_used_ancestor_namespace_declarations_count(self):
+ uri = "urn:" + "u" * (_guard().MAX_DOCX_NAMESPACE_URI_CHARS - 4)
+ root = b"<w:document xmlns:z='%s' " % uri.encode()
+
+ def stats(body: bytes):
+ data = _rewrite_zip(
+ _blank_with(body),
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:document ", root, 1
+ )
+ },
+ )
+ return _docx_stats(data).copied_bytes
+
+ unused = stats(_page_break_paragraph(3))
+ used = stats(
+ _page_break_paragraph(3).replace(b"<w:r>", b"<w:r z:a='1'>", 1)
+ )
+ # The attribute (its node and value) and the declaration, per
+ # copy.
+ assert used - unused == 2 * 3 * (
+ _guard().DOCX_COPIED_BYTES_PER_ATTRIBUTE
+ + 1
+ + _declaration_bytes("z", uri)
+ )
+ assert (
+ unused
+ == _docx_stats(_blank_with(_page_break_paragraph(3))).copied_bytes
+ )
+
+ def test_the_text_after_a_page_break_paragraph_counts(self):
+ tail = b"t" * 50_000
+ base = _docx_stats(_blank_with(_page_break_paragraph(3))).copied_bytes
+ for after in (b"", b"<!--c-->", b"<w:p/>"):
+ body = _page_break_paragraph(3) + tail + after
+ copied = _docx_stats(_blank_with(body)).copied_bytes
+ assert copied - base == 2 * 3 * len(tail)
+ # Not after a paragraph without breaks.
+ body = _text_paragraphs_body(1) + tail
+ assert _docx_stats(_blank_with(body)).copied_bytes == 0
+
+ @pytest.mark.parametrize("where", ["w:p", "w:r", "tail", "ancestor"])
+ def test_hostile_declaration_heavy_page_break_paragraph_is_refused(
+ self, where
+ ):
+ # 80 breaks before 1 MB in a namespace URI or after the
+ # paragraph (a ~37 KB file): every copy keeps it, ~150 MB in
+ # all (~1.5 GB at 9.5 MB), and the guard used to count none.
+ # The text is refused as copies; a URI that long is now refused
+ # outright (MAX_DOCX_NAMESPACE_URI_CHARS).
+ guard = _guard()
+ uri = b"urn:" + b"u" * 1_000_000
+ paragraph = _page_break_paragraph(80, gap=0)
+ data = None
+ if where == "w:p":
+ paragraph = paragraph.replace(b"<w:p>", b"<w:p xmlns:z='%s'>" % uri)
+ elif where == "w:r":
+ paragraph = paragraph.replace(b"<w:r>", b"<w:r xmlns:z='%s'>" % uri)
+ elif where == "tail":
+ paragraph += uri
+ else:
+ paragraph = paragraph.replace(b"<w:r>", b"<w:r z:a='1'>")
+ data = _rewrite_zip(
+ _blank_with(paragraph),
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:document ", b"<w:document xmlns:z='%s' " % uri, 1
+ )
+ },
+ )
+ if data is None:
+ data = _blank_with(paragraph)
+ match = "copy" if where == "tail" else "namespace URI"
+ with pytest.raises(guard.DecompressionBombError, match=match):
+ guard.validate_zip_container(data, ".docx")
+
+ # Each attribute is copied as two libxml2 nodes (~275 bytes per
+ # empty attribute per copy measured), which an empty value used to
+ # leave uncounted.
+
+ @pytest.mark.parametrize("attributes", [10, 100])
+ def test_each_attribute_counts_a_node_and_its_value(self, attributes):
+ # 10 are read with attrib.values(), 100 with the @* XPath.
+ guard = _guard()
+ base = _docx_stats(_blank_with(_page_break_paragraph(3))).copied_bytes
+ for value in (b"", b"vv"):
+ marker = (
+ b"<w:bookmarkStart "
+ + b" ".join(b"a%d='%s'" % (i, value) for i in range(attributes))
+ + b"/>"
+ )
+ paragraph = _page_break_paragraph(3).replace(
+ b"<w:p>", b"<w:p>" + marker, 1
+ )
+ copied = _docx_stats(_blank_with(paragraph)).copied_bytes
+ assert copied - base == 2 * 3 * (
+ guard.DOCX_COPIED_BYTES_PER_NODE
+ + attributes
+ * (guard.DOCX_COPIED_BYTES_PER_ATTRIBUTE + len(value))
+ )
+
+ def test_hostile_attribute_heavy_page_break_paragraph_is_refused(self):
+ # 20 rendered page breaks, then 200 elements of 256 empty
+ # attributes (a ~40 KB file): the fragments unstructured keeps
+ # held ~310 MB more (~14 MB of attribute nodes per copy), and
+ # the guard used to count ~1 MB.
+ guard = _guard()
+ element = (
+ b"<w:bookmarkEnd "
+ + b" ".join(b"a%d=''" % i for i in range(256))
+ + b"/>"
+ )
+ paragraph = (
+ b"<w:p>"
+ + b"<w:r><w:t>a</w:t><w:lastRenderedPageBreak/><w:t>a</w:t></w:r>"
+ * 20
+ + element * 200
+ + b"<w:r><w:t>z</w:t></w:r></w:p>"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="copy"):
+ guard.validate_zip_container(_blank_with(paragraph), ".docx")
+
+ # unstructured's HTML keeps every extra copy of a cell as a string,
+ # then HTML-escaped in its row's and in its table's string: a '"'
+ # becomes '&quot;', and one astral character makes a string four
+ # bytes per character.
+
+ def test_premise_table_html_escapes_every_copy_of_a_spanned_cell(self):
+ pytest.importorskip("docx")
+ udocx = pytest.importorskip("unstructured.partition.docx")
+ text = '"q"\U0001f600'
+ data = _blank_with(_spanned_table(5, text.encode()))
+ (table,) = [
+ e
+ for e in udocx.partition_docx(file=io.BytesIO(data))
+ if e.category == "Table"
+ ]
+ html = table.metadata.text_as_html
+ assert html.count("&quot;q&quot;\U0001f600") == 5
+
+ def test_spanned_cell_copies_count_each_text_byte_at_the_html_factor(
+ self,
+ ):
+ text = ('"' * 1_000 + "\U0001f600").encode()
+ stats = _docx_stats(_blank_with(_spanned_table(21, text)))
+ assert stats.copied_bytes == 20 * _cell_copy(text)
+ assert _cell_copy(text) == (
+ _guard().DOCX_TABLE_COPY_BYTES_PER_TEXT_BYTE * (1_000 + 4)
+ )
+
+ @pytest.mark.parametrize("shape", ["spanned", "merged"])
+ def test_hostile_quoted_astral_cell_copies_are_refused(self, shape):
+ # 20 extra copies of a 1 MB cell of '"' and one emoji (a ~38 KB
+ # file) kept ~1 GB in unstructured's table HTML (~49 bytes per
+ # byte per copy); the guard counted 20 MB and accepted it.
+ guard = _guard()
+ text = b'"' * 1_000_000 + "\U0001f600".encode()
+ if shape == "spanned":
+ body = _spanned_table(21, text)
+ else:
+ body = _merged_column(text, 20)
+ with pytest.raises(guard.DecompressionBombError, match="copy"):
+ guard.validate_zip_container(_blank_with(body), ".docx")
+
+ def test_ordinary_spanned_and_merged_text_is_accepted(self):
+ # A 2 KB header cell across 20 columns and a 2 KB cell merged
+ # down 100 rows: ~15 MB counted.
+ guard = _guard()
+ text = b"Quarterly results " * 110
+ body = _spanned_table(20, text) + _merged_column(text, 100)
+ guard.validate_zip_container(_blank_with(body), ".docx")
+
+
+_W_DECL = b"xmlns:w='%s'" % _W_MAIN.encode()
+_PLAIN_CELL = b"<w:tc><w:p/></w:tc>"
+_CONTINUING_CELL = b"<w:tc><w:tcPr><w:vMerge/></w:tcPr><w:p/></w:tc>"
+
+
+def _merged_rows(width: int, rows: int) -> bytes:
+ """A table of *rows* rows of *width* cells: a plain first row, and
+ every cell of the others continuing a vertical merge."""
+ return (
+ b"<w:tbl><w:tr>"
+ + _PLAIN_CELL * width
+ + b"</w:tr>"
+ + (b"<w:tr>" + _CONTINUING_CELL * width + b"</w:tr>") * (rows - 1)
+ + b"</w:tbl>"
+ )
+
+
+def _random_tc(rng: random.Random, span: int, row: int) -> bytes:
+ """A w:tc of *span* columns in table row *row* with a random vMerge,
+ in encodings python-docx reads one way and a careless reader
+ another (a second w:tcPr, a w:tcPr after the content, an omitted,
+ zero or negative gridSpan)."""
+ merge = rng.choices(
+ (
+ None,
+ b"<w:vMerge/>",
+ b"<w:vMerge w:val='continue'/>",
+ b"<w:vMerge w:val='restart'/>",
+ b"<w:vMerge w:val='x'/>",
+ ),
+ weights=(35, 25, 20, 15, 5) if row else (70, 2, 3, 20, 5),
+ )[0]
+ if rng.random() < 0.08:
+ span = rng.choice((0, -1))
+ parts = (
+ []
+ if span == 1 and rng.random() < 0.5
+ else [b"<w:gridSpan w:val='%d'/>" % span]
+ )
+ if merge is not None:
+ parts.insert(rng.randint(0, len(parts)), merge)
+ tc_pr = b"<w:tcPr>" + b"".join(parts) + b"</w:tcPr>"
+ pieces = [tc_pr, b"<w:p/>"] if rng.random() < 0.9 else [b"<w:p/>", tc_pr]
+ if rng.random() < 0.1:
+ pieces.append(
+ rng.choice(
+ (
+ b"<w:tcPr><w:gridSpan w:val='2'/></w:tcPr>",
+ b"<w:tcPr><w:vMerge/></w:tcPr>",
+ b"<w:tcPr><w:vMerge w:val='restart'/></w:tcPr>",
+ )
+ )
+ )
+ return b"<w:tc>" + b"".join(pieces) + b"</w:tc>"
+
+
+def _random_merged_table(rng: random.Random) -> bytes:
+ """A table of a few rows that mostly share one column layout, with
+ random merges, gridBefore values and other children between the
+ cells."""
+ layout = [rng.choice((1, 1, 1, 2, 3)) for _ in range(rng.randint(1, 5))]
+ rows = []
+ for index in range(rng.randint(2, 7)):
+ spans = (
+ layout
+ if rng.random() < 0.85
+ else [rng.choice((1, 2)) for _ in range(rng.randint(1, 5))]
+ )
+ parts = []
+ if rng.random() < 0.15:
+ parts.append(
+ b"<w:trPr><w:gridBefore w:val='%d'/></w:trPr>"
+ % rng.choice((0, 1, 2, -1))
+ )
+ if rng.random() < 0.3:
+ parts.append(b"<w:trPr><w:gridBefore w:val='1'/></w:trPr>")
+ for span in spans:
+ if rng.random() < 0.1:
+ parts.append(b"<w:bookmarkStart w:id='0' w:name='b'/>")
+ parts.append(_random_tc(rng, span, index))
+ rows.append(b"<w:tr>" + b"".join(parts) + b"</w:tr>")
+ return b"<w:tbl>" + b"".join(rows) + b"</w:tbl>"
+
+
+class TestDocxMergedRows:
+ # python-docx resolves a cell continuing a vertical merge
+ # (``row.cells``) by computing its grid offset, which reads the
+ # span of every earlier cell in its row, and finding the cell at
+ # that offset in the row above, recursively up the merge;
+ # unstructured reads ``row.cells`` twice per table. Each step costs
+ # time proportional to the rows' width, and a merge D rows deep
+ # takes D steps per cell: two rows of 1,000 cells, the second all
+ # continuing (a 37 KB file), took 6-7 s per read, and every column
+ # merged down 50 rows of 64 cells 42 s per read, while the guard
+ # counted 15,000 and 32,000 run-work units (of 1.5 million). Rows are now
+ # capped at 256 cells and 2,048 grid columns, and every step is
+ # priced in MAX_DOCX_RUN_WORK.
+
+ def test_premise_python_docx_steps_once_per_merged_row_above(self):
+ docx = pytest.importorskip("docx")
+ from docx.oxml.table import CT_Tc
+
+ steps = []
+ above = CT_Tc._tc_above
+
+ def counting(tc):
+ steps.append(tc)
+ return above.fget(tc)
+
+ table = docx.Document(
+ io.BytesIO(_blank_with(_merged_rows(3, 5)))
+ ).tables[0]
+ with patch.object(CT_Tc, "_tc_above", property(counting)):
+ for row in table.rows:
+ assert len(row.cells) == 3
+ # Row r's cells each step up r rows.
+ assert len(steps) == 3 * (1 + 2 + 3 + 4)
+
+ def test_wide_merged_row_is_refused(self):
+ # 37 KB; 6-7 s per read of its cells, ~15 run-work units a cell
+ # before.
+ guard = _guard()
+ with pytest.raises(guard.DecompressionBombError, match="cells"):
+ guard.validate_zip_container(
+ _blank_with(_merged_rows(1_000, 2)), ".docx"
+ )
+
+ def test_row_cell_cap_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ cap = guard.MAX_DOCX_ROW_CELLS
+ row = b"<w:tbl><w:tr>%s</w:tr></w:tbl>"
+ guard.validate_zip_container(
+ _blank_with(row % (_PLAIN_CELL * cap)), ".docx"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="cells"):
+ guard.validate_zip_container(
+ _blank_with(row % (_PLAIN_CELL * (cap + 1))), ".docx"
+ )
+
+ def test_cells_of_nested_rows_count_per_row(self):
+ # Only a row's own w:tc children count towards its cells.
+ guard = _guard()
+ half = guard.MAX_DOCX_ROW_CELLS // 2 + 1
+ inner = b"<w:tbl><w:tr>" + _PLAIN_CELL * half + b"</w:tr></w:tbl>"
+ outer = (
+ b"<w:tbl><w:tr>"
+ + _PLAIN_CELL * half
+ + b"<w:tc>"
+ + inner
+ + b"<w:p/></w:tc></w:tr></w:tbl>"
+ )
+ guard.validate_zip_container(_blank_with(outer), ".docx")
+
+ def test_row_grid_column_cap_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ cap = guard.MAX_DOCX_ROW_GRID_COLUMNS
+ span = guard.MAX_DOCX_GRID_SPAN
+
+ def row(columns: int) -> bytes:
+ # gridBefore, cells of at most the span cap, gridAfter.
+ cells = []
+ rest = columns - 2
+ while rest:
+ width = min(rest, span)
+ cells.append(
+ b"<w:tc><w:tcPr><w:gridSpan w:val='%d'/></w:tcPr>"
+ b"<w:p/></w:tc>" % width
+ )
+ rest -= width
+ return (
+ b"<w:tbl><w:tr><w:trPr><w:gridBefore w:val='1'/>"
+ b"<w:gridAfter w:val='1'/></w:trPr>"
+ + b"".join(cells)
+ + b"</w:tr></w:tbl>"
+ )
+
+ with _isolated(guard, None):
+ guard.validate_zip_container(_blank_with(row(cap)), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="columns"):
+ guard.validate_zip_container(_blank_with(row(cap + 1)), ".docx")
+
+ def test_cap_is_well_above_real_table_widths(self):
+ # Word's tables are at most 63 columns wide.
+ guard = _guard()
+ assert guard.MAX_DOCX_ROW_CELLS >= 4 * 63
+ assert guard.MAX_DOCX_ROW_GRID_COLUMNS >= 2 * guard.MAX_DOCX_GRID_SPAN
+
+ def test_merge_steps_grow_with_the_merge_depth(self):
+ # One column merged down R rows takes R * (R - 1) / 2 steps.
+ guard = _guard()
+ weight = guard.DOCX_MERGE_STEP_WEIGHT
+ for rows in (2, 10, 40):
+ work = _docx_stats(_blank_with(_merged_rows(1, rows))).run_work
+ assert work >= weight * rows * (rows - 1) // 2
+
+ def test_long_merged_column_is_refused(self):
+ # 600 rows of one merged column, a ~37 KB file: ~180,000 steps
+ # of ~0.1 ms per read (one 300-row column took 8 s to partition),
+ # counted ~9,000 units before.
+ guard = _guard()
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(
+ _blank_with(_merged_rows(1, 600)), ".docx"
+ )
+
+ def test_wide_deep_merge_is_refused(self):
+ # 64 columns merged down 30 rows: ~28,000 steps at ~0.5 ms per
+ # read each.
+ guard = _guard()
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(
+ _blank_with(_merged_rows(64, 30)), ".docx"
+ )
+
+ def test_steps_follow_python_docx_on_random_tables(self):
+ # The guard walks the merges as python-docx does (spans and
+ # gridBefore as python-docx reads them, tc_at_grid_offset's
+ # search): never fewer steps, and the same number whenever
+ # python-docx resolves every cell.
+ pytest.importorskip("docx")
+ from docx.oxml.table import CT_Tc
+
+ guard = _guard()
+ steps = []
+ above = CT_Tc._tc_above
+
+ def counting(tc):
+ steps.append(tc)
+ return above.fget(tc)
+
+ from docx.oxml import parse_xml
+ from docx.table import Table
+
+ rng = random.Random(6515)
+ exact = deep = 0
+ for _ in range(150):
+ xml = _random_merged_table(rng)
+ data = _blank_with(xml)
+ with (
+ patch.object(guard, "DOCX_MERGE_STEP_WEIGHT", 10**9),
+ patch.object(guard, "DOCX_MERGE_CELLS_PER_UNIT", 10**12),
+ patch.object(guard, "DOCX_MERGE_NODES_PER_UNIT", 10**12),
+ ):
+ counted = _docx_stats(data).run_work // 10**9
+ del steps[:]
+ failed = False
+ table = Table(
+ parse_xml(xml.replace(b"<w:tbl>", b"<w:tbl %s>" % _W_DECL, 1)),
+ None, # type: ignore[arg-type]
+ )
+ with patch.object(CT_Tc, "_tc_above", property(counting)):
+ for row in table.rows:
+ try:
+ row.cells # noqa: B018
+ except ValueError:
+ failed = True
+ assert counted >= len(steps)
+ if not failed:
+ assert counted == len(steps)
+ exact += 1
+ deep += len(steps) > 1
+ assert exact > 40 and deep > 25
+
+ def test_real_wide_merged_tables_are_accepted(self):
+ # A 63-column table (Word's widest) with a merged header and its
+ # first column merged down 30 rows, as python-docx writes it.
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ table = document.add_table(rows=31, cols=63)
+ table.cell(0, 0).merge(table.cell(0, 62))
+ table.cell(1, 0).merge(table.cell(30, 0))
+ for row in table.rows[1:]:
+ row.cells[1].text = "value"
+ buf = io.BytesIO()
+ document.save(buf)
+ guard = _guard()
+ guard.validate_zip_container(buf.getvalue(), ".docx")
+ stats = _docx_stats(buf.getvalue())
+ assert stats.run_work < guard.MAX_DOCX_RUN_WORK // 4
+
+
+_MARKER = b"<w:bookmarkEnd w:id='0'/>"
+
+
+def _table_with_siblings(
+ width: int, rows: int, between: bytes = b"", trailing: bytes = b""
+) -> bytes:
+ """_merged_rows(width, rows) with *between* before every row after
+ the first and *trailing* after the cells of every row."""
+ return (
+ b"<w:tbl><w:tr>"
+ + _PLAIN_CELL * width
+ + trailing
+ + b"</w:tr>"
+ + (
+ between
+ + b"<w:tr>"
+ + _CONTINUING_CELL * width
+ + trailing
+ + b"</w:tr>"
+ )
+ * (rows - 1)
+ + b"</w:tbl>"
+ )
+
+
+class TestDocxTableSiblings:
+ # Every step python-docx takes up a vertical merge reads the
+ # continuing cell's row's grid_before (an lxml find over all the
+ # row's children when it has no w:trPr) and evaluates _tr_above
+ # (ancestor::w:tr[1]/preceding-sibling::w:tr[1], which visits each
+ # sibling between that row and the one above). Neither was priced:
+ # a row padded with 200,000 empty elements after its cell (a 1.6 KB
+ # file, at 0.09 of the run-work ceiling) took 7.6 s per read of the
+ # cells, and 64 merged columns with 200,000 elements between each
+ # two of 26 rows (81 KB, at 0.90) 58 s per read. Such siblings are
+ # now capped and priced into every step.
+
+ def test_wrappers_do_not_add_direct_row_or_table_siblings(self):
+ """The guard prices direct siblings, not descendants of a wrapper.
+
+ This checks the shape python-docx actually parses. A wall-clock
+ ratio is too sensitive to CI contention to establish that premise.
+ """
+ docx = pytest.importorskip("docx")
+ loose = _MARKER * 100
+ wrapped = b"<w:sdt><w:sdtContent>" + loose + b"</w:sdtContent></w:sdt>"
+
+ def table(between: bytes, trailing: bytes):
+ return docx.Document(
+ io.BytesIO(
+ _blank_with(_table_with_siblings(1, 2, between, trailing))
+ )
+ ).tables[0]
+
+ loose_between = table(loose, b"")
+ wrapped_between = table(wrapped, b"")
+ loose_trailing = table(b"", loose)
+ wrapped_trailing = table(b"", wrapped)
+
+ assert len(loose_between._tbl) == len(wrapped_between._tbl) + 99
+ assert (
+ len(loose_trailing.rows[1]._tr)
+ == len(wrapped_trailing.rows[1]._tr) + 99
+ )
+ for parsed in (
+ loose_between,
+ wrapped_between,
+ loose_trailing,
+ wrapped_trailing,
+ ):
+ assert len(parsed.rows[1].cells) == 1
+
+ def test_caps_are_at_least_a_wrapped_word_row(self):
+ # Word's widest row (63 cells), each in a content control, with
+ # w:trPr, w:tblPrEx and range markers.
+ guard = _guard()
+ assert guard.MAX_DOCX_ROW_OTHER_CHILDREN >= 63 + 2 + 32
+ assert guard.MAX_DOCX_TABLE_ROW_GAP >= 2 + 32
+
+ @pytest.mark.parametrize("node", [_MARKER, b"<!--c-->", b"<?pi x?>"])
+ def test_row_children_cap_accepts_the_limit_and_refuses_one_more(
+ self, node
+ ):
+ guard = _guard()
+ cap = guard.MAX_DOCX_ROW_OTHER_CHILDREN
+ guard.validate_zip_container(
+ _blank_with(_table_with_siblings(2, 2, trailing=node * cap)),
+ ".docx",
+ )
+ with pytest.raises(guard.DecompressionBombError, match="not cells"):
+ guard.validate_zip_container(
+ _blank_with(
+ _table_with_siblings(2, 2, trailing=node * (cap + 1))
+ ),
+ ".docx",
+ )
+
+ def test_row_children_count_wherever_they_sit_in_the_row(self):
+ # grid_before's find walks all of them when there is no w:trPr.
+ guard = _guard()
+ cap = guard.MAX_DOCX_ROW_OTHER_CHILDREN
+ half = _MARKER * (cap // 2 + 1)
+ row = b"<w:tbl><w:tr>" + half + _PLAIN_CELL + half + b"</w:tr></w:tbl>"
+ with pytest.raises(guard.DecompressionBombError, match="not cells"):
+ guard.validate_zip_container(_blank_with(row), ".docx")
+
+ @pytest.mark.parametrize("node", [_MARKER, b"<!--c-->", b"<?pi x?>"])
+ def test_children_between_rows_cap_accepts_the_limit_and_refuses_one_more(
+ self, node
+ ):
+ guard = _guard()
+ cap = guard.MAX_DOCX_TABLE_ROW_GAP
+ guard.validate_zip_container(
+ _blank_with(_table_with_siblings(2, 3, between=node * cap)),
+ ".docx",
+ )
+ with pytest.raises(guard.DecompressionBombError, match="between"):
+ guard.validate_zip_container(
+ _blank_with(
+ _table_with_siblings(2, 3, between=node * (cap + 1))
+ ),
+ ".docx",
+ )
+
+ def test_children_before_the_first_row_count_with_tblpr_and_tblgrid(self):
+ # A continuing cell in the first row walks them all (and then
+ # python-docx raises).
+ guard = _guard()
+ cap = guard.MAX_DOCX_TABLE_ROW_GAP
+
+ def table(markers: int) -> bytes:
+ return (
+ b"<w:tbl><w:tblPr/><w:tblGrid/>"
+ + _MARKER * markers
+ + b"<w:tr>"
+ + _CONTINUING_CELL
+ + b"</w:tr></w:tbl>"
+ )
+
+ guard.validate_zip_container(_blank_with(table(cap - 2)), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="between"):
+ guard.validate_zip_container(_blank_with(table(cap - 1)), ".docx")
+
+ def test_wrapped_content_and_children_after_the_last_row_are_free(self):
+ # No step walks inside a w:sdt or past the last row: a row group
+ # or cell in a content control holds any number of elements, and
+ # a table may keep all its rows in w:sdt wrappers.
+ guard = _guard()
+ wrapped = (
+ b"<w:sdt><w:sdtContent>"
+ + _MARKER * 5_000
+ + (b"</w:sdtContent></w:sdt>")
+ )
+ sdt_rows = (
+ b"<w:sdt><w:sdtContent><w:tr>"
+ + _PLAIN_CELL
+ + b"</w:tr></w:sdtContent></w:sdt>"
+ )
+ for body in (
+ _table_with_siblings(4, 5, between=wrapped, trailing=wrapped),
+ b"<w:tbl><w:tblPr/><w:tblGrid/>" + sdt_rows * 1_000 + b"</w:tbl>",
+ _table_with_siblings(4, 5)[: -len(b"</w:tbl>")]
+ + _MARKER * 5_000
+ + b"</w:tbl>",
+ # Rows of a nested table inside a wrapper are not table rows
+ # python-docx reads.
+ b"<w:tbl><w:tr><w:tc><w:sdt><w:sdtContent><w:tr>"
+ + _MARKER * 1_000
+ + _PLAIN_CELL
+ + b"</w:tr></w:sdtContent></w:sdt><w:p/></w:tc></w:tr></w:tbl>",
+ ):
+ guard.validate_zip_container(_blank_with(body), ".docx")
+
+ def test_hostile_padded_rows_are_refused(self):
+ # The gate's shapes: 200,000 elements after one row's cell, and
+ # between the rows of 64 columns merged down 26 rows.
+ guard = _guard()
+ padding = b"<w:x/>" * 200_000
+ for body in (
+ _table_with_siblings(1, 2, trailing=padding),
+ _table_with_siblings(64, 26, between=padding),
+ ):
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(_blank_with(body), ".docx")
+
+ def test_every_step_is_priced_at_the_rows_it_walks_between(self):
+ # One column merged down 40 rows takes 780 steps; each walks the
+ # siblings before its row once more.
+ guard = _guard()
+ cap = guard.MAX_DOCX_TABLE_ROW_GAP
+ plain = _docx_stats(_blank_with(_table_with_siblings(1, 40))).run_work
+ padded = _docx_stats(
+ _blank_with(_table_with_siblings(1, 40, between=_MARKER * cap))
+ ).run_work
+ steps = 40 * 39 // 2
+ assert padded - plain >= steps * (
+ cap // guard.DOCX_MERGE_NODES_PER_UNIT
+ )
+
+ def test_every_step_is_priced_at_its_rows_other_children(self):
+ # 64 cells continuing a plain row: 64 steps, each reading the
+ # continuing row's grid_before over all its children (the
+ # siblings after the last cell were not counted).
+ guard = _guard()
+ cap = guard.MAX_DOCX_ROW_OTHER_CHILDREN
+
+ def table(markers: int) -> bytes:
+ return (
+ b"<w:tbl><w:tr>"
+ + _PLAIN_CELL * 64
+ + b"</w:tr><w:tr>"
+ + _CONTINUING_CELL * 64
+ + _MARKER * markers
+ + b"</w:tr></w:tbl>"
+ )
+
+ plain = _docx_stats(_blank_with(table(0))).run_work
+ padded = _docx_stats(_blank_with(table(cap))).run_work
+ assert padded - plain >= 64 * (cap // guard.DOCX_MERGE_NODES_PER_UNIT)
+
+ def test_every_step_is_priced_at_its_rows_first_trpr(self):
+ # grid_before looks in the row's first w:trPr wherever it sits:
+ # one after 256 continuing cells holding 100,000 children (a
+ # 38 KB file) added ~0.28 s per read at 0.04 of the ceiling.
+ guard = _guard()
+
+ def table(markers: int) -> bytes:
+ return (
+ b"<w:tbl><w:tr>"
+ + _PLAIN_CELL * 64
+ + b"</w:tr><w:tr>"
+ + _CONTINUING_CELL * 64
+ + b"<w:trPr>"
+ + _MARKER * markers
+ + b"</w:trPr></w:tr></w:tbl>"
+ )
+
+ plain = _docx_stats(_blank_with(table(0))).run_work
+ padded = _docx_stats(_blank_with(table(4_096))).run_work
+ assert padded - plain >= 64 * (4_096 // guard.DOCX_MERGE_NODES_PER_UNIT)
+
+ def test_real_tables_with_markers_and_wrappers_are_accepted(self):
+ # A Word-like table: w:tblPrEx and w:trPr on every row, bookmark,
+ # comment, permission and proofing markers between and inside
+ # rows, every cell of a 63-column row in a content control, a
+ # group of rows in one, and the first column merged down.
+ guard = _guard()
+ markers = (
+ b"<w:bookmarkStart w:id='1' w:name='r'/><w:bookmarkEnd w:id='1'/>"
+ b"<w:commentRangeStart w:id='2'/><w:commentRangeEnd w:id='2'/>"
+ b"<w:permStart w:id='3' w:edGrp='everyone'/><w:permEnd w:id='3'/>"
+ b"<w:proofErr w:type='spellStart'/><w:proofErr w:type='spellEnd'/>"
+ )
+ row_pr = (
+ b"<w:tblPrEx><w:tblBorders/></w:tblPrEx>"
+ b"<w:trPr><w:trHeight w:val='300'/></w:trPr>"
+ )
+ cell = b"<w:tc><w:p><w:r><w:t>value</w:t></w:r></w:p></w:tc>"
+ wrapped_cell = (
+ b"<w:sdt><w:sdtPr/><w:sdtContent>%s</w:sdtContent></w:sdt>"
+ )
+ rows = [
+ b"<w:tr>" + row_pr + markers + wrapped_cell % cell * 63 + b"</w:tr>"
+ ]
+ for _ in range(40):
+ rows.append(
+ b"<w:tr>"
+ + row_pr
+ + markers
+ + _CONTINUING_CELL
+ + cell * 62
+ + markers
+ + b"</w:tr>"
+ )
+ group = (
+ b"<w:sdt><w:sdtPr/><w:sdtContent>"
+ + (b"<w:tr>" + row_pr + cell * 63 + b"</w:tr>") * 3
+ + b"</w:sdtContent></w:sdt>"
+ )
+ body = (
+ b"<w:tbl><w:tblPr/><w:tblGrid/>"
+ + markers
+ + (markers + group).join(rows)
+ + markers
+ + b"</w:tbl>"
+ )
+ data = _blank_with(body)
+ guard.validate_zip_container(data, ".docx")
+ assert _docx_stats(data).run_work < guard.MAX_DOCX_RUN_WORK // 4
+
+ def test_python_docx_table_with_bookmarks_is_accepted(self):
+ # python-docx's own table (63 columns, a merged header and first
+ # column), with a bookmark around every row, as Word keeps one
+ # spanning rows.
+ docx = pytest.importorskip("docx")
+ from docx.oxml import parse_xml
+
+ document = docx.Document()
+ table = document.add_table(rows=31, cols=63)
+ table.cell(0, 0).merge(table.cell(0, 62))
+ table.cell(1, 0).merge(table.cell(30, 0))
+ for index, row in enumerate(table.rows):
+ tr = row._tr
+ for tag, position in (("bookmarkStart", 0), ("bookmarkEnd", 1)):
+ marker = parse_xml(
+ b"<w:%s %s w:id='%d' w:name='b%d'/>"
+ % (tag.encode(), _W_DECL, index, index)
+ )
+ if position:
+ tr.addnext(marker)
+ else:
+ tr.addprevious(marker)
+ buf = io.BytesIO()
+ document.save(buf)
+ guard = _guard()
+ guard.validate_zip_container(buf.getvalue(), ".docx")
+ stats = _docx_stats(buf.getvalue())
+ assert stats.run_work < guard.MAX_DOCX_RUN_WORK // 4
+
+
+class TestDocxCellContentPerYield:
+ # unstructured reads a cell's content once per grid column it is
+ # yielded for (iter_inner_content, paragraphs, Paragraph.text), so
+ # its nodes other than runs are walked span times too: a cell
+ # spanning 1,000 columns with 60,000 empty elements after its
+ # paragraph took ~1.7 s to partition and counted 5,005 units; 30
+ # such rows (a 54 KB file) were accepted at 0.10 of the ceiling.
+
+ def test_cell_nodes_count_once_per_spanned_column(self):
+ guard = _guard()
+ nodes = 4 * guard.DOCX_CELL_NODES_PER_UNIT
+
+ def table(markers: int) -> bytes:
+ return (
+ b"<w:tbl><w:tr><w:tc><w:tcPr><w:gridSpan w:val='100'/>"
+ b"</w:tcPr><w:p/>"
+ + _MARKER * markers
+ + b"</w:tc></w:tr></w:tbl>"
+ )
+
+ extra = (
+ _docx_stats(_blank_with(table(nodes))).run_work
+ - _docx_stats(_blank_with(table(0))).run_work
+ )
+ assert extra >= 100 * 4
+
+ def test_hostile_padded_spanned_cells_are_refused(self):
+ # Seven rows of one cell spanning 1,000 columns with 60,000
+ # elements after its paragraph (~12 s to partition): 35,035
+ # units counted before.
+ guard = _guard()
+ cell = (
+ b"<w:tc><w:tcPr><w:gridSpan w:val='1000'/></w:tcPr><w:p/>"
+ + _MARKER * 60_000
+ + b"</w:tc>"
+ )
+ body = b"<w:tbl>" + (b"<w:tr>" + cell + b"</w:tr>") * 7 + b"</w:tbl>"
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(_blank_with(body), ".docx")
+
+ def test_ordinary_cells_count_no_node_units(self):
+ # A cell of a few paragraphs and runs holds well under the unit.
+ guard = _guard()
+ cell = (
+ b"<w:tc><w:tcPr><w:tcW w:w='100' w:type='dxa'/></w:tcPr>"
+ + b"<w:p><w:pPr/><w:r><w:rPr><w:b/></w:rPr><w:t>v</w:t></w:r></w:p>"
+ * 8
+ + b"</w:tc>"
+ )
+ assert guard.DOCX_CELL_NODES_PER_UNIT >= 64
+ weight = guard.DOCX_RUN_WORK_ITEM_WEIGHT
+ stats = _docx_stats(
+ _blank_with(b"<w:tbl><w:tr>" + cell + b"</w:tr></w:tbl>")
+ )
+ assert stats.run_work == weight * 2 + 8 * (
+ weight + 2 + guard.DOCX_CELL_BLOCK_ITEM_WEIGHT
+ )
+
+
+#: Namespace declarations on the root of the documents _blank_with
+#: builds (python-docx's template).
+_TEMPLATE_ROOT_DECLARATIONS = 17
+
+
+def _with_attributes(count: int, tag: bytes = b"w:p") -> bytes:
+ return (
+ b"<%s " % tag + b" ".join(b"a%d=''" % i for i in range(count)) + b"/>"
+ )
+
+
+def _declarations(count: int, start: int = 0) -> bytes:
+ return b" ".join(
+ b"xmlns:n%d='urn:n%d'" % (i, i) for i in range(start, start + count)
+ )
+
+
+class TestDocxAbnormalMarkupIsRefused:
+ # No writer puts more than a few dozen attributes on an element or
+ # declares more than a few dozen namespaces in scope (python-docx's
+ # template: 17 on w:document; Word ~35), and both have costs that
+ # grow faster than their size: lxml reads each attribute value by
+ # rescanning the element's attribute list (one paragraph of 50,000
+ # empty attributes, a 145 KB file, kept the guard itself busy for
+ # 40 s), and libxml2 resolves each copied element's namespace by
+ # walking the declarations in scope. Both are refused outright.
+
+ def test_premise_template_root_declarations(self):
+ data = _blank_with(b"")
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ xml = archive.read("word/document.xml")
+ root = xml[: xml.index(b"<w:body>")]
+ assert root.count(b"xmlns:") == _TEMPLATE_ROOT_DECLARATIONS
+
+ @pytest.mark.parametrize("tag", [b"w:p", b"w:bookmarkStart"])
+ def test_attribute_cap_accepts_the_limit_and_refuses_one_more(self, tag):
+ guard = _guard()
+ cap = guard.MAX_DOCX_ELEMENT_ATTRIBUTES
+ body = _with_attributes(cap, tag)
+ if tag != b"w:p":
+ body = b"<w:p>" + body + b"</w:p>"
+ guard.validate_zip_container(_blank_with(body), ".docx")
+ body = body.replace(b"/>", b" extra=''/>", 1)
+ with pytest.raises(guard.DecompressionBombError, match="attributes"):
+ guard.validate_zip_container(_blank_with(body), ".docx")
+
+ def test_attribute_cap_applies_outside_paragraphs_and_tables(self):
+ # The w:body itself, which the guard prices nothing for.
+ guard = _guard()
+ cap = guard.MAX_DOCX_ELEMENT_ATTRIBUTES
+ attrs = b" ".join(b"a%d=''" % i for i in range(cap + 1))
+ data = _rewrite_zip(
+ _blank_with(b""),
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:body>", b"<w:body " + attrs + b">", 1
+ )
+ },
+ )
+ with pytest.raises(guard.DecompressionBombError, match="attributes"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_attribute_flood_is_refused_before_any_value_is_read(self):
+ # Before, 30,000 attributes took ~6 s to price (and were
+ # accepted); the count is checked before any value is read.
+ guard = _guard()
+ data = _blank_with(_with_attributes(30_000))
+ reads = []
+ text_bytes = guard._text_bytes
+
+ def counting(text):
+ reads.append(text)
+ return text_bytes(text)
+
+ started = time.perf_counter()
+ with patch.object(guard, "_text_bytes", counting):
+ with pytest.raises(
+ guard.DecompressionBombError, match="attributes"
+ ):
+ guard.validate_zip_container(data, ".docx")
+ assert len(reads) < 100
+ # Generous: ~0.03 s measured.
+ assert time.perf_counter() - started < 3
+
+ def test_namespace_cap_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ room = guard.MAX_DOCX_NAMESPACES_IN_SCOPE - _TEMPLATE_ROOT_DECLARATIONS
+ for declared, refused in ((room, False), (room + 1, True)):
+ data = _blank_with(b"<w:p " + _declarations(declared) + b"/>")
+ if refused:
+ with pytest.raises(
+ guard.DecompressionBombError, match="namespace"
+ ):
+ guard.validate_zip_container(data, ".docx")
+ else:
+ guard.validate_zip_container(data, ".docx")
+
+ def test_namespace_cap_counts_declarations_in_scope(self):
+ guard = _guard()
+ half = (
+ guard.MAX_DOCX_NAMESPACES_IN_SCOPE - _TEMPLATE_ROOT_DECLARATIONS
+ ) // 2 + 1
+ # Siblings: never in scope together.
+ siblings = (
+ (b"<w:p " + _declarations(half) + b"/>")
+ + b"<w:p "
+ + _declarations(half, half)
+ + b"/>"
+ )
+ guard.validate_zip_container(_blank_with(siblings), ".docx")
+ # Nested: the run sees its own and the paragraph's.
+ nested = (
+ b"<w:p "
+ + _declarations(half)
+ + b"><w:r "
+ + _declarations(half, half)
+ + b"/></w:p>"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="namespace"):
+ guard.validate_zip_container(_blank_with(nested), ".docx")
+
+ # lxml hands back every element and attribute name as
+ # "{URI}local", building the string again on each read, so one long
+ # URI declared once and used through a short prefix multiplies
+ # through every name read under it: an 8 MB URI used by 3,000
+ # elements, a 44 KB file, exhausted 3 GB in the guard, and a 1 MB
+ # URI on 1,024 attribute names grew it by ~0.5 GB. URIs (and
+ # prefixes) are capped where they are declared, before any name is
+ # read.
+
+ @pytest.mark.parametrize("where", ["w:p", "w:r", "default", "root"])
+ def test_namespace_uri_cap_accepts_the_limit_and_refuses_one_more(
+ self, where
+ ):
+ guard = _guard()
+ cap = guard.MAX_DOCX_NAMESPACE_URI_CHARS
+
+ def document(length: int) -> bytes:
+ uri = b"urn:" + b"u" * (length - 4)
+ if where == "root":
+ return _rewrite_zip(
+ _blank_with(b"<w:p/>"),
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:document ",
+ b"<w:document xmlns:z='%s' " % uri,
+ 1,
+ )
+ },
+ )
+ declaration = (
+ b"xmlns='%s'" % uri
+ if where == "default"
+ else b"xmlns:z='%s'" % uri
+ )
+ if where == "w:r":
+ return _blank_with(
+ b"<w:p><w:r %s><w:t>a</w:t></w:r></w:p>" % declaration
+ )
+ return _blank_with(b"<w:p %s><x/></w:p>" % declaration)
+
+ guard.validate_zip_container(document(cap), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="namespace URI"):
+ guard.validate_zip_container(document(cap + 1), ".docx")
+
+ def test_namespace_prefix_cap_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ cap = guard.MAX_DOCX_NAMESPACE_PREFIX_CHARS
+ for length, refused in ((cap, False), (cap + 1, True)):
+ prefix = b"p" * length
+ data = _blank_with(
+ b"<w:p xmlns:%s='urn:x'><%s:x/></w:p>" % (prefix, prefix)
+ )
+ if refused:
+ with pytest.raises(
+ guard.DecompressionBombError, match="prefix"
+ ):
+ guard.validate_zip_container(data, ".docx")
+ else:
+ guard.validate_zip_container(data, ".docx")
+
+ def test_long_uri_is_refused_before_any_name_is_read(self):
+ # A 2 MB URI used by 3,000 elements: refused when declared, so
+ # the guard reads no element under it (counted through the
+ # attribute values and texts it sizes).
+ guard = _guard()
+ uri = b"urn:" + b"u" * 2_000_000
+ data = _blank_with(
+ b"<w:p xmlns:u='%s'>" % uri + b"<u:x a='1'/>" * 3_000 + b"</w:p>"
+ )
+ reads = []
+ text_bytes = guard._text_bytes
+
+ def counting(text):
+ reads.append(text)
+ return text_bytes(text)
+
+ started = time.perf_counter()
+ with patch.object(guard, "_text_bytes", counting):
+ with pytest.raises(
+ guard.DecompressionBombError, match="namespace URI"
+ ):
+ guard.validate_zip_container(data, ".docx")
+ assert len(reads) < 100
+ # Generous: ~0.05 s measured (~11 s, and accepted, before).
+ assert time.perf_counter() - started < 3
+
+ def test_guard_memory_stays_small_under_many_names_at_the_uri_cap(self):
+ # 20,480 distinct attribute names under a URI at the cap,
+ # declared on w:document: the guard used to keep every name
+ # (~24 MB of Python objects measured); it keeps the URIs.
+ import tracemalloc
+
+ guard = _guard()
+ uri = b"urn:" + b"u" * (guard.MAX_DOCX_NAMESPACE_URI_CHARS - 4)
+ elements = b"".join(
+ b"<w:bookmarkStart "
+ + b" ".join(b"z:a%d_%d=''" % (e, i) for i in range(256))
+ + b"/>"
+ for e in range(80)
+ )
+ data = _rewrite_zip(
+ _blank_with(b"<w:p>" + elements + b"</w:p>"),
+ {
+ "word/document.xml": lambda xml: xml.replace(
+ b"<w:document ", b"<w:document xmlns:z='%s' " % uri, 1
+ )
+ },
+ )
+ tracemalloc.start()
+ try:
+ _docx_stats(data)
+ _current, peak = tracemalloc.get_traced_memory()
+ finally:
+ tracemalloc.stop()
+ # ~0.8 MB measured.
+ assert peak < 6 * 1024 * 1024
+
+ def test_guard_time_at_the_uri_cap_stays_linear(self):
+ # 100,000 short elements named through a URI at the cap cost
+ # the guard about a third more than through Word's own (~0.5 s
+ # against ~0.4 s measured): each name is read a bounded number
+ # of times.
+ guard = _guard()
+
+ def elapsed(length: int) -> float:
+ uri = b"urn:" + b"u" * (length - 4)
+ data = _blank_with(
+ b"<w:p xmlns:u='%s'>" % uri + b"<u:x/>" * 100_000 + b"</w:p>"
+ )
+ started = time.perf_counter()
+ guard.validate_zip_container(data, ".docx")
+ return time.perf_counter() - started
+
+ word = elapsed(71)
+ assert elapsed(guard.MAX_DOCX_NAMESPACE_URI_CHARS) < 3 * word + 1
+
+ # libxml2 re-homes a removed subtree's namespace declarations through
+ # a cache it searches linearly, so lxml's remove(), which
+ # python-docx calls on a paragraph copy per rendered page break,
+ # costs the square of the declarations under the removed node
+ # (40,000 one-declaration elements: 0.4-0.8 s per removal; six page
+ # breaks before them, a 142 KB file, took 5 s to partition and were
+ # accepted). A body-level paragraph may hold at most
+ # MAX_DOCX_PARAGRAPH_NAMESPACES declarations.
+
+ def test_paragraph_namespace_cap_accepts_the_limit_and_refuses_one_more(
+ self,
+ ):
+ guard = _guard()
+ cap = guard.MAX_DOCX_PARAGRAPH_NAMESPACES
+ # 128 per run (in scope with the template's 17), one on the w:p.
+ per_run = 128
+
+ def paragraph(declared: int) -> bytes:
+ runs = []
+ rest = declared - 1
+ start = 1
+ while rest:
+ count = min(rest, per_run)
+ runs.append(b"<w:r %s/>" % _declarations(count, start))
+ start += count
+ rest -= count
+ return b"<w:p %s>" % _declarations(1) + b"".join(runs) + b"</w:p>"
+
+ guard.validate_zip_container(_blank_with(paragraph(cap)), ".docx")
+ with pytest.raises(guard.DecompressionBombError, match="namespace"):
+ guard.validate_zip_container(
+ _blank_with(paragraph(cap + 1)), ".docx"
+ )
+ # The cap is per paragraph.
+ guard.validate_zip_container(
+ _blank_with(paragraph(cap) + paragraph(cap)), ".docx"
+ )
+
+ def test_hostile_declaration_flood_with_page_breaks_is_refused(self):
+ # 200 groups of 200 one-declaration elements in one run, after
+ # six page breaks: 5 s to partition, accepted before.
+ guard = _guard()
+ groups = b"".join(
+ b"<w:x>"
+ + b"".join(
+ b"<w:y xmlns:n='urn:%d'/>" % (g * 200 + i) for i in range(200)
+ )
+ + b"</w:x>"
+ for g in range(200)
+ )
+ body = (
+ b"<w:p><w:r><w:t>a</w:t>"
+ + b"<w:lastRenderedPageBreak/><w:t>a</w:t>" * 6
+ + b"</w:r><w:r>"
+ + groups
+ + b"</w:r></w:p>"
+ )
+ with pytest.raises(guard.DecompressionBombError, match="namespace"):
+ guard.validate_zip_container(_blank_with(body), ".docx")
+
+ def test_paragraphs_of_many_pictures_are_accepted(self):
+ # Pictures declare namespaces inside the paragraph: python-docx
+ # two per inline picture (on wp:inline), Word up to five
+ # (a:graphicFrameLocks, a:graphic, pic:pic, a14:useLocalDpi and
+ # a16:creationId each declare their own).
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ run = document.add_paragraph().add_run()
+ image = _small_png()
+ for _ in range(100):
+ run.add_picture(io.BytesIO(image))
+ buf = io.BytesIO()
+ document.save(buf)
+ data = buf.getvalue()
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ xml = archive.read("word/document.xml")
+ body = xml[xml.index(b"<w:body>") :]
+ assert body.count(b"xmlns:") == 200
+ guard = _guard()
+ guard.validate_zip_container(data, ".docx")
+ # 200 Word-style pictures in one paragraph.
+ word_picture = (
+ b"<w:r><w:drawing><w:x>"
+ b"<a:graphicFrameLocks xmlns:a='%(a)s'/>"
+ b"<a:graphic xmlns:a='%(a)s'><pic:pic xmlns:pic='%(pic)s'>"
+ b"<a14:useLocalDpi xmlns:a14='%(a14)s'/>"
+ b"<a16:creationId xmlns:a16='%(a16)s'/>"
+ b"</pic:pic></a:graphic></w:x></w:drawing></w:r>"
+ % {
+ b"a": b"http://schemas.openxmlformats.org/drawingml/2006/main",
+ b"pic": b"http://schemas.openxmlformats.org/drawingml/2006/"
+ b"picture",
+ b"a14": b"http://schemas.microsoft.com/office/drawing/2010/"
+ b"main",
+ b"a16": b"http://schemas.microsoft.com/office/drawing/2014/"
+ b"main",
+ }
+ )
+ guard.validate_zip_container(
+ _blank_with(b"<w:p>" + word_picture * 200 + b"</w:p>"), ".docx"
+ )
+
+ def test_documents_python_docx_writes_stay_far_under_both_caps(self):
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ document.add_heading("Title", 0)
+ paragraph = document.add_paragraph("Some ")
+ paragraph.add_run("bold").bold = True
+ table = document.add_table(rows=3, cols=3)
+ table.cell(0, 0).merge(table.cell(0, 2))
+ document.add_page_break()
+ buf = io.BytesIO()
+ document.save(buf)
+ data = buf.getvalue()
+ guard = _guard()
+ guard.validate_zip_container(data, ".docx")
+ from lxml import etree
+
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ root = etree.fromstring(archive.read("word/document.xml"))
+ assert max(len(e.attrib) for e in root.iter()) * 8 < (
+ guard.MAX_DOCX_ELEMENT_ATTRIBUTES
+ )
+ assert max(len(e.nsmap) for e in root.iter()) * 8 < (
+ guard.MAX_DOCX_NAMESPACES_IN_SCOPE
+ )
+ uris = set().union(*(e.nsmap.values() for e in root.iter()))
+ assert max(len(uri) for uri in uris) * 8 < (
+ guard.MAX_DOCX_NAMESPACE_URI_CHARS
+ )
+ prefixes = set().union(*(e.nsmap.keys() for e in root.iter()))
+ assert max(len(p or "") for p in prefixes) * 6 < (
+ guard.MAX_DOCX_NAMESPACE_PREFIX_CHARS
+ )
+
+
+def _text_paragraphs_body(paragraphs: int) -> bytes:
+ return b"<w:p><w:r><w:t>text</w:t></w:r></w:p>" * paragraphs
+
+
+def _with_doctype(doctype: bytes, root_tag: bytes):
+ """A rewrite that inserts *doctype* before the part's root element."""
+
+ def rewrite(xml: bytes) -> bytes:
+ assert root_tag in xml
+ return xml.replace(root_tag, doctype + root_tag, 1)
+
+ return rewrite
+
+
+_INTERNAL_DTD = b'<!DOCTYPE w:document [<!ENTITY e "">]>'
+_EXTERNAL_DTD = b'<!DOCTYPE w:document SYSTEM "x.dtd">'
+
+
+class TestPackagePartsWithADtdAreRefused:
+ # python-docx parses with resolve_entities=False, which keeps each
+ # entity reference as an _Entity node that its per-section XPath
+ # walks, while iterparse emits no event for it: the section-work
+ # count missed them. Package parts never carry a DTD (OPC forbids
+ # it), and a DTD is the only way to declare an entity.
+
+ def _docx_with_entity_refs(self, doctype: bytes, refs: int = 50):
+ data = _docx_with_sections(3, header=None)
+ return _rewrite_zip(
+ data,
+ {
+ "word/document.xml": lambda xml: _with_doctype(
+ doctype, b"<w:document"
+ )(
+ # standalone="yes" would make an undeclared
+ # entity (the external-subset case) a parse error.
+ re.sub(
+ rb" standalone=['\"]yes['\"]", b"", xml, count=1
+ ).replace(
+ b"<w:body>",
+ b"<w:body><w:p>" + b"&e;" * refs + b"</w:p>",
+ 1,
+ )
+ )
+ },
+ )
+
+ @pytest.mark.parametrize(
+ "doctype", [_INTERNAL_DTD, _EXTERNAL_DTD], ids=["internal", "system"]
+ )
+ def test_premise_entity_references_are_nodes_the_count_misses(
+ self, doctype
+ ):
+ docx = pytest.importorskip("docx")
+ from lxml import etree
+
+ data = self._docx_with_entity_refs(doctype)
+ body = docx.Document(io.BytesIO(data)).element.body
+ assert sum(isinstance(n, etree._Entity) for n in body[0]) == 50
+
+ @pytest.mark.parametrize(
+ "doctype", [_INTERNAL_DTD, _EXTERNAL_DTD], ids=["internal", "system"]
+ )
+ def test_document_xml_with_a_dtd_is_refused(self, doctype):
+ pytest.importorskip("docx")
+ guard = _guard()
+ data = self._docx_with_entity_refs(doctype)
+
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".docx")
+ guard.validate_zip_container( # control: same document, no DTD
+ _docx_with_sections(3, header=None), ".docx"
+ )
+
+ def test_relationships_part_with_a_dtd_is_refused(self):
+ pytest.importorskip("docx")
+ guard = _guard()
+ data = _rewrite_zip(
+ _docx_with_sections(1),
+ {
+ "word/_rels/document.xml.rels": _with_doctype(
+ b"<!DOCTYPE Relationships>", b"<Relationships"
+ )
+ },
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_presentation_part_with_a_dtd_is_refused(self):
+ guard = _guard()
+ data = _rewrite_zip(
+ _deck(1),
+ {
+ "ppt/presentation.xml": _with_doctype(
+ b"<!DOCTYPE p:presentation>", b"<p:presentation"
+ )
+ },
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".pptx")
+ guard.validate_zip_container(_deck(1), ".pptx") # control
+
+ def test_workbook_part_with_a_dtd_is_refused(self):
+ openpyxl = pytest.importorskip("openpyxl")
+ guard = _guard()
+ buf = io.BytesIO()
+ openpyxl.Workbook().save(buf)
+ data = _rewrite_zip(
+ buf.getvalue(),
+ {
+ "xl/workbook.xml": _with_doctype(
+ b"<!DOCTYPE workbook>", b"<workbook"
+ )
+ },
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".xlsx")
+ guard.validate_zip_container(buf.getvalue(), ".xlsx") # control
+
+ def test_header_part_with_a_dtd_is_refused(self):
+ # Header/footer parts are streamed for their unions now, so a
+ # DTD there is refused as in document.xml.
+ guard = _guard()
+ data = _rewrite_zip(
+ _docx_with_sections(1),
+ {"word/header1.xml": _with_doctype(b"<!DOCTYPE w:hdr>", b"<w:hdr")},
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".docx")
+ guard.validate_zip_container(_docx_with_sections(1), ".docx")
+
+
+def _real_package(ext: str) -> bytes:
+ """A package the format's own library writes."""
+ buf = io.BytesIO()
+ if ext == ".docx":
+ pytest.importorskip("docx").Document().save(buf)
+ elif ext == ".pptx":
+ return _deck(1)
+ else:
+ pytest.importorskip("openpyxl").Workbook().save(buf)
+ return buf.getvalue()
+
+
+def _detected_type(tmp_path, data: bytes, ext: str) -> str:
+ """What unstructured's ``detect_filetype`` calls *data* saved as
+ *ext* (the call langchain's Word and PowerPoint loaders make)."""
+ filetype = pytest.importorskip("unstructured.file_utils.filetype")
+ path = tmp_path / f"probe{ext}"
+ path.write_bytes(data)
+ return filetype.detect_filetype(str(path)).name
+
+
+def _renamed_members(data: bytes, renames: dict[str, str]) -> bytes:
+ out = io.BytesIO()
+ with (
+ zipfile.ZipFile(io.BytesIO(data)) as zin,
+ zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zout,
+ ):
+ for info in zin.infolist():
+ payload = zin.read(info)
+ for old, new in renames.items():
+ payload = payload.replace(old.encode(), new.encode())
+ zout.writestr(renames.get(info.filename, info.filename), payload)
+ return out.getvalue()
+
+
+class TestPackageTypeMatchesTheExtension:
+ # langchain's Word and PowerPoint loaders ask unstructured's
+ # detect_filetype (whenever python-magic imports) and send what it
+ # calls DOC or PPT to partition_doc/partition_ppt: soffice with no
+ # timeout, then partition_docx on its output without this guard. A
+ # zip whose member names match none of its OOXML patterns is typed
+ # from a root ``mimetype`` member, which the guard accepted before.
+
+ @pytest.mark.parametrize(
+ ("ext", "mimetype", "detected"),
+ [
+ (".docx", "application/msword", "DOC"),
+ (".pptx", "application/vnd.ms-powerpoint", "PPT"),
+ ],
+ )
+ def test_mimetype_naming_a_legacy_format_is_refused(
+ self, tmp_path, ext, mimetype, detected
+ ):
+ guard = _guard()
+ data = _zip_bytes({"mimetype": mimetype.encode()})
+ assert len(data) < 200
+ assert _detected_type(tmp_path, data, ext) == detected
+
+ with pytest.raises(guard.DecompressionBombError, match="mimetype"):
+ guard.validate_zip_container(data, ext)
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx", ".xlsx"])
+ def test_any_mimetype_member_of_an_office_package_is_refused(self, ext):
+ # Even beside the main part, which makes the sniffer type the
+ # package correctly: OPC packages have no such member.
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(ext), add={"mimetype": b"application/msword"}
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="mimetype"):
+ guard.validate_zip_container(data, ext)
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx", ".xlsx"])
+ def test_real_office_packages_are_accepted(self, tmp_path, ext):
+ data = _real_package(ext)
+ assert _detected_type(tmp_path, data, ext) == ext[1:].upper()
+
+ _guard().validate_zip_container(data, ext)
+
+ def test_docx_without_its_main_part_is_refused(self):
+ # word/document.xml is there (the sniffer says DOCX), but no
+ # package relationship names it: python-docx cannot open this.
+ guard = _guard()
+ data = _zip_bytes(
+ {
+ "word/document.xml": (
+ f"<w:document xmlns:w='{_W_MAIN}'><w:body/></w:document>"
+ ).encode()
+ }
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="main document"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_pptx_without_its_main_part_is_refused(self):
+ guard = _guard()
+ data = _rewrite_zip(
+ _deck(1),
+ {
+ "_rels/.rels": lambda xml: xml.replace(
+ b"/officeDocument", b"/officeDocumentX"
+ )
+ },
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="main document"):
+ guard.validate_zip_container(data, ".pptx")
+
+ @pytest.mark.parametrize(
+ ("written", "ext"),
+ [
+ (".docx", ".pptx"),
+ (".pptx", ".docx"),
+ (".xlsx", ".docx"),
+ (".docx", ".xlsx"),
+ (".xlsx", ".pptx"),
+ ],
+ )
+ def test_package_of_another_kind_is_refused(self, written, ext):
+ guard = _guard()
+
+ with pytest.raises(guard.DecompressionBombError, match="part names"):
+ guard.validate_zip_container(_real_package(written), ext)
+
+ def test_relocated_main_part_is_refused(self):
+ # python-docx would read word/main.xml through the relationship,
+ # but no member name tells the sniffer this is a .docx, so a
+ # mimetype member would decide (or it calls it a plain zip).
+ guard = _guard()
+ data = _renamed_members(
+ _real_package(".docx"), {"word/document.xml": "word/main.xml"}
+ )
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ assert b"word/main.xml" in archive.read("_rels/.rels")
+
+ with pytest.raises(guard.DecompressionBombError, match="part names"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_xlsx_must_hold_xl_workbook_xml(self):
+ # The sniffer's pattern matches xl/workbook2.xml, but pandas picks
+ # openpyxl only for xl/workbook.xml.
+ guard = _guard()
+ data = _xlsx_with_sheets(
+ ["rId1"],
+ [("rId1", "worksheets/sheet1.xml")],
+ workbook="xl/workbook2.xml",
+ )
+
+ with pytest.raises(
+ guard.DecompressionBombError, match="xl/workbook.xml"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ @pytest.mark.parametrize(
+ ("ext", "mimetype", "other"),
+ [
+ (
+ ".odt",
+ b"application/vnd.oasis.opendocument.text",
+ b"application/epub+zip",
+ ),
+ (
+ ".epub",
+ b"application/epub+zip",
+ b"application/vnd.oasis.opendocument.text",
+ ),
+ ],
+ )
+ def test_odt_and_epub_mimetype_must_name_the_extension(
+ self, ext, mimetype, other
+ ):
+ guard = _guard()
+ guard.validate_zip_container(
+ _zip_bytes({"mimetype": mimetype, "content.xml": b"<a/>"}), ext
+ )
+ guard.validate_zip_container(_zip_bytes({"content.xml": b"<a/>"}), ext)
+
+ for wrong in (other, b"application/msword", b"\xff\xfe", b"x" * 300):
+ with pytest.raises(guard.DecompressionBombError, match="mimetype"):
+ guard.validate_zip_container(
+ _zip_bytes({"mimetype": wrong, "content.xml": b"<a/>"}),
+ ext,
+ )
+
+ def test_upload_path_never_reaches_the_legacy_partitioner(self):
+ doc_partitioner = pytest.importorskip("unstructured.partition.doc")
+ from local_deep_research.document_loaders.bytes_loader import (
+ load_from_bytes,
+ )
+
+ guard = _guard()
+ data = _zip_bytes({"mimetype": b"application/msword"})
+ with patch.object(
+ doc_partitioner,
+ "partition_doc",
+ side_effect=AssertionError("routed to soffice"),
+ ):
+ with pytest.raises(guard.DecompressionBombError):
+ load_from_bytes(data, ".docx", "sniffed.docx")
+
+
+def _one_cell_table(span: int, content: bytes) -> bytes:
+ return (
+ b"<w:tbl><w:tr><w:tc><w:tcPr><w:gridSpan w:val='%d'/></w:tcPr>" % span
+ + content
+ + b"</w:tc></w:tr></w:tbl>"
+ )
+
+
+def _union_units(steps: int, reads: int | None = None) -> int:
+ guard = _guard()
+ reads = guard.DOCX_UNION_READS if reads is None else reads
+ return -(-steps * reads // guard.DOCX_UNION_STEPS_PER_RUN_WORK_UNIT)
+
+
+def _without_sections(data: bytes) -> bytes:
+ return _rewrite_zip(
+ data,
+ {
+ "word/document.xml": lambda xml: re.sub(
+ rb"<w:sectPr.*?</w:sectPr>", b"", xml, flags=re.S
+ )
+ },
+ )
+
+
+class TestDocxNodeSetUnions:
+ # python-docx selects a cell's, a header's (and, without sections,
+ # the body's) paragraphs and tables with ``./w:p | ./w:tbl``, a
+ # paragraph's runs and hyperlinks with ``w:r | w:hyperlink`` and a
+ # run's text with a six-branch union; libxml2 merges the branches by
+ # comparing every node with every node, then sorts the result with
+ # comparisons that walk sibling links, so one evaluation costs up to
+ # (selected nodes) x (child nodes) steps once a later branch's node
+ # precedes an earlier one's. None of this was counted.
+
+ @pytest.mark.parametrize("tables_first", [False, True])
+ def test_cell_of_tables_and_paragraphs_is_refused(self, tables_first):
+ # One cell spanning 1,000 columns holding 16,000 empty paragraphs
+ # and 16,000 empty tables, a 37 KB file: accepted at 0.09 of the
+ # ceiling before, ~1.5 s per yield (~25 minutes).
+ guard = _guard()
+ blocks = [b"<w:p/>" * 16_000, b"<w:tbl/>" * 16_000]
+ if tables_first:
+ blocks.reverse()
+ data = _blank_with(_one_cell_table(1000, b"".join(blocks) + b"<w:p/>"))
+ assert len(data) < 40_000
+
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_cell_paragraphs_count_once_per_yield(self):
+ guard = _guard()
+ item = guard.DOCX_CELL_BLOCK_ITEM_WEIGHT
+
+ def run_work(paragraphs: int) -> int:
+ return _docx_stats(
+ _blank_with(_one_cell_table(10, b"<w:p/>" * paragraphs))
+ ).run_work
+
+ assert run_work(101) - run_work(1) == 10 * 100 * item
+ # 32,000 empty paragraphs in a cell spanning 1,000 columns: about
+ # 20 us per paragraph and yield, ~10 minutes; 125 units per
+ # yield (one per 256 nodes) before.
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(
+ _blank_with(_one_cell_table(1000, b"<w:p/>" * 32_000)),
+ ".docx",
+ )
+
+ def test_cell_union_counts_selected_nodes_times_children(self):
+ guard = _guard()
+ weight = guard.DOCX_RUN_WORK_ITEM_WEIGHT
+ item = guard.DOCX_CELL_BLOCK_ITEM_WEIGHT
+ content = b"<w:tbl/>" * 3 + b"<w:p/>" * 40 + _MARKER * 200
+ stats = _docx_stats(_blank_with(_one_cell_table(7, content)))
+ # The cell's children: w:tcPr, 43 blocks and 200 markers.
+ children = 1 + 43 + 200
+ assert stats.run_work == weight + 7 * (
+ weight + 43 * item + _union_units(43 * children)
+ )
+
+ def test_paragraph_union_is_counted(self):
+ # A hyperlink before 8,000 runs and 40,000 empty elements in one
+ # paragraph, a 38 KB file: accepted at 0.03 of the ceiling
+ # before and took 15 s to partition (4,000 runs beside 20,000:
+ # 2.8 s; the cost quadruples per doubling).
+ guard = _guard()
+ run = b"<w:r><w:t xml:space='preserve'>a </w:t></w:r>"
+ link = b"<w:hyperlink><w:r><w:t>h</w:t></w:r></w:hyperlink>"
+ data = _blank_with(
+ b"<w:p>" + link + run * 8_000 + b"<w:x/>" * 40_000 + b"</w:p>"
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+ plain = _docx_stats(_blank_with(b"<w:p>" + run * 3 + b"</w:p>"))
+ linked = _docx_stats(_blank_with(b"<w:p>" + link + run * 3 + b"</w:p>"))
+ weight = guard.DOCX_RUN_WORK_ITEM_WEIGHT
+ assert plain.run_work == 3 * (weight + 1)
+ assert linked.run_work == 4 * (weight + 1) + _union_units(4 * 4)
+
+ def test_run_union_is_counted(self):
+ # 8,000 w:t, then a w:br, then 40,000 empty elements in one run,
+ # a 38 KB file: accepted at 0.03 of the ceiling before, 14 s to
+ # partition (4,000 and 20,000: 2.5 s).
+ guard = _guard()
+ text = b"<w:t xml:space='preserve'>a </w:t>"
+ data = _blank_with(
+ b"<w:p><w:r>"
+ + text * 8_000
+ + b"<w:br/>"
+ + b"<w:x/>" * 40_000
+ + b"</w:r></w:p>"
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+ weight = guard.DOCX_RUN_WORK_ITEM_WEIGHT
+ one_kind = _docx_stats(
+ _blank_with(b"<w:p><w:r>" + text * 5 + b"</w:r></w:p>")
+ )
+ assert one_kind.run_work == weight + 5
+ # Three kinds: two merges, of 7 selected nodes among 7 children.
+ mixed = _docx_stats(
+ _blank_with(
+ b"<w:p><w:r>" + text * 5 + b"<w:tab/><w:br/></w:r></w:p>"
+ )
+ )
+ assert mixed.run_work == weight + 7 + _union_units(2 * 7 * 7)
+
+ def test_body_union_is_counted_without_sections(self):
+ paragraph = b"<w:p><w:r><w:t>a</w:t></w:r></w:p>"
+
+ def stats(prefix: bytes):
+ return _docx_stats(
+ _without_sections(_blank_with(prefix + paragraph * 50))
+ )
+
+ plain, tabled = stats(b""), stats(b"<w:tbl/>")
+ assert plain.sections == tabled.sections == 0
+ # The table's own work is a table item; the union is read once.
+ assert tabled.run_work - plain.run_work == _union_units(
+ 51 * tabled.body_nodes, reads=1
+ )
+ # With a section the body union is not read (the section lookup
+ # is priced instead).
+ with_sections = _docx_stats(_blank_with(b"<w:tbl/>" + paragraph * 50))
+ without_table = _docx_stats(_blank_with(paragraph * 50))
+ assert with_sections.run_work == without_table.run_work
+
+ def test_header_unions_count_per_reference(self):
+ # A header holding a table before 8,000 paragraphs and 40,000
+ # empty elements, referenced by ten sections, a 37 KB file:
+ # accepted at 0.23 of the header ceiling before and took 35 s
+ # (two references: 8 s).
+ guard = _guard()
+ header = (
+ b"h</w:t></w:r></w:p><w:tbl/>"
+ + b"<w:p/>" * 8_000
+ + b"<w:x/>" * 40_000
+ + b"<w:p><w:r><w:t>x"
+ )
+
+ with pytest.raises(guard.DecompressionBombError, match="header/footer"):
+ guard.validate_zip_container(
+ _docx_with_sections(10, header=header), ".docx"
+ )
+ # Without a table first, the root's union has one branch.
+ plain = _docx_with_sections(3, header=b"plain")
+ with zipfile.ZipFile(io.BytesIO(plain)) as archive:
+ size = archive.getinfo("word/header1.xml").file_size
+ assert _docx_stats(plain).referenced_bytes == 3 * size
+ tabled = _docx_with_sections(
+ 3,
+ header=b"h</w:t></w:r></w:p><w:tbl/><w:p/>"
+ + b"<w:x/>" * 1_000
+ + b"<w:p><w:r><w:t>x",
+ )
+ with zipfile.ZipFile(io.BytesIO(tabled)) as archive:
+ size = archive.getinfo("word/header1.xml").file_size
+ # The root's union: 4 selected nodes among 1,004 children, read
+ # once per reference.
+ assert _docx_stats(tabled).referenced_bytes == 3 * size + (
+ 3 * 4 * 1_004 // guard.DOCX_UNION_STEPS_PER_HEADER_BYTE
+ )
+
+ def test_word_like_document_with_links_and_nested_tables_is_accepted(self):
+ # 2,000 paragraphs of eight runs around a hyperlink, and a 20 x 5
+ # table whose cells each hold a nested 2 x 2 table and a
+ # paragraph: the unions add little to the text extraction.
+ guard = _guard()
+ run = b"<w:r><w:rPr><w:b/></w:rPr><w:t xml:space='preserve'>word </w:t></w:r>"
+ link = b"<w:hyperlink><w:r><w:t>link</w:t></w:r></w:hyperlink>"
+ paragraph = b"<w:p>" + run * 4 + link + run * 4 + b"</w:p>"
+ nested = (
+ b"<w:tbl>"
+ + (
+ b"<w:tr>"
+ + (b"<w:tc><w:p>" + run + b"</w:p></w:tc>") * 2
+ + b"</w:tr>"
+ )
+ * 2
+ + b"</w:tbl>"
+ )
+ cell = b"<w:tc>" + nested + b"<w:p>" + run + b"</w:p></w:tc>"
+ table = (
+ b"<w:tbl>" + (b"<w:tr>" + cell * 5 + b"</w:tr>") * 20 + b"</w:tbl>"
+ )
+ data = _blank_with(paragraph * 2_000 + table)
+
+ guard.validate_zip_container(data, ".docx")
+ stats = _docx_stats(data)
+ assert stats.run_work < guard.MAX_DOCX_RUN_WORK // 2
+
+
+_BREAK_IN_RUN = b"<w:p><w:r><w:lastRenderedPageBreak/></w:r></w:p>"
+_BREAK_IN_LINK = (
+ b"<w:p><w:hyperlink><w:r><w:lastRenderedPageBreak/></w:r></w:hyperlink>"
+ b"</w:p>"
+)
+# The same paragraph with its break outside every branch of the union.
+_BREAK_IN_SMART_TAG = (
+ b"<w:p><w:smartTag><w:r><w:lastRenderedPageBreak/></w:r></w:smartTag></w:p>"
+)
+_PAGE_BREAK_BRANCHES = (
+ "./w:body/w:p/w:r/w:lastRenderedPageBreak",
+ "./w:body/w:p/w:hyperlink/w:r/w:lastRenderedPageBreak",
+ "./w:body/w:tbl/w:tr/w:tc/w:p/w:r/w:lastRenderedPageBreak",
+ "./w:body/w:tbl/w:tr/w:tc/w:p/w:hyperlink/w:r/w:lastRenderedPageBreak",
+)
+
+
+def _cell_of(content: bytes) -> bytes:
+ return b"<w:tbl><w:tr><w:tc>" + content + b"</w:tc></w:tr></w:tbl>"
+
+
+def _run_work_with_pair_price(data: bytes, pairs_per_unit: int) -> int:
+ with patch.object(
+ _guard(), "DOCX_PAGE_BREAK_UNION_PAIRS_PER_UNIT", pairs_per_unit
+ ):
+ return _docx_stats(data).run_work
+
+
+def _run_work_with_sort_price(data: bytes, steps_per_unit: int) -> int:
+ with patch.object(
+ _guard(), "DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT", steps_per_unit
+ ):
+ return _docx_stats(data).run_work
+
+
+def _expected_sort_steps(data: bytes) -> int:
+ """The sum over the elements of ``document.xml`` of the union's
+ breaks at or below each, B, weighted for the sort's binary insertion
+ (B + 4 * min(B, 64)), times its child nodes as python-docx's tree
+ has them (text included), computed from the parsed tree."""
+ from lxml import etree
+
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ root = etree.fromstring(zf.read("word/document.xml"))
+ ns = {"w": _W_MAIN}
+ breaks = set()
+ for branch in _PAGE_BREAK_BRANCHES:
+ breaks.update(root.xpath(branch, namespaces=ns))
+ below: dict = {}
+ steps = 0
+ for element in reversed(list(root.iter())):
+ count = (element in breaks) + sum(below.get(c, 0) for c in element)
+ below[element] = count
+ nodes = len(element) + bool(element.text)
+ nodes += sum(bool(child.tail) for child in element)
+ steps += (count + 4 * min(count, 64)) * nodes
+ return steps
+
+
+class TestDocxPageBreakUnion:
+ # unstructured asks once per document whether it has rendered page
+ # breaks, with a four-branch union over the whole body; libxml2
+ # compares each branch's nodes with every node merged before them,
+ # so 20,000 breaks in one table cell after 20,000 in body paragraphs
+ # took 0.8 s, quadrupling per doubling, while a break in a cell cost
+ # about one unit of MAX_DOCX_RUN_WORK: 96,000 in each of the two
+ # cell branches, ~0.9 of that ceiling, were accepted (~18 s).
+
+ def test_premise_unstructured_unions_four_branches_over_the_body(self):
+ import inspect
+
+ docx = pytest.importorskip("docx")
+ udocx = pytest.importorskip("unstructured.partition.docx")
+ source = inspect.getsource(udocx)
+ for branch in _PAGE_BREAK_BRANCHES:
+ assert branch in source
+ data = _blank_with(
+ _BREAK_IN_RUN * 2
+ + _BREAK_IN_LINK * 3
+ + _cell_of(_BREAK_IN_RUN * 5 + _BREAK_IN_LINK * 7)
+ + _BREAK_IN_SMART_TAG
+ )
+ element = docx.Document(io.BytesIO(data)).element
+ assert [len(element.xpath(b)) for b in _PAGE_BREAK_BRANCHES] == [
+ 2,
+ 3,
+ 5,
+ 7,
+ ]
+
+ def test_breaks_over_the_ceiling_are_refused(self):
+ guard = _guard()
+ limit = guard.MAX_DOCX_PAGE_BREAKS
+ refusal = f"more than {limit} rendered page breaks"
+ # One branch: no merge and no sort to price (two branches of
+ # half each in one cell are refused by their sort's price).
+ at_ceiling = _blank_with(_cell_of(_BREAK_IN_RUN * limit))
+ guard.validate_zip_container(at_ceiling, ".docx")
+ over = _blank_with(_cell_of(_BREAK_IN_RUN * limit + _BREAK_IN_LINK))
+ with pytest.raises(guard.DecompressionBombError, match=refusal):
+ guard.validate_zip_container(over, ".docx")
+ # Breaks outside the union's branches count toward it too.
+ elsewhere = _blank_with(
+ _cell_of(_BREAK_IN_SMART_TAG * (guard.MAX_DOCX_PAGE_BREAKS + 1))
+ )
+ with pytest.raises(guard.DecompressionBombError, match=refusal):
+ guard.validate_zip_container(elsewhere, ".docx")
+
+ def test_hostile_cross_branch_document_is_refused_by_default(self):
+ # Accepted at ~0.85 of MAX_DOCX_RUN_WORK before; the union alone
+ # would take ~16 s.
+ guard = _guard()
+ data = _blank_with(
+ _cell_of(_BREAK_IN_RUN * 90_000 + _BREAK_IN_LINK * 90_000)
+ )
+ assert len(data) < 200_000
+ with pytest.raises(
+ guard.DecompressionBombError, match="rendered page breaks"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_cross_branch_pairs_are_priced(self):
+ # Each branch is merged against the branches before it, so the
+ # pairs are the sum over pairs of branches of their products.
+ a, b, c, d = 3, 5, 7, 11
+ data = _blank_with(
+ _BREAK_IN_RUN * a
+ + _BREAK_IN_LINK * b
+ + _cell_of(_BREAK_IN_RUN * c + _BREAK_IN_LINK * d)
+ )
+ pairs = a * b + a * c + a * d + b * c + b * d + c * d
+ # Priced at one unit per pair, or rounded up to one unit.
+ assert (
+ _run_work_with_pair_price(data, 1)
+ - _run_work_with_pair_price(data, 10**30)
+ == pairs - 1
+ )
+ # One branch alone, or breaks outside the branches: no merge.
+ for content in (
+ _BREAK_IN_RUN * 50,
+ _BREAK_IN_RUN * 7 + _BREAK_IN_SMART_TAG * 11,
+ ):
+ single = _blank_with(_cell_of(content))
+ assert _run_work_with_pair_price(
+ single, 1
+ ) == _run_work_with_pair_price(single, 10**30)
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ # Rows of hyperlink breaks before rows of plain ones, then
+ # empty table children.
+ b"<w:tbl>"
+ + (b"<w:tr><w:tc>" + _BREAK_IN_LINK + b"</w:tc></w:tr>") * 3
+ + (b"<w:tr><w:tc>" + _BREAK_IN_RUN + b"</w:tc></w:tr>") * 2
+ + b"<w:bookmarkEnd/>" * 50
+ + b"</w:tbl>",
+ # Body paragraphs and a cell, text between them.
+ _BREAK_IN_LINK * 3
+ + b"text"
+ + _cell_of(_BREAK_IN_RUN * 4 + b"<w:x/>" * 9)
+ + _BREAK_IN_RUN * 2,
+ ],
+ )
+ def test_sort_steps_are_priced(self, body):
+ # Each element counts the union's breaks below it times its
+ # child nodes, priced at one unit per step here.
+ data = _blank_with(body)
+ steps = _expected_sort_steps(data)
+ assert steps > 0
+ assert (
+ _run_work_with_sort_price(data, 1)
+ - _run_work_with_sort_price(data, 10**30)
+ == steps - 1
+ )
+
+ @pytest.mark.parametrize(
+ "content",
+ [
+ _BREAK_IN_RUN * 50 + b"<w:x/>" * 500,
+ _BREAK_IN_LINK * 7 + _BREAK_IN_SMART_TAG * 11 + b"<w:x/>" * 500,
+ ],
+ )
+ def test_sort_of_one_branch_is_not_priced(self, content):
+ # One non-empty branch is already in document order.
+ data = _blank_with(_cell_of(content))
+ assert _run_work_with_sort_price(data, 1) == _run_work_with_sort_price(
+ data, 10**30
+ )
+
+ def test_hostile_sort_filler_is_refused_by_default(self):
+ # 1,000 rows of hyperlink breaks before 1,000 rows of plain
+ # ones, then empty table children the sort walks per break:
+ # 160,000 took 2.2-2.6 s per evaluation and 640,000 10.5 s, all
+ # counted at 0.02 of MAX_DOCX_RUN_WORK before.
+ guard = _guard()
+
+ def row(paragraph: bytes) -> bytes:
+ return b"<w:tr><w:tc>" + paragraph + b"</w:tc></w:tr>"
+
+ data = _blank_with(
+ b"<w:tbl>"
+ + row(_BREAK_IN_LINK) * 1_000
+ + row(_BREAK_IN_RUN) * 1_000
+ + b"<w:bookmarkEnd/>" * 1_000_000
+ + b"</w:tbl>"
+ )
+ assert len(data) < 80_000
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_sort_price_covers_siblings_far_apart_in_memory(self):
+ # Filler elements with 16 empty attributes each lie a cache miss
+ # apart: 1,000 rows of each branch before 200,000 of them took
+ # 16 s per evaluation (40 ns per step), counted at 0.29 of
+ # MAX_DOCX_RUN_WORK at 30 ns per step before.
+ guard = _guard()
+ filler = (
+ b"<w:bookmarkEnd"
+ + b"".join(b' w:a%d=""' % n for n in range(16))
+ + b"/>"
+ )
+
+ def row(paragraph: bytes) -> bytes:
+ return b"<w:tr><w:tc>" + paragraph + b"</w:tc></w:tr>"
+
+ data = _blank_with(
+ b"<w:tbl>"
+ + row(_BREAK_IN_LINK) * 1_000
+ + row(_BREAK_IN_RUN) * 1_000
+ + filler * 200_000
+ + b"</w:tbl>"
+ )
+ assert len(data) < 200_000
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_sort_price_covers_binary_insertion(self):
+ # Below 64 nodes libxml2 sorts by binary insertion: 62 breaks of
+ # one branch before one of another walked the filler after them
+ # about 12 times per break (1.1 s per evaluation over 200,000
+ # plain filler elements, 5.4 s over elements with 16
+ # attributes). Unweighted, this shape counts at 0.25 of
+ # MAX_DOCX_RUN_WORK; weighted, it is refused.
+ guard = _guard()
+
+ def row(paragraph: bytes) -> bytes:
+ return b"<w:tr><w:tc>" + paragraph + b"</w:tc></w:tr>"
+
+ data = _blank_with(
+ b"<w:tbl>"
+ + row(_BREAK_IN_LINK) * 62
+ + row(_BREAK_IN_RUN)
+ + b"<w:bookmarkEnd/>" * 1_200_000
+ + b"</w:tbl>"
+ )
+ assert len(data) < 100_000
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_sort_price_defaults(self):
+ guard = _guard()
+ assert guard.DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT <= 200
+ assert guard.DOCX_PAGE_BREAK_SORT_INSERTION_WALKS >= 4
+ assert guard.DOCX_PAGE_BREAK_SORT_INSERTION_RUN >= 64
+
+ def test_pairs_refuse_below_the_count_ceiling(self):
+ # 40,000 breaks in each cell branch: 1.6e9 pairs, ~3.2-3.6 s for
+ # the union, counted at 0.37 of MAX_DOCX_RUN_WORK before.
+ guard = _guard()
+ data = _blank_with(
+ _cell_of(_BREAK_IN_RUN * 40_000 + _BREAK_IN_LINK * 40_000)
+ )
+ with patch.object(guard, "MAX_DOCX_PAGE_BREAKS", 10**9):
+ with pytest.raises(
+ guard.DecompressionBombError, match="cells cost"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_word_like_long_document_is_accepted(self):
+ # 280 pages of ten paragraphs, each page's first paragraph
+ # starting with a rendered break (some inside a hyperlink), then
+ # a four-column table of 600 rows over 20 pages, each page
+ # boundary crossing a row and putting a break in each of its
+ # cells: Word's one break per page and flow.
+ guard = _guard()
+ text = b"<w:r><w:t xml:space='preserve'>Some words on the page. </w:t></w:r>"
+ page = b"".join(
+ (
+ b"<w:p><w:r><w:lastRenderedPageBreak/><w:t>Start</w:t></w:r>"
+ if n % 7
+ else b"<w:p><w:hyperlink><w:r><w:lastRenderedPageBreak/>"
+ b"<w:t>Link</w:t></w:r></w:hyperlink>"
+ )
+ + text * 4
+ + b"</w:p>"
+ + (b"<w:p>" + text * 6 + b"</w:p>") * 9
+ for n in range(280)
+ )
+
+ def row(n: int) -> bytes:
+ mark = b"<w:lastRenderedPageBreak/>" if n % 30 == 29 else b""
+ cell = (
+ b"<w:tc><w:p><w:r>"
+ + mark
+ + b"<w:t>cell</w:t></w:r></w:p></w:tc>"
+ )
+ return b"<w:tr>" + cell * 4 + b"</w:tr>"
+
+ table = b"<w:tbl>" + b"".join(row(n) for n in range(600)) + b"</w:tbl>"
+ data = _blank_with(page + table)
+
+ guard.validate_zip_container(data, ".docx")
+ assert (
+ _run_work_with_pair_price(data, 1)
+ - _run_work_with_pair_price(data, 10**30)
+ == 240 * 40 + 40 * 80 + 240 * 80 - 1
+ )
+ # Its sort steps are a small share of the ceiling.
+ steps = _expected_sort_steps(data)
+ assert (
+ 0
+ < steps
+ < (
+ guard.MAX_DOCX_RUN_WORK
+ * guard.DOCX_PAGE_BREAK_SORT_STEPS_PER_UNIT
+ )
+ // 100
+ )
+
+
+def _inline_drawing(runs: bytes, inline: bytes = b"wp:inline") -> bytes:
+ return (
+ b"<w:r><w:drawing><"
+ + inline
+ + b">"
+ + runs
+ + b"</"
+ + inline
+ + b"></w:drawing></w:r>"
+ )
+
+
+_PLAIN_RUN = b"<w:r><w:t>x</w:t></w:r>"
+
+
+class TestDocxInlineDrawingRuns:
+ # unstructured reads a body-level paragraph's text with
+ # ``w:r | w:hyperlink | w:r/descendant::wp:inline[ancestor::w:drawing][1]//w:r``;
+ # the third branch's runs are not the paragraph's children, so the
+ # union's merge and sort are not bounded by the paragraph's own
+ # child count, and a paragraph with a single w:r branch counted
+ # nothing: one run whose inline drawing holds a run, before 10,000
+ # plain runs (37 KB), took 0.37 s per evaluation at 0.04 of the
+ # ceiling (40,000: 8.9 s), ten runs whose drawings hold 5,000 runs
+ # each 2.9 s at 0.17.
+
+ def test_premise_unstructured_reads_runs_in_inline_drawings(self):
+ import inspect
+
+ docx = pytest.importorskip("docx")
+ udocx = pytest.importorskip("unstructured.partition.docx")
+ union = (
+ "w:r | w:hyperlink | "
+ "w:r/descendant::wp:inline[ancestor::w:drawing][1]//w:r"
+ )
+ assert union in inspect.getsource(udocx)
+ data = _blank_with(
+ b"<w:p>"
+ + _inline_drawing(b"<w:r/>" * 4)
+ + _PLAIN_RUN * 3
+ + b"</w:p>"
+ )
+ p = docx.Document(io.BytesIO(data)).paragraphs[0]._p
+ assert len(p.xpath(union)) == 1 + 3 + 4
+
+ @pytest.mark.parametrize("nested, plain", [(50, 30), (1, 300)])
+ def test_inline_runs_are_a_third_branch(self, nested, plain):
+ def stats(inline: bytes):
+ return _docx_stats(
+ _blank_with(
+ b"<w:p>"
+ + _inline_drawing(b"<w:r/>" * nested, inline)
+ + _PLAIN_RUN * plain
+ + b"</w:p>"
+ )
+ )
+
+ # Under wp:anchor the runs are not selected, and nothing else
+ # differs. The inline's own child nodes (the nested runs, which
+ # have none) are walked by the sort as well.
+ selected = 1 + plain + nested
+ children = 1 + plain
+ assert stats(b"wp:inline").run_work - stats(
+ b"wp:anchor"
+ ).run_work == _union_units(
+ selected * max(children, selected) + selected * nested
+ )
+
+ @pytest.mark.parametrize("nested, filler", [(3, 0), (40, 500), (1, 2_000)])
+ def test_nodes_in_inline_drawings_are_priced(self, nested, filler):
+ # A run whose drawing holds runs before filler, then a
+ # hyperlink: sorting the drawing's runs walks the filler after
+ # them, so the drawing's nodes count once per node selected.
+ def stats(inline: bytes):
+ return _docx_stats(
+ _blank_with(
+ b"<w:p>"
+ + _inline_drawing(
+ b"<w:c>"
+ + b"<w:r/>" * nested
+ + b"<w:x/>" * filler
+ + b"</w:c>",
+ inline,
+ )
+ + b"<w:hyperlink/></w:p>"
+ )
+ )
+
+ selected = 1 + 1 + nested
+ children = 2
+ # The inline's one child, and w:c's runs and filler.
+ drawing_nodes = 1 + nested + filler
+ # Three non-empty branches under wp:inline, two under wp:anchor.
+ with_drawing = _union_units(
+ 2 * selected * max(children, selected) + selected * drawing_nodes
+ )
+ without = _union_units(children * children)
+ assert (
+ stats(b"wp:inline").run_work - stats(b"wp:anchor").run_work
+ == with_drawing - without
+ )
+
+ def test_hostile_drawing_filler_is_refused(self):
+ # One run with a hyperlink after it, its drawing holding 1,000
+ # runs before 100,000 empty elements: 0.31-0.39 s per evaluation
+ # of the paragraph union, counted at 0.04 of MAX_DOCX_RUN_WORK
+ # before.
+ guard = _guard()
+ drawing = _inline_drawing(
+ b"<w:c>" + b"<w:r/>" * 1_000 + b"<w:x/>" * 100_000 + b"</w:c>"
+ )
+ data = _blank_with(b"<w:p>" + drawing + b"<w:hyperlink/></w:p>")
+ assert len(data) < 40_000
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+
+ @pytest.mark.parametrize(
+ "paragraph",
+ [
+ # An inline outside a w:drawing.
+ b"<w:p><w:r><w:pict><wp:inline><w:r/><w:r/></wp:inline></w:pict>"
+ b"</w:r>" + _PLAIN_RUN * 5 + b"</w:p>",
+ # A drawing in a hyperlink's run, not the paragraph's.
+ b"<w:p><w:hyperlink>"
+ + _inline_drawing(b"<w:r/><w:r/>")
+ + b"</w:hyperlink></w:p>",
+ ],
+ )
+ def test_runs_the_third_branch_does_not_select_are_not_counted(
+ self, paragraph
+ ):
+ moved = paragraph.replace(b"wp:inline", b"wp:anchor")
+ assert (
+ _docx_stats(_blank_with(paragraph)).run_work
+ == _docx_stats(_blank_with(moved)).run_work
+ )
+
+ @pytest.mark.parametrize(
+ "paragraph",
+ [
+ _inline_drawing(b"<w:r/>") + _PLAIN_RUN * 10_000,
+ _inline_drawing(b"<w:r/>" * 5_000) * 10,
+ ],
+ ids=["one-before-many", "ten-of-many"],
+ )
+ def test_hostile_inline_runs_are_refused(self, paragraph):
+ guard = _guard()
+ data = _blank_with(b"<w:p>" + paragraph + b"</w:p>")
+ assert len(data) < 40_000
+ with pytest.raises(guard.DecompressionBombError, match="cells cost"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_paragraphs_with_inline_text_boxes_are_accepted(self):
+ # 500 paragraphs of 20 runs, each with an inline drawing holding
+ # a text box of two ten-run paragraphs.
+ guard = _guard()
+ box = (
+ b"<wps:txbx><w:txbxContent>"
+ + (b"<w:p>" + _PLAIN_RUN * 10 + b"</w:p>") * 2
+ + b"</w:txbxContent></wps:txbx>"
+ )
+ paragraph = (
+ b"<w:p>"
+ + _PLAIN_RUN * 10
+ + _inline_drawing(box)
+ + _PLAIN_RUN * 10
+ + b"</w:p>"
+ )
+ data = _blank_with(paragraph * 500)
+ guard.validate_zip_container(data, ".docx")
+ assert _docx_stats(data).run_work < guard.MAX_DOCX_RUN_WORK // 4
+
+
+_PPTX_P = "http://schemas.openxmlformats.org/presentationml/2006/main"
+_PPTX_A = "http://schemas.openxmlformats.org/drawingml/2006/main"
+_PPTX_R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"
+
+
+def _placeholder_sp(
+ shape_id: int, idx: int, ph_type: str = "body", junk: int = 0
+):
+ return (
+ f'<p:sp><p:nvSpPr><p:cNvPr id="{shape_id}" name="s{shape_id}"/>'
+ f"<p:cNvSpPr/>{'<p:x/>' * junk}<p:nvPr>"
+ f'<p:ph type="{ph_type}" idx="{idx}"/></p:nvPr></p:nvSpPr><p:spPr/>'
+ "<p:txBody><a:bodyPr/><a:p><a:r><a:t>t</a:t></a:r></a:p></p:txBody>"
+ "</p:sp>"
+ ).encode()
+
+
+def _deck_with_placeholders(
+ on_slide: int,
+ on_layout: int,
+ *,
+ slides: int = 1,
+ junk: int = 0,
+ links: int = 0,
+) -> bytes:
+ """Blank-layout slides each holding *on_slide* placeholders without
+ a position, all of the idx of the layout's last placeholder, after
+ *on_layout* other placeholders without one (each with *junk* empty
+ elements in its non-visual properties); with *links* external
+ hyperlink relationships on each slide."""
+ pptx = pytest.importorskip("pptx")
+ deck = pptx.Presentation()
+ layout = deck.slide_layouts[6]
+ for _ in range(slides):
+ deck.slides.add_slide(layout)
+ layout_name = layout.part.partname[1:]
+ buf = io.BytesIO()
+ deck.save(buf)
+ slide_shapes = b"".join(
+ _placeholder_sp(100 + n, 7777) for n in range(on_slide)
+ )
+ layout_shapes = b"".join(
+ _placeholder_sp(100 + n, 5000 + n, junk=junk) for n in range(on_layout)
+ ) + _placeholder_sp(99_999, 7777)
+ link_rels = "".join(
+ f'<Relationship Id="rIdLink{n}" Type="{_PPTX_R}/hyperlink" '
+ f'Target="https://example.com/{n}" TargetMode="External"/>'
+ for n in range(links)
+ ).encode()
+ changes = {
+ layout_name: lambda xml: xml.replace(
+ b"</p:spTree>", layout_shapes + b"</p:spTree>", 1
+ )
+ }
+ for n in range(1, slides + 1):
+ changes[f"ppt/slides/slide{n}.xml"] = lambda xml: xml.replace(
+ b"</p:spTree>", slide_shapes + b"</p:spTree>", 1
+ )
+ changes[f"ppt/slides/_rels/slide{n}.xml.rels"] = lambda xml: (
+ xml.replace(b"</Relationships>", link_rels + b"</Relationships>", 1)
+ )
+ return _rewrite_zip(buf.getvalue(), changes)
+
+
+def _placeholder_work(data: bytes) -> int:
+ from pptx.opc.packuri import PackURI
+
+ guard = _guard()
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ slides = guard._pptx_slide_targets(archive, PackURI)
+ return guard._pptx_placeholder_work(archive, PackURI, slides, 10**30)
+
+
+def _expected_read_units(data: bytes, slide: int = 1) -> int:
+ """One inherited read of slide *slide*, counted independently from
+ the parsed parts python-pptx resolves."""
+ pptx = pytest.importorskip("pptx")
+ guard = _guard()
+ part = pptx.Presentation(io.BytesIO(data)).slides[slide - 1].part
+ layout = part.slide_layout.part
+ master = layout.slide_master.part
+
+ def shape_tree(element):
+ tree = element.find(f"{{{_PPTX_P}}}cSld/{{{_PPTX_P}}}spTree")
+ below = tree.xpath(
+ "*/node()[not(self::text())]"
+ " | */*/node()[not(self::text())]"
+ " | */*/*/node()[not(self::text())]"
+ )
+ return len(tree), 2 * len(below)
+
+ layout_shapes, layout_nodes = shape_tree(layout._element)
+ master_shapes, master_nodes = shape_tree(master._element)
+ relationships = len(part.rels) + len(layout.rels)
+ return (
+ layout_shapes
+ + master_shapes
+ - (
+ -(layout_nodes + master_nodes)
+ // guard.PPTX_PLACEHOLDER_NODES_PER_UNIT
+ )
+ - (-relationships // guard.PPTX_PLACEHOLDER_RELATIONSHIPS_PER_UNIT)
+ )
+
+
+class TestPptxPlaceholderWork:
+ # unstructured reads top and left of every slide shape up to three
+ # times each; a placeholder without a position of its own inherits
+ # it through python-pptx's uncached layout (and master) lookups,
+ # which build a proxy for each layout placeholder per read: 100
+ # placeholders over a 100-placeholder layout, a 30 KB file, took
+ # 5.2 s, 200 over 200, 18.6 s, and nothing counted them.
+
+ def test_premise_each_inherited_read_scans_the_layout(self):
+ pptx = pytest.importorskip("pptx")
+ from pptx.shapes import shapetree
+
+ data = _deck_with_placeholders(3, 5)
+ layout = pptx.Presentation(io.BytesIO(data)).slide_layouts[6]
+ # The template's three, the five added and the matching one.
+ on_layout = len(list(layout.placeholders))
+ assert on_layout == 9
+ calls = []
+ original = shapetree.LayoutPlaceholders._shape_factory
+
+ def counting(self, element):
+ calls.append(element)
+ return original(self, element)
+
+ with patch.object(
+ shapetree.LayoutPlaceholders, "_shape_factory", counting
+ ):
+ slide = pptx.Presentation(io.BytesIO(data)).slides[0]
+ placeholders = list(slide.placeholders)
+ for shape in placeholders:
+ assert shape.top is not None
+ assert len(calls) == 3 * on_layout
+ for shape in placeholders:
+ assert shape.left is not None
+ assert len(calls) == 2 * 3 * on_layout
+
+ def test_premise_unstructured_reads_positions_of_every_shape(self):
+ import inspect
+
+ upptx = pytest.importorskip("unstructured.partition.pptx")
+ source = inspect.getsource(upptx)
+ assert "return shape.top or 0, shape.left or 0" in source
+ assert (
+ "(shape.top and shape.left) and (shape.top < 0 or shape.left < 0)"
+ in source
+ )
+
+ def test_work_is_placeholders_times_one_read(self):
+ data = _deck_with_placeholders(4, 6, slides=3)
+ read = _expected_read_units(data)
+ assert read > 6
+ assert _placeholder_work(data) == 3 * 4 * read
+
+ def test_layout_nodes_and_slide_relationships_are_counted(self):
+ plain = _deck_with_placeholders(2, 3)
+ junk = _deck_with_placeholders(2, 3, junk=5_000)
+ linked = _deck_with_placeholders(2, 3, links=1_000)
+ for data in (plain, junk, linked):
+ assert _placeholder_work(data) == 2 * _expected_read_units(data)
+ assert _placeholder_work(junk) - _placeholder_work(plain) >= (
+ 2 * 3 * 2 * 5_000 // _guard().PPTX_PLACEHOLDER_NODES_PER_UNIT
+ )
+ assert _placeholder_work(linked) - _placeholder_work(plain) >= (
+ 2 * 1_000 // _guard().PPTX_PLACEHOLDER_RELATIONSHIPS_PER_UNIT
+ )
+
+ def test_ceiling_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ data = _deck_with_placeholders(5, 8, slides=2)
+ work = _placeholder_work(data)
+ with patch.object(guard, "MAX_PPTX_PLACEHOLDER_WORK", work):
+ guard.validate_zip_container(data, ".pptx")
+ with patch.object(guard, "MAX_PPTX_PLACEHOLDER_WORK", work - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="placeholders cost"
+ ):
+ guard.validate_zip_container(data, ".pptx")
+
+ def test_hostile_deck_is_refused_by_default(self):
+ # Three slides of 200 placeholders over a 200-placeholder layout:
+ # ~56 s to partition (one such slide: 18.6 s), accepted before.
+ guard = _guard()
+ data = _deck_with_placeholders(200, 200, slides=3)
+ assert len(data) < 60_000
+ with pytest.raises(
+ guard.DecompressionBombError, match="placeholders cost"
+ ):
+ guard.validate_zip_container(data, ".pptx")
+
+ def test_upload_path_refuses_the_fan_out(self):
+ from local_deep_research.document_loaders.bytes_loader import (
+ load_from_bytes,
+ )
+
+ guard = _guard()
+ data = _deck_with_placeholders(200, 200, slides=3)
+ with pytest.raises(guard.DecompressionBombError):
+ load_from_bytes(data, ".pptx", "placeholders.pptx")
+
+ def test_slide_relationships_over_the_cap_are_refused(self):
+ guard = _guard()
+ data = _deck_with_placeholders(1, 0, links=guard.MAX_PART_RELATIONSHIPS)
+ with pytest.raises(
+ guard.DecompressionBombError, match="relationships part"
+ ):
+ guard.validate_zip_container(data, ".pptx")
+
+ @pytest.mark.parametrize("part", ["slide", "layout", "master"])
+ def test_slide_layout_and_master_with_a_dtd_are_refused(self, part):
+ pptx = pytest.importorskip("pptx")
+ guard = _guard()
+ data = _deck(1)
+ slide = pptx.Presentation(io.BytesIO(data)).slides[0].part
+ layout = slide.slide_layout.part
+ names = {
+ "slide": (slide.partname[1:], b"<p:sld"),
+ "layout": (layout.partname[1:], b"<p:sldLayout"),
+ "master": (layout.slide_master.part.partname[1:], b"<p:sldMaster"),
+ }
+ name, root = names[part]
+ hostile = _rewrite_zip(
+ data, {name: _with_doctype(b"<!DOCTYPE " + root[1:] + b">", root)}
+ )
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(hostile, ".pptx")
+ guard.validate_zip_container(data, ".pptx") # control
+
+ def test_real_decks_are_accepted(self):
+ pptx = pytest.importorskip("pptx")
+ guard = _guard()
+ # Every layout of the default template, each placeholder filled.
+ deck = pptx.Presentation()
+ for layout in deck.slide_layouts:
+ slide = deck.slides.add_slide(layout)
+ for shape in slide.placeholders:
+ if shape.has_text_frame:
+ shape.text_frame.text = "text"
+ buf = io.BytesIO()
+ deck.save(buf)
+ guard.validate_zip_container(buf.getvalue(), ".pptx")
+ assert _placeholder_work(buf.getvalue()) < 600
+ # 300 title-and-content slides: 34 units each.
+ deck = pptx.Presentation()
+ for n in range(300):
+ slide = deck.slides.add_slide(deck.slide_layouts[1])
+ slide.shapes.title.text = f"Slide {n}"
+ slide.placeholders[1].text = "first point\nsecond point"
+ buf = io.BytesIO()
+ deck.save(buf)
+ guard.validate_zip_container(buf.getvalue(), ".pptx")
+ assert _placeholder_work(buf.getvalue()) <= 40 * 300
+
+
+_CT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
+_CT_OFFICE = "application/vnd.openxmlformats-officedocument."
+_CT_SLIDE = _CT_OFFICE + "presentationml.slide+xml"
+_CT_DOCUMENT = _CT_OFFICE + "wordprocessingml.document.main+xml"
+_STYLES_REL = (
+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"
+)
+
+
+def _retyped(data: bytes, partname: str, content_type: str) -> bytes:
+ """*data* with an ``Override`` giving *partname* *content_type*
+ appended to ``[Content_Types].xml`` (a later entry wins)."""
+ override = (
+ f'<Override PartName="{partname}" ContentType="{content_type}"/>'
+ ).encode()
+ return _rewrite_zip(
+ data,
+ {
+ "[Content_Types].xml": lambda xml: xml.replace(
+ b"</Types>", override + b"</Types>", 1
+ )
+ },
+ )
+
+
+def _empty_slide() -> bytes:
+ return (
+ f'<p:sld xmlns:a="{_PPTX_A}" xmlns:r="{_PPTX_R}" xmlns:p="{_PPTX_P}">'
+ "<p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id='1' name=''/>"
+ "<p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/></p:spTree>"
+ "</p:cSld></p:sld>"
+ ).encode()
+
+
+def _chained_layout_deck(on_slide: int, on_layout: int) -> bytes:
+ """``_deck_with_placeholders(on_slide, on_layout)``, but the slide's
+ layout relationship targets an empty slide (typed as a slide, not
+ listed in the presentation), whose own layout relationship targets
+ the layout of *on_layout* placeholders."""
+ direct = _deck_with_placeholders(on_slide, on_layout)
+ with zipfile.ZipFile(io.BytesIO(direct)) as zf:
+ slide_rels = zf.read("ppt/slides/_rels/slide1.xml.rels")
+ layout_rel = re.compile(rb'(Type="[^"]*/slideLayout"\s+Target=")[^"]+"')
+ assert layout_rel.search(slide_rels)
+ chained = _rewrite_zip(
+ direct,
+ {
+ "ppt/slides/_rels/slide1.xml.rels": lambda xml: layout_rel.sub(
+ rb'\g<1>slide99.xml"', xml
+ )
+ },
+ add={
+ "ppt/slides/slide99.xml": _empty_slide(),
+ "ppt/slides/_rels/slide99.xml.rels": slide_rels,
+ },
+ )
+ return _retyped(chained, "/ppt/slides/slide99.xml", _CT_SLIDE)
+
+
+def _chained_docx_part(reltype: str, member: str, payload: bytes) -> bytes:
+ """python-docx's blank document whose *reltype* relationship
+ targets a second document part (typed as one), whose own *reltype*
+ relationship targets *member* holding *payload*, typed as the part
+ *reltype* names."""
+ docx = pytest.importorskip("docx")
+ buf = io.BytesIO()
+ docx.Document().save(buf)
+ target = re.compile(
+ rb'(<Relationship [^>]*Type="'
+ + re.escape(reltype.encode())
+ + rb'"[^>]*Target=")[^"]+"'
+ + rb"|"
+ + rb'(<Relationship [^>]*Target=")[^"]+("[^>]*Type="'
+ + re.escape(reltype.encode())
+ + rb'")'
+ )
+
+ def retarget(xml: bytes) -> bytes:
+ def sub(match):
+ if match.group(1):
+ return match.group(1) + b'document2.xml"'
+ return match.group(2) + b"document2.xml" + match.group(3)
+
+ out, count = target.subn(sub, xml)
+ assert count == 1
+ return out
+
+ chained = _rewrite_zip(
+ buf.getvalue(),
+ {"word/_rels/document.xml.rels": retarget},
+ add={
+ "word/document2.xml": (
+ f'<w:document xmlns:w="{_W_MAIN}"><w:body/></w:document>'
+ ).encode(),
+ "word/_rels/document2.xml.rels": (
+ f'<Relationships xmlns="{_PKG_RELS}"><Relationship Id="rId1" '
+ f'Type="{reltype}" Target="{member.split("/")[-1]}"/>'
+ "</Relationships>"
+ ).encode(),
+ member: payload,
+ },
+ )
+ kind = reltype.rsplit("/", 1)[1]
+ chained = _retyped(
+ chained, f"/{member}", f"{_CT_OFFICE}wordprocessingml.{kind}+xml"
+ )
+ return _retyped(chained, "/word/document2.xml", _CT_DOCUMENT)
+
+
+def _many_styles(count: int) -> bytes:
+ return (
+ f'<w:styles xmlns:w="{_W_MAIN}">'.encode()
+ + b"".join(
+ b'<w:style w:type="paragraph" w:styleId="S%d"/>' % n
+ for n in range(count)
+ )
+ + b"</w:styles>"
+ )
+
+
+class TestRelationshipTargetContentTypes:
+ # python-pptx and python-docx build each part as the class its
+ # content type names, whatever relationship reaches it, and a slide
+ # (or document) part answers ``slide_layout`` (or ``styles`` and
+ # ``settings``) by following its own relationship of that type. A
+ # slide's layout relationship to another slide therefore makes
+ # python-pptx read that slide's layout, which the guard never
+ # priced: 300 placeholders over a chained 300-placeholder layout
+ # were counted at 1,200 units, the same layout reached directly at
+ # about 90,000.
+
+ def test_premise_python_pptx_follows_a_chained_layout(self):
+ pptx = pytest.importorskip("pptx")
+ data = _chained_layout_deck(3, 5)
+ slide = pptx.Presentation(io.BytesIO(data)).slides[0]
+ assert (
+ slide.part.part_related_by(
+ "http://schemas.openxmlformats.org/officeDocument/2006/"
+ "relationships/slideLayout"
+ ).partname
+ == "/ppt/slides/slide99.xml"
+ )
+ # The template's three placeholders, the five added and the
+ # matching one: the layout two relationships away.
+ assert len(list(slide.slide_layout.placeholders)) == 9
+
+ def test_chained_layout_is_refused(self):
+ guard = _guard()
+ direct = _deck_with_placeholders(300, 300)
+ with pytest.raises(
+ guard.DecompressionBombError, match="placeholders cost"
+ ):
+ guard.validate_zip_container(direct, ".pptx")
+ chained = _chained_layout_deck(300, 300)
+ assert len(chained) < 80_000
+ with pytest.raises(
+ guard.DecompressionBombError, match="slide layout part has the"
+ ):
+ guard.validate_zip_container(chained, ".pptx")
+
+ @pytest.mark.parametrize(
+ ("reltype", "member", "attribute"),
+ [
+ (_STYLES_REL, "word/styles2.xml", "styles"),
+ (_SETTINGS_REL, "word/settings2.xml", "settings"),
+ ],
+ )
+ def test_premise_python_docx_follows_a_chained_part(
+ self, reltype, member, attribute
+ ):
+ docx = pytest.importorskip("docx")
+ root = "w:styles" if attribute == "styles" else "w:settings"
+ payload = (
+ f'<{root} xmlns:w="{_W_MAIN}">'.encode()
+ + b"<w:pad/>" * 7
+ + f"</{root}>".encode()
+ )
+ data = _chained_docx_part(reltype, member, payload)
+ document = docx.Document(io.BytesIO(data))
+ assert len(getattr(document, attribute).element) == 7
+
+ @pytest.mark.parametrize(
+ ("reltype", "member", "payload"),
+ [
+ (
+ _STYLES_REL,
+ "word/styles2.xml",
+ lambda guard: _many_styles(guard.MAX_DOCX_STYLES * 4),
+ ),
+ (
+ _SETTINGS_REL,
+ "word/settings2.xml",
+ lambda guard: (
+ f'<w:settings xmlns:w="{_W_MAIN}">'.encode()
+ + b"<w:pad/>" * (guard.MAX_DOCX_SETTINGS_CHILDREN * 4)
+ + b"</w:settings>"
+ ),
+ ),
+ ],
+ ids=["styles", "settings"],
+ )
+ def test_chained_styles_and_settings_are_refused(
+ self, reltype, member, payload
+ ):
+ # Four times the cap behind a second document part: the guard
+ # counted that part's one child before.
+ guard = _guard()
+ data = _chained_docx_part(reltype, member, payload(guard))
+ with pytest.raises(guard.DecompressionBombError, match="content type"):
+ guard.validate_zip_container(data, ".docx")
+
+ @pytest.mark.parametrize(
+ ("ext", "part", "content_type", "what"),
+ [
+ (
+ ".pptx",
+ "main",
+ _CT_OFFICE + "presentationml.slideshow.main+xml",
+ "main",
+ ),
+ (
+ ".pptx",
+ "slide",
+ _CT_OFFICE + "presentationml.slideLayout+xml",
+ "slide",
+ ),
+ (".pptx", "layout", _CT_SLIDE, "slide layout"),
+ (
+ ".pptx",
+ "master",
+ _CT_OFFICE + "presentationml.slideLayout+xml",
+ "slide master",
+ ),
+ (
+ ".docx",
+ "main",
+ "application/vnd.ms-word.document.macroEnabled.main+xml",
+ "main",
+ ),
+ (".docx", "styles", "application/xml", "styles"),
+ (".docx", "settings", _CT_DOCUMENT, "settings"),
+ (
+ ".docx",
+ "header",
+ _CT_OFFICE + "wordprocessingml.footer+xml",
+ "header",
+ ),
+ (
+ ".docx",
+ "footer",
+ _CT_OFFICE + "wordprocessingml.header+xml",
+ "footer",
+ ),
+ ],
+ )
+ def test_mistyped_target_is_refused(self, ext, part, content_type, what):
+ guard = _guard()
+ data, partnames = self._real(ext)
+ guard.validate_zip_container(data, ext) # control
+ hostile = _retyped(data, partnames[part], content_type)
+ with pytest.raises(
+ guard.DecompressionBombError, match=f"{what} part has the wrong"
+ ):
+ guard.validate_zip_container(hostile, ext)
+
+ @staticmethod
+ def _real(ext: str) -> tuple[bytes, dict[str, str]]:
+ """A package python-pptx or python-docx writes (a deck whose
+ slide has placeholders, a document with a header and a footer),
+ and the partnames of its parts."""
+ if ext == ".pptx":
+ pptx = pytest.importorskip("pptx")
+ data = _deck_with_placeholders(2, 2)
+ slide = pptx.Presentation(io.BytesIO(data)).slides[0]
+ layout = slide.slide_layout
+ return data, {
+ "main": "/ppt/presentation.xml",
+ "slide": str(slide.part.partname),
+ "layout": str(layout.part.partname),
+ "master": str(layout.slide_master.part.partname),
+ }
+ docx = pytest.importorskip("docx")
+ document = docx.Document()
+ document.add_paragraph("body")
+ section = document.sections[0]
+ section.header.paragraphs[0].text = "header"
+ section.footer.paragraphs[0].text = "footer"
+ buf = io.BytesIO()
+ document.save(buf)
+ data = buf.getvalue()
+ loaded = docx.Document(io.BytesIO(data))
+ part = loaded.part
+ return data, {
+ "main": str(part.partname),
+ "styles": str(part._styles_part.partname),
+ "settings": str(part._settings_part.partname),
+ "header": str(loaded.sections[0].header.part.partname),
+ "footer": str(loaded.sections[0].footer.part.partname),
+ }
+
+ @pytest.mark.parametrize("ext", [".pptx", ".docx"])
+ def test_real_packages_are_accepted(self, ext):
+ guard = _guard()
+ data, _ = self._real(ext)
+ guard.validate_zip_container(data, ext)
+ # And python-pptx's and python-docx's untouched defaults.
+ guard.validate_zip_container(_real_package(ext), ext)
+
+ def test_content_types_resolve_as_the_libraries_resolve_them(self):
+ docx = pytest.importorskip("docx")
+ guard = _guard()
+ data, partnames = self._real(".docx")
+ styles = partnames["styles"]
+ styles_ct = _CT_OFFICE + "wordprocessingml.styles+xml"
+ # Part names match without regard to case...
+ upper = _retyped(data, styles.upper(), "application/xml")
+ with pytest.raises(guard.DecompressionBombError, match="styles part"):
+ guard.validate_zip_container(upper, ".docx")
+ # ...and a later entry replaces an earlier one, either way.
+ fixed = _retyped(upper, styles, styles_ct)
+ guard.validate_zip_container(fixed, ".docx")
+ assert docx.Document(io.BytesIO(fixed)).styles is not None
+ # Without an Override, the Default of the extension applies.
+ override = re.compile(
+ rb'<Override PartName="' + re.escape(styles.encode()) + rb'"[^>]*/>'
+ )
+ bare = _rewrite_zip(
+ data,
+ {"[Content_Types].xml": lambda xml: override.sub(b"", xml)},
+ )
+ with pytest.raises(guard.DecompressionBombError, match="styles part"):
+ guard.validate_zip_container(bare, ".docx")
+ defaulted = _rewrite_zip(
+ bare,
+ {
+ "[Content_Types].xml": lambda xml: xml.replace(
+ b"</Types>",
+ f'<Default Extension="XML" ContentType="{styles_ct}"/>'
+ "</Types>".encode(),
+ )
+ },
+ )
+ assert docx.Document(io.BytesIO(defaulted)).styles is not None
+ guard.validate_zip_container(defaulted, ".docx")
+
+ @pytest.mark.parametrize("ext", [".pptx", ".docx"])
+ def test_package_without_content_types_is_refused(self, ext):
+ guard = _guard()
+ data = _real_package(ext)
+ with zipfile.ZipFile(io.BytesIO(data)) as zin:
+ entries = {
+ info.filename: zin.read(info)
+ for info in zin.infolist()
+ if info.filename != "[Content_Types].xml"
+ }
+ with pytest.raises(guard.DecompressionBombError, match="content types"):
+ guard.validate_zip_container(_zip_bytes(entries), ext)
+
+
+_MAIN_RELS = {
+ ".docx": "word/_rels/document.xml.rels",
+ ".pptx": "ppt/_rels/presentation.xml.rels",
+}
+
+
+def _relationships(count: int, target: str, external: bool = False) -> bytes:
+ """A relationships part of *count* entries all targeting *target*."""
+ mode = ' TargetMode="External"' if external else ""
+ body = "".join(
+ f'<Relationship Id="h{n}" Type="{_REL_NS}/customXml" '
+ f'Target="{target}"{mode}/>'
+ for n in range(count)
+ )
+ return f'<Relationships xmlns="{_PKG_RELS}">{body}</Relationships>'.encode()
+
+
+def _package_with_parts(
+ ext: str,
+ parts: int,
+ hubs: dict[int, int],
+ *,
+ external: bool = False,
+ name: str = "item",
+) -> bytes:
+ """A real package whose main part relates to *parts* tiny parts
+ ``cx/<name>NNNNN.xml``; part *i* of *hubs* gets a relationships part
+ of ``hubs[i]`` entries, all to the last of them (or external)."""
+ names = [f"{name}{n:05d}.xml" for n in range(parts)]
+ links = "".join(
+ f'<Relationship Id="rX{n}" Type="{_REL_NS}/customXml" '
+ f'Target="../cx/{part}"/>'
+ for n, part in enumerate(names)
+ ).encode()
+ add = {f"cx/{part}": b"<a/>" for part in names}
+ for index, count in hubs.items():
+ add[f"cx/_rels/{names[index]}.rels"] = _relationships(
+ count,
+ "https://example.com/" if external else names[-1],
+ external,
+ )
+ return _rewrite_zip(
+ _real_package(ext),
+ {
+ _MAIN_RELS[ext]: lambda xml: xml.replace(
+ b"</Relationships>", links + b"</Relationships>"
+ )
+ },
+ add,
+ )
+
+
+def _name_bytes(name: str) -> int:
+ """Bytes CPython stores *name* in: 1, 2 or 4 per character by its
+ widest code point (PEP 393)."""
+ widest = max(map(ord, name), default=0)
+ return len(name) * (1 if widest < 256 else 2 if widest < 65_536 else 4)
+
+
+def _walk_steps(data: bytes) -> int:
+ """Internal relationships of every relationships part times the
+ members, each member one step plus one per 256 bytes of its name as
+ CPython stores it."""
+ from lxml import etree
+
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ names = zf.namelist()
+ internal = sum(
+ 1
+ for member in names
+ if member.endswith(".rels")
+ for rel in etree.fromstring(zf.read(member))
+ if rel.get("TargetMode") != "External"
+ )
+ return internal * (len(names) + sum(map(_name_bytes, names)) // 256)
+
+
+def _orphan_rels(ext: str, body: str, root_attrs: str = "") -> bytes:
+ """A real package plus a relationships part no part owns, holding
+ *body* under its root."""
+ return _rewrite_zip(
+ _real_package(ext),
+ add={
+ "cx/_rels/none.xml.rels": (
+ f'<Relationships xmlns="{_PKG_RELS}"{root_attrs}>{body}'
+ "</Relationships>"
+ ).encode()
+ },
+ )
+
+
+class TestPackageRelationships:
+ # python-docx and python-pptx parse the relationships part of every
+ # part they reach, not just those the guard reads; python-docx also
+ # scans a list of the parts it has visited once per internal
+ # relationship (PackageReader._walk_phys_parts, OpcPackage.iter_rels):
+ # 9,000 parts and one unread part with 200,000 relationships to the
+ # last of them, a 1.66 MB file, took 41 s to open.
+
+ def test_premise_python_docx_scans_a_list_of_visited_parts(self):
+ import inspect
+
+ pytest.importorskip("docx")
+ from docx.opc import package, pkgreader
+
+ walk = inspect.getsource(pkgreader.PackageReader._walk_phys_parts)
+ assert "visited_partnames = []" in walk
+ assert "partname in visited_partnames" in walk
+ iter_rels = inspect.getsource(package.OpcPackage.iter_rels)
+ assert "visited = [] if visited is None" in iter_rels
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_premise_unread_relationships_parts_are_parsed(self, ext):
+ # The library reaches the part and reads its relationships.
+ data = _package_with_parts(ext, 3, {1: 2})
+ if ext == ".docx":
+ opened = pytest.importorskip("docx").Document(io.BytesIO(data))
+ else:
+ opened = pytest.importorskip("pptx").Presentation(io.BytesIO(data))
+ parts = {
+ str(rel.target_part.partname): rel.target_part
+ for rel in opened.part.rels.values()
+ if not rel.is_external
+ }
+ assert len(parts["/cx/item00001.xml"].rels) == 2
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_every_relationships_part_is_capped(self, ext):
+ guard = _guard()
+ limit = guard.MAX_PART_RELATIONSHIPS
+ guard.validate_zip_container(
+ _package_with_parts(ext, 2, {0: limit}), ext
+ )
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"more than {limit} entries",
+ ):
+ guard.validate_zip_container(
+ _package_with_parts(ext, 2, {0: limit + 1}), ext
+ )
+ # Reached or not: a relationships part of no part counts too.
+ orphan = _rewrite_zip(
+ _real_package(ext),
+ add={"cx/_rels/none.xml.rels": _relationships(limit + 1, "x")},
+ )
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"more than {limit} entries",
+ ):
+ guard.validate_zip_container(orphan, ext)
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_relationships_are_capped_across_the_package(self, ext):
+ guard = _guard()
+ data = _package_with_parts(
+ ext, 6, {n: 9_000 for n in range(6)}, external=True
+ )
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ total = sum(
+ _count_children(data, member)
+ for member in zf.namelist()
+ if member.endswith(".rels")
+ )
+ assert guard.MAX_PACKAGE_RELATIONSHIPS < total
+ with pytest.raises(
+ guard.DecompressionBombError, match="entries together"
+ ):
+ guard.validate_zip_container(data, ext)
+ with patch.object(guard, "MAX_PACKAGE_RELATIONSHIPS", total):
+ guard.validate_zip_container(data, ext)
+ with patch.object(guard, "MAX_PACKAGE_RELATIONSHIPS", total - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="entries together"
+ ):
+ guard.validate_zip_container(data, ext)
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_unread_relationships_parts_get_the_skeleton_treatment(self, ext):
+ guard = _guard()
+ data = _package_with_parts(ext, 2, {0: 50})
+ member = "cx/_rels/item00000.xml.rels"
+ with_dtd = _rewrite_zip(
+ data,
+ {
+ member: _with_doctype(
+ b"<!DOCTYPE Relationships>", b"<Relationships"
+ )
+ },
+ )
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(with_dtd, ext)
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ size = zf.getinfo(member).file_size
+ with patch.object(guard, "MAX_OPC_SKELETON_PART_BYTES", size - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="larger than"
+ ):
+ guard.validate_zip_container(data, ext)
+
+ def test_relationship_walk_is_priced_exactly(self):
+ guard = _guard()
+ data = _package_with_parts(".docx", 40, {3: 70, 39: 11})
+ steps = _walk_steps(data)
+ with patch.object(guard, "MAX_DOCX_RELATIONSHIP_WALK", steps):
+ guard.validate_zip_container(data, ".docx")
+ with patch.object(guard, "MAX_DOCX_RELATIONSHIP_WALK", steps - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="relationship walk"
+ ):
+ guard.validate_zip_container(data, ".docx")
+ # External relationships are never looked up in the list.
+ external = _package_with_parts(".docx", 40, {3: 500}, external=True)
+ assert _walk_steps(external) < steps
+ with patch.object(guard, "MAX_DOCX_RELATIONSHIP_WALK", steps):
+ guard.validate_zip_container(external, ".docx")
+ # Long names cost their bytes.
+ long = _package_with_parts(
+ ".docx", 40, {3: 70, 39: 11}, name="n" * 2_000
+ )
+ assert _walk_steps(long) > steps * 3
+ with patch.object(guard, "MAX_DOCX_RELATIONSHIP_WALK", steps):
+ with pytest.raises(
+ guard.DecompressionBombError, match="relationship walk"
+ ):
+ guard.validate_zip_container(long, ".docx")
+
+ def test_hostile_relationship_walk_is_refused_by_default(self):
+ # Every relationships part under MAX_PART_RELATIONSHIPS; 9,000
+ # parts and 27,000 internal relationships cost python-docx about
+ # 2.4e8 list comparisons on open.
+ guard = _guard()
+ data = _package_with_parts(".docx", 9_000, {0: 9_000, 1: 9_000})
+ assert len(data) < 2_000_000
+ with pytest.raises(
+ guard.DecompressionBombError, match="relationship walk"
+ ):
+ guard.validate_zip_container(data, ".docx")
+ # python-pptx keeps sets: no walk to price.
+ guard.validate_zip_container(
+ _package_with_parts(".pptx", 9_000, {0: 9_000, 1: 9_000}), ".pptx"
+ )
+
+ def test_document_with_many_images_is_accepted(self):
+ # One part and one internal relationship per image: 5,000 of
+ # them count about an eighth of the ceiling.
+ guard = _guard()
+ data = _package_with_parts(".docx", 5_000, {})
+ assert _walk_steps(data) < guard.MAX_DOCX_RELATIONSHIP_WALK // 4
+ guard.validate_zip_container(data, ".docx")
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_an_entry_with_child_elements_is_refused(self, ext):
+ # The OPC schema gives Relationship text content only. One entry
+ # holding millions of children (16 MiB, ~16 KB deflated, in a
+ # part no library reads) cost the guard 3.1 s and ~550 MB, since
+ # an entry was only dropped at its end.
+ guard = _guard()
+ rel = f'Id="r1" Type="{_REL_NS}/customXml" Target="x.xml"'
+ guard.validate_zip_container(
+ _orphan_rels(ext, f"<Relationship {rel}>text</Relationship>"), ext
+ )
+ for children in (
+ "<a/>",
+ "<a/>" * 200_000,
+ "<x:a xmlns:x='u'><b/></x:a>",
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="child elements"
+ ):
+ guard.validate_zip_container(
+ _orphan_rels(
+ ext, f"<Relationship {rel}>{children}</Relationship>"
+ ),
+ ext,
+ )
+ # Any element below the root's children, whatever it is called.
+ with pytest.raises(
+ guard.DecompressionBombError, match="child elements"
+ ):
+ guard.validate_zip_container(
+ _orphan_rels(ext, "<other><a/></other>"), ext
+ )
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_comments_and_instructions_count_as_entries(self, ext):
+ # Each stays in the streamed tree until the next entry ends.
+ guard = _guard()
+ limit = 50
+ rel = f'<Relationship Id="r1" Type="{_REL_NS}/customXml" Target="x"/>'
+ with patch.object(guard, "MAX_PART_RELATIONSHIPS", limit):
+ guard.validate_zip_container(
+ _orphan_rels(ext, rel + "<!---->" * 24 + "<?p?>" * 25), ext
+ )
+ for body in (
+ rel + "<!---->" * 25 + "<?p?>" * 25,
+ f'<Relationship Id="r1" Type="t" Target="x">{"<!---->" * limit}'
+ "</Relationship>",
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"more than {limit} entries",
+ ):
+ guard.validate_zip_container(_orphan_rels(ext, body), ext)
+ # At the default cap, a part of nothing but comments is refused.
+ with pytest.raises(
+ guard.DecompressionBombError, match="more than .* entries"
+ ):
+ guard.validate_zip_container(
+ _orphan_rels(
+ ext, "<!---->" * (guard.MAX_PART_RELATIONSHIPS + 1)
+ ),
+ ext,
+ )
+
+ @pytest.mark.parametrize("ext", [".docx", ".pptx"])
+ def test_elements_with_many_attributes_are_refused(self, ext):
+ guard = _guard()
+ limit = guard.MAX_RELS_ELEMENT_ATTRIBUTES
+ assert 4 <= limit <= 64
+
+ def attributes(count: int) -> str:
+ return "".join(f' a{n}=""' for n in range(count))
+
+ guard.validate_zip_container(
+ _orphan_rels(ext, f"<Relationship{attributes(limit)}/>"), ext
+ )
+ guard.validate_zip_container(
+ _orphan_rels(ext, "", root_attrs=attributes(limit)), ext
+ )
+ for body, root in (
+ (f"<Relationship{attributes(limit + 1)}/>", ""),
+ ("", attributes(limit + 1)),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"more than {limit} attributes",
+ ):
+ guard.validate_zip_container(
+ _orphan_rels(ext, body, root_attrs=root), ext
+ )
+
+ def test_ordinary_relationships_parts_still_pass(self):
+ # Text content and namespace declarations are allowed.
+ guard = _guard()
+ body = (
+ f'<Relationship xmlns:x="urn:x" Id="r1" Type="{_REL_NS}/customXml"'
+ ' Target="x" TargetMode="External"> </Relationship>'
+ )
+ for ext in (".docx", ".pptx"):
+ guard.validate_zip_container(_orphan_rels(ext, body), ext)
+
+ @pytest.mark.parametrize("char", ["\u00e9", "\u30a2", "\U0001f600"])
+ def test_relationship_walk_prices_names_as_stored(self, char):
+ # CPython compares equal-length names over len * width bytes:
+ # names of four-byte characters measured two to four times the
+ # cost per character of ASCII ones.
+ guard = _guard()
+ ascii_data = _package_with_parts(
+ ".docx", 40, {3: 70, 39: 11}, name="n" * 1_000
+ )
+ data = _package_with_parts(
+ ".docx", 40, {3: 70, 39: 11}, name=char * 1_000
+ )
+ steps = _walk_steps(data)
+ width = {"\u00e9": 1, "\u30a2": 2, "\U0001f600": 4}[char]
+ if width == 1:
+ assert steps == _walk_steps(ascii_data)
+ else:
+ # Every name stored in *width* bytes per character (less
+ # the fixed step per member and the ASCII member names).
+ assert steps > _walk_steps(ascii_data) * (width - 1)
+ with patch.object(guard, "MAX_DOCX_RELATIONSHIP_WALK", steps):
+ guard.validate_zip_container(data, ".docx")
+ with patch.object(guard, "MAX_DOCX_RELATIONSHIP_WALK", steps - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="relationship walk"
+ ):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_relationship_defaults(self):
+ guard = _guard()
+ assert guard.MAX_PART_RELATIONSHIPS >= 10_000
+ assert guard.MAX_PACKAGE_RELATIONSHIPS >= 50_000
+ assert guard.MAX_DOCX_RELATIONSHIP_WALK <= 200_000_000
+ assert guard.DOCX_RELATIONSHIP_WALK_NAME_BYTES_PER_STEP <= 256
+
+
+class TestXlsxSheetCount:
+ # openpyxl checks each sheet's target against a list of the members
+ # and pandas looks every sheet up by name in lists of all of them:
+ # 10,000 empty sheets took 40 s in pandas.read_excel, and 100,000
+ # sheets without parts next to 9,000 members 7.6 s in openpyxl alone.
+
+ def test_premise_lookups_are_linear_scans(self):
+ import inspect
+
+ pytest.importorskip("openpyxl")
+ pytest.importorskip("pandas")
+ from openpyxl.reader.excel import ExcelReader
+ from pandas.io.excel._base import BaseExcelReader
+
+ source = inspect.getsource(ExcelReader.read_worksheets)
+ assert "rel.target not in self.valid_files" in source
+ data = _xlsx_with_sheets(["rId1"], [("rId1", "worksheets/sheet1.xml")])
+ assert isinstance(ExcelReader(io.BytesIO(data)).valid_files, list)
+ assert "not in self.sheet_names" in inspect.getsource(
+ BaseExcelReader.raise_if_bad_sheet_by_name
+ )
+
+ def test_sheet_cap_accepts_the_limit_and_refuses_one_more(self):
+ guard = _guard()
+ limit = guard.MAX_XLSX_SHEETS
+
+ def workbook(sheets: int) -> bytes:
+ return _xlsx_with_sheets(
+ [f"r{n}" for n in range(sheets)],
+ [(f"r{n}", f"worksheets/s{n}.xml") for n in range(sheets)],
+ )
+
+ guard.validate_zip_container(workbook(limit), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match=f"more than {limit} sheets"
+ ):
+ guard.validate_zip_container(workbook(limit + 1), ".xlsx")
+
+ def test_sheet_defaults(self):
+ guard = _guard()
+ assert 500 <= guard.MAX_XLSX_SHEETS <= 2_000
+
+
+_SML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
+
+
+def _stylesheet(
+ formats: list[tuple[int, str]] = (),
+ cell_formats: list[int] = (0,),
+ named: int = 1,
+ named_formats: int = 1,
+ prefix: str = "",
+ namespace: str = _SML_NS,
+ style_ids: list[int] | None = None,
+ fonts: str = "<font/>",
+ fills: str = "<fill><patternFill/></fill>",
+ borders: str = "<border/>",
+ style_format: str = "",
+) -> bytes:
+ """An ``xl/styles.xml`` openpyxl loads: *formats* as (numFmtId,
+ formatCode), one cellXfs ``<xf>`` per id in *cell_formats*, *named*
+ named styles over *named_formats* cellStyleXfs entries (all with a
+ custom format id, so openpyxl rebuilds its format dict per style),
+ under *prefix* bound to *namespace*. *style_ids* overrides the
+ named styles' ``xfId`` values; *fonts*, *fills* and *borders* are
+ the lists' unprefixed contents (one entry each by default), and
+ *style_format* the children of every cellStyleXfs ``<xf>``."""
+ p = f"{prefix}:" if prefix else ""
+ ns = f' xmlns{":" + prefix if prefix else ""}="{namespace}"'
+ numfmts = "".join(
+ f'<{p}numFmt numFmtId="{n}" formatCode="{code}"/>'
+ for n, code in formats
+ )
+ xfs = "".join(
+ f'<{p}xf numFmtId="{n}" fontId="0" fillId="0" borderId="0" xfId="0"/>'
+ for n in cell_formats
+ )
+ style_xf = '<{p}xf numFmtId="164" fontId="0" fillId="0" borderId="0"'
+ style_xfs = (
+ style_xf.format(p=p)
+ + (f">{style_format}</{p}xf>" if style_format else "/>")
+ ) * named_formats
+ if style_ids is None:
+ style_ids = [n % named_formats for n in range(named)]
+ styles = "".join(
+ f'<{p}cellStyle name="s{n}" xfId="{xf_id}"/>'
+ for n, xf_id in enumerate(style_ids)
+ )
+ if prefix:
+ fonts, fills, borders = (
+ re.sub(r"<(/?)(?=\w)", rf"<\1{p}", xml)
+ for xml in (fonts, fills, borders)
+ )
+ return (
+ f"<{p}styleSheet{ns}><{p}numFmts>{numfmts}</{p}numFmts>"
+ f"<{p}fonts>{fonts}</{p}fonts>"
+ f"<{p}fills>{fills}</{p}fills>"
+ f"<{p}borders>{borders}</{p}borders>"
+ f"<{p}cellStyleXfs>{style_xfs}</{p}cellStyleXfs>"
+ f"<{p}cellXfs>{xfs}</{p}cellXfs>"
+ f"<{p}cellStyles>{styles}</{p}cellStyles></{p}styleSheet>"
+ ).encode()
+
+
+def _xlsx_with_styles(styles: bytes) -> bytes:
+ """A workbook openpyxl writes, with *styles* as ``xl/styles.xml``."""
+ return _rewrite_zip(
+ _real_package(".xlsx"), {"xl/styles.xml": lambda _xml: styles}
+ )
+
+
+def _load_xlsx(data: bytes):
+ """Open *data* the way pandas does."""
+ openpyxl = pytest.importorskip("openpyxl")
+ return openpyxl.load_workbook(
+ io.BytesIO(data), read_only=True, data_only=True, keep_links=False
+ )
+
+
+def _gradient_fill(stops: int, tag: str = "gradientFill") -> str:
+ """A ``<fill>`` of *stops* stops, each 13 characters of attribute
+ values, under a first child named *tag*."""
+ return (
+ f"<fill><{tag}>"
+ + "".join(
+ f'<stop position="{n / 1_000:.3f}"><color rgb="FF000000"/></stop>'
+ for n in range(stops)
+ )
+ + f"</{tag}></fill>"
+ )
+
+
+def _format_units(guard, code: str) -> int:
+ return len(code) * (guard.XLSX_NUMBER_FORMAT_SCAN_WEIGHT + code.count("["))
+
+
+class TestXlsxStyles:
+ # openpyxl loads xl/styles.xml on every read (pandas' read-only load
+ # too) and repeats work per cell format and per named style: one
+ # 1,000,000-character format code under 2,000 cell formats, a 3.3 KB
+ # file, took 53 s to load.
+
+ def test_premise_openpyxl_repeats_work_per_format(self):
+ import inspect
+
+ pytest.importorskip("openpyxl")
+ from openpyxl.reader.excel import ExcelReader
+ from openpyxl.styles import stylesheet
+ from openpyxl.xml.constants import ARC_STYLE
+
+ assert ARC_STYLE == "xl/styles.xml"
+ assert "apply_stylesheet(" in inspect.getsource(ExcelReader.read)
+ normalise = inspect.getsource(stylesheet.Stylesheet._normalise_numbers)
+ assert "for idx, style in enumerate(self.cell_styles)" in normalise
+ assert "is_date_format(fmt)" in normalise
+ assert "is_timedelta_format(fmt)" in normalise
+ expand = inspect.getsource(stylesheet.Stylesheet._expand_named_style)
+ assert "self.custom_formats" in expand
+ assert isinstance(
+ inspect.getattr_static(stylesheet.Stylesheet, "custom_formats"),
+ property,
+ )
+ # Children are matched by local name, in any namespace.
+ data = _xlsx_with_styles(
+ _stylesheet(
+ [(164, "0.0")], [164, 164], prefix="x", namespace="urn:x"
+ )
+ )
+ workbook = _load_xlsx(data)
+ assert len(workbook._cell_styles) == 2
+ workbook.close()
+
+ def test_long_format_codes_are_refused(self):
+ guard = _guard()
+ limit = guard.MAX_XLSX_NUMBER_FORMAT_CHARS
+ assert 255 <= limit <= 1_024
+ guard.validate_zip_container(
+ _xlsx_with_styles(_stylesheet([(164, "0" * limit)], [164])),
+ ".xlsx",
+ )
+ for styles in (
+ _stylesheet([(164, "0" * (limit + 1))], [164]),
+ # Referenced or not, in any namespace.
+ _stylesheet([(170, "0" * (limit + 1))], [0], prefix="s"),
+ _stylesheet([(164, "0" * (limit + 1))], [164], namespace="urn:x"),
+ # The reported shape: one 1,000,000-character code, 2,000 xfs.
+ _stylesheet([(164, "0" * 1_000_000)], [164] * 2_000),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"longer than {limit} characters",
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+
+ @pytest.mark.parametrize(
+ "styles",
+ [
+ lambda n: _stylesheet([], [0] * n),
+ lambda n: _stylesheet([], [0], named=n, named_formats=1),
+ lambda n: _stylesheet([], [0], named=1, named_formats=n),
+ # Repeated lists are counted together.
+ lambda n: _stylesheet([], [0] * (n // 2)).replace(
+ b"</styleSheet>",
+ b"<cellXfs>"
+ + b'<xf numFmtId="0"/>' * (n - n // 2)
+ + b"</cellXfs>"
+ b"</styleSheet>",
+ ),
+ ],
+ )
+ def test_cell_format_lists_are_capped(self, styles):
+ guard = _guard()
+ assert guard.MAX_XLSX_CELL_FORMATS >= 65_490
+ with patch.object(guard, "MAX_XLSX_CELL_FORMATS", 40):
+ guard.validate_zip_container(_xlsx_with_styles(styles(39)), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="more than 40 cell"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(styles(41)), ".xlsx"
+ )
+
+ def test_number_format_work_is_priced_exactly(self):
+ guard = _guard()
+ codes = [
+ (164, "[" * 300),
+ (165, "[$-409]d/m/yy h:mm"),
+ (165, "0.00"),
+ (166, "x"),
+ ]
+ cell_formats = [164] * 7 + [165] * 3 + [0, 14, 200]
+ data = _xlsx_with_styles(_stylesheet(codes, cell_formats))
+ units = (
+ 7 * _format_units(guard, "[" * 300)
+ # A code given twice counts at the costlier entry.
+ + 3 * _format_units(guard, "[$-409]d/m/yy h:mm")
+ # Built-in or unknown formats count at 64 characters.
+ + 3 * 64 * guard.XLSX_NUMBER_FORMAT_SCAN_WEIGHT
+ )
+ with patch.object(guard, "MAX_XLSX_NUMBER_FORMAT_WORK", units):
+ guard.validate_zip_container(data, ".xlsx")
+ with patch.object(guard, "MAX_XLSX_NUMBER_FORMAT_WORK", units - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="number formats cost"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_bracket_codes_are_refused_by_default(self):
+ # One scan restarts at every unclosed "[": 4,000 cell formats of
+ # a 1,024-bracket code take about 2.3 s to load.
+ guard = _guard()
+ code = "[" * guard.MAX_XLSX_NUMBER_FORMAT_CHARS
+ assert (
+ 4_000 * _format_units(guard, code)
+ > guard.MAX_XLSX_NUMBER_FORMAT_WORK
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="number formats cost"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(_stylesheet([(164, code)], [164] * 4_000)),
+ ".xlsx",
+ )
+
+ def test_named_style_work_is_priced(self):
+ guard = _guard()
+ formats = [(164 + n, "0.0") for n in range(30)]
+ data = _xlsx_with_styles(
+ _stylesheet(formats, [0], named=25, named_formats=20)
+ )
+ # 20 distinct xfIds, each a style of the fixed work, the 30
+ # formats and the default font, fill and border (1, 2 and 1
+ # elements).
+ units = 20 * (
+ guard.XLSX_NAMED_STYLE_BASE_UNITS
+ + 30
+ + 4 * guard.XLSX_STYLE_NODE_UNITS
+ )
+ with patch.object(guard, "MAX_XLSX_NAMED_STYLE_WORK", units):
+ guard.validate_zip_container(data, ".xlsx")
+ with patch.object(guard, "MAX_XLSX_NAMED_STYLE_WORK", units - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="named styles cost"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ # 5,000 named styles over 5,000 custom formats: about 3.5 s.
+ many = [(164 + n, "0") for n in range(5_000)]
+ with pytest.raises(
+ guard.DecompressionBombError, match="named styles cost"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(
+ _stylesheet(many, [0], named=5_000, named_formats=5_000)
+ ),
+ ".xlsx",
+ )
+
+ def test_negative_xf_ids_count_as_named_styles(self):
+ # openpyxl drops a named style whose xfId repeats but indexes a
+ # negative xfId from the end, so n cellStyleXfs entries carry 2n
+ # named styles: 8,800 over 4,400 formats and 4,400 custom
+ # formats took 5.3 s to load, and were counted as 4,400.
+ guard = _guard()
+ n = 6
+ formats = [(164 + i, "0.0") for i in range(10)]
+ ids = list(range(-n, n))
+ workbook = _load_xlsx(
+ _xlsx_with_styles(
+ _stylesheet(formats, [0], named_formats=n, style_ids=ids)
+ )
+ )
+ assert len(workbook._named_styles) == 2 * n
+ workbook.close()
+ # Repeated ids are dropped, as openpyxl drops them.
+ data = _xlsx_with_styles(
+ _stylesheet(
+ formats, [0], named_formats=n, style_ids=ids + [0, -1, 5]
+ )
+ )
+ units = (
+ 2
+ * n
+ * (
+ guard.XLSX_NAMED_STYLE_BASE_UNITS
+ + len(formats)
+ + 4 * guard.XLSX_STYLE_NODE_UNITS
+ )
+ )
+ with patch.object(guard, "MAX_XLSX_NAMED_STYLE_WORK", units):
+ guard.validate_zip_container(data, ".xlsx")
+ with patch.object(guard, "MAX_XLSX_NAMED_STYLE_WORK", units - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="named styles cost"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ # The reported shape.
+ many = [(164 + i, "0") for i in range(4_400)]
+ with pytest.raises(
+ guard.DecompressionBombError, match="named styles cost"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(
+ _stylesheet(
+ many,
+ [0],
+ named_formats=4_400,
+ style_ids=list(range(-4_400, 4_400)),
+ )
+ ),
+ ".xlsx",
+ )
+
+ def test_named_styles_price_the_objects_they_bind(self):
+ # apply_stylesheet binds every named style, hashing its font,
+ # fill and border (every stop of a gradient fill) and comparing
+ # them with equal listed entries (every character of a font
+ # name): 1,000 named styles of a 1,000-stop gradient fill, an
+ # 13 KB file, took about 3 s to load, 2,000 of 2,000 stops 12.4 s.
+ guard = _guard()
+ node = guard.XLSX_STYLE_NODE_UNITS
+ # Text counts too, though openpyxl reads these from attributes.
+ fonts = (
+ '<font><name val="{}"/><sz val="11">{}</sz></font><font/>'.format(
+ "n" * 1_000, "t" * 512
+ )
+ )
+ border = (
+ '<border><left style="thin"><color indexed="64"/></left></border>'
+ )
+ data = _xlsx_with_styles(
+ _stylesheet(
+ [(164, "0" * 600), (165, "0")],
+ named=7,
+ named_formats=7,
+ fonts=fonts,
+ fills=_gradient_fill(10) + "<fill><patternFill/></fill>",
+ borders="<border/>" + border,
+ )
+ )
+ # The 2 custom formats and the longest code's 600 characters;
+ # the largest font: 3 elements and 1,514 characters; fill: 2
+ # elements and 10 stops of 2 elements and 13 characters each;
+ # border: 3 elements and 6 characters.
+ units = 7 * (
+ guard.XLSX_NAMED_STYLE_BASE_UNITS
+ + 2
+ + 600 // guard.XLSX_STYLE_CHARS_PER_UNIT
+ + (3 * node + 1_514 // guard.XLSX_STYLE_CHARS_PER_UNIT)
+ + (22 * node + 130 // guard.XLSX_STYLE_CHARS_PER_UNIT)
+ + (3 * node + 6 // guard.XLSX_STYLE_CHARS_PER_UNIT)
+ )
+ with patch.object(guard, "MAX_XLSX_NAMED_STYLE_WORK", units):
+ guard.validate_zip_container(data, ".xlsx")
+ with patch.object(guard, "MAX_XLSX_NAMED_STYLE_WORK", units - 1):
+ with pytest.raises(
+ guard.DecompressionBombError, match="named styles cost"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ # The reported shape, refused by its stops alone and by its
+ # named styles with the stop and entry ceilings lifted.
+ reported = _xlsx_with_styles(
+ _stylesheet(
+ named=1_000,
+ named_formats=1_000,
+ fills=_gradient_fill(1_000),
+ )
+ )
+ with pytest.raises(guard.DecompressionBombError, match="stops"):
+ guard.validate_zip_container(reported, ".xlsx")
+ with (
+ patch.object(guard, "MAX_XLSX_GRADIENT_STOPS", 1_000),
+ patch.object(guard, "MAX_XLSX_STYLE_ENTRY_ELEMENTS", 2_002),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="named styles cost"
+ ):
+ guard.validate_zip_container(reported, ".xlsx")
+ # 2,000 named styles of a fill at the stop ceiling load in
+ # about 1.6 s.
+ guard.validate_zip_container(
+ _xlsx_with_styles(
+ _stylesheet(
+ named=2_000,
+ named_formats=2_000,
+ fills=_gradient_fill(guard.MAX_XLSX_GRADIENT_STOPS),
+ )
+ ),
+ ".xlsx",
+ )
+
+ def test_gradient_stops_are_capped(self):
+ guard = _guard()
+ limit = guard.MAX_XLSX_GRADIENT_STOPS
+ assert 3 <= limit <= 256
+ # openpyxl reads a fill's first child as a gradient whatever
+ # its tag.
+ workbook = _load_xlsx(
+ _xlsx_with_styles(_stylesheet(fills=_gradient_fill(3, "x")))
+ )
+ assert type(workbook._fills[0]).__name__ == "GradientFill"
+ assert len(workbook._fills[0].stop) == 3
+ workbook.close()
+ guard.validate_zip_container(
+ _xlsx_with_styles(
+ _stylesheet(fills=_gradient_fill(limit) * 2, prefix="s")
+ ),
+ ".xlsx",
+ )
+ for fills in (
+ _gradient_fill(limit + 1),
+ _gradient_fill(limit + 1, "x"),
+ _gradient_fill(3) + _gradient_fill(limit + 1),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"more than {limit} stops",
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(_stylesheet(fills=fills)), ".xlsx"
+ )
+
+ def test_premise_from_tree_reads_fields_from_child_elements(self):
+ pytest.importorskip("openpyxl")
+ from openpyxl.styles.cell_style import CellStyle
+ from openpyxl.styles.named_styles import _NamedCellStyle
+
+ guard = _guard()
+ base = _stylesheet([(164, "0")], [0])
+ workbook = _load_xlsx(
+ _xlsx_with_styles(
+ base.replace(
+ b'formatCode="0"/>',
+ b'formatCode="0"><formatCode>0.000</formatCode></numFmt>',
+ ).replace(
+ b'xfId="0"/></cellXfs>',
+ b'xfId="0"><numFmtId>164</numFmtId></xf></cellXfs>',
+ )
+ )
+ )
+ assert list(workbook._number_formats) == ["0.000"]
+ assert workbook._cell_styles[0].numFmtId == 164
+ workbook.close()
+ assert guard._xlsx_text_fields(CellStyle) == {
+ "numFmtId",
+ "fontId",
+ "fillId",
+ "borderId",
+ "xfId",
+ "quotePrefix",
+ "pivotButton",
+ "applyNumberFormat",
+ "applyFont",
+ "applyFill",
+ "applyBorder",
+ }
+ assert guard._xlsx_text_fields(_NamedCellStyle) == {
+ "name",
+ "xfId",
+ "builtinId",
+ "iLevel",
+ "hidden",
+ "customBuiltin",
+ }
+
+ @pytest.mark.parametrize(
+ "old, new",
+ [
+ # A format code given as a child's text: one 1,000,000-
+ # character code under 2,000 cell formats, a 1,881-byte
+ # file, took 52 s to load.
+ (
+ b'formatCode="0"/>',
+ b'formatCode="0"><formatCode>LONG</formatCode></numFmt>',
+ ),
+ (
+ b'formatCode="0"/>',
+ b'formatCode="0"><x:formatCode xmlns:x="urn:x">LONG'
+ b"</x:formatCode></numFmt>",
+ ),
+ (
+ b'formatCode="0"/>',
+ b'formatCode="0"><numFmtId>165</numFmtId></numFmt>',
+ ),
+ (b'formatCode="0"/>', b'formatCode="0"><foo/></numFmt>'),
+ # A cell format's format id, a named style's format's font
+ # id, a named style's xfId.
+ (
+ b'xfId="0"/></cellXfs>',
+ b'xfId="0"><numFmtId>164</numFmtId></xf></cellXfs>',
+ ),
+ (
+ b'borderId="0"/></cellStyleXfs>',
+ b'borderId="0"><fontId>0</fontId></xf></cellStyleXfs>',
+ ),
+ (
+ b'xfId="0"/></cellStyles>',
+ b'xfId="0"><xfId>0</xfId></cellStyle></cellStyles>',
+ ),
+ ],
+ )
+ def test_fields_given_as_child_elements_are_refused(self, old, new):
+ guard = _guard()
+ base = _stylesheet([(164, "0")], [164] * 2_000)
+ assert old in base
+ styles = base.replace(old, new.replace(b"LONG", b"0" * 1_000_000))
+ with pytest.raises(guard.DecompressionBombError, match="child element"):
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+
+ def test_child_elements_excel_writes_pass(self):
+ guard = _guard()
+ children = (
+ b'<alignment horizontal="center" wrapText="1"/>'
+ b'<protection locked="0"/><extLst><ext uri="urn:x"/></extLst>'
+ b"<foo/>"
+ )
+ styles = (
+ _stylesheet([(164, "0")], [164], style_format=children.decode())
+ .replace(
+ b'xfId="0"/></cellXfs>',
+ b'xfId="0">' + children + b"</xf></cellXfs>",
+ )
+ .replace(
+ b'xfId="0"/></cellStyles>',
+ b'xfId="0"><extLst><ext uri="urn:x"/></extLst>'
+ b"</cellStyle></cellStyles>",
+ )
+ )
+ data = _xlsx_with_styles(styles)
+ workbook = _load_xlsx(data)
+ assert workbook._alignments[1].horizontal == "center"
+ workbook.close()
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_unloadable_ids_and_dtds_are_refused(self):
+ guard = _guard()
+ bad = _stylesheet([(164, "0")], [164]).replace(
+ b'numFmtId="164" formatCode', b'numFmtId="x" formatCode'
+ )
+ with pytest.raises((TypeError, ValueError)):
+ _load_xlsx(_xlsx_with_styles(bad))
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(_xlsx_with_styles(bad), ".xlsx")
+ with_dtd = b"<!DOCTYPE styleSheet>" + _stylesheet([(164, "0")], [164])
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(_xlsx_with_styles(with_dtd), ".xlsx")
+
+ def test_ordinary_workbooks_pass(self):
+ guard = _guard()
+ openpyxl = pytest.importorskip("openpyxl")
+ workbook = openpyxl.Workbook()
+ sheet = workbook.active
+ for row in range(1, 301):
+ cell = sheet.cell(row=row, column=1, value=row)
+ cell.number_format = f'[$-409]#,##0.{"0" * (row % 9)}" u{row}"'
+ workbook.add_named_style(openpyxl.styles.NamedStyle(name="extra"))
+ buf = io.BytesIO()
+ workbook.save(buf)
+ guard.validate_zip_container(buf.getvalue(), ".xlsx")
+ # Excel's limits: 65,490 cell formats of an ordinary date code.
+ limit = guard.MAX_XLSX_CELL_FORMATS
+ code = "[$-409]d/m/yy\\ h:mm;@"
+ guard.validate_zip_container(
+ _xlsx_with_styles(_stylesheet([(164, code)], [164] * limit)),
+ ".xlsx",
+ )
+ # No styles part at all is fine too.
+ data = _real_package(".xlsx")
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ kept = {
+ n: zf.read(n) for n in zf.namelist() if n != "xl/styles.xml"
+ }
+ guard.validate_zip_container(_zip_bytes(kept), ".xlsx")
+
+ def test_style_defaults(self):
+ guard = _guard()
+ assert guard.MAX_XLSX_NUMBER_FORMAT_WORK <= 4_000_000_000
+ assert guard.MAX_XLSX_NAMED_STYLE_WORK <= 20_000_000
+ assert guard.MAX_XLSX_GRADIENT_STOPS <= 256
+ assert guard.XLSX_NAMED_STYLE_BASE_UNITS >= 500
+ assert guard.XLSX_STYLE_NODE_UNITS >= 10
+ assert guard.XLSX_STYLE_CHARS_PER_UNIT <= 1_024
+ assert guard.MAX_XLSX_STYLE_LIST_ENTRIES <= 16_384
+ assert guard.MAX_XLSX_STYLE_HASH_CHAIN <= 8
+ assert guard.XLSX_STYLE_INT_MAX < 2**61 - 1
+ assert guard.XLSX_STYLE_INT_MIN > -(2**61 - 1)
+ assert guard.MAX_XLSX_STYLE_FLOAT <= 2**53
+
+
+_HASH_MODULUS = 2**61 - 1
+
+
+def _one_hash_floats(count: int) -> list[str]:
+ """*count* distinct floats of one hash: Python hashes ``x`` and
+ ``x * 2**-61`` alike."""
+ return [repr(2.0 ** (-61 * n)) for n in range(count)]
+
+
+def _cell_formats(entries: list[str]) -> bytes:
+ """A stylesheet with *entries* appended to its ``cellXfs``."""
+ return _stylesheet().replace(
+ b"</cellXfs>", "".join(entries).encode() + b"</cellXfs>"
+ )
+
+
+class TestXlsxStyleHashCollisions:
+ # openpyxl keeps fonts, fills, borders, alignments, protections and
+ # cell formats in IndexedLists (dicts keyed by the style object,
+ # whose hash is taken over its field values) and adds each named
+ # style's objects to them again. Distinct objects of one hash are
+ # compared with each other on every insertion and lookup: 4,000
+ # fonts differing only in a charset of 1 + k * (2**61 - 1) took
+ # 6.6 s to load (51 KB), 8,000 of them under 8,000 named styles 81 s.
+
+ def test_premise_distinct_style_objects_share_a_hash(self):
+ pytest.importorskip("openpyxl")
+ import inspect
+
+ from openpyxl.styles import stylesheet
+ from openpyxl.styles.cell_style import CellStyleList
+ from openpyxl.styles.fonts import Font
+ from openpyxl.utils.indexed_list import IndexedList
+
+ fonts = [Font(charset=1 + n * _HASH_MODULUS) for n in range(3)]
+ assert len({hash(font) for font in fonts}) == 1
+ assert fonts[0] != fonts[1] != fonts[2] != fonts[0]
+ floats = [Font(sz=float(x)) for x in _one_hash_floats(3)]
+ assert len({hash(font) for font in floats}) == 1
+ assert floats[0] != floats[1] != floats[2] != floats[0]
+ assert "IndexedList(stylesheet.fonts)" in inspect.getsource(
+ stylesheet.apply_stylesheet
+ )
+ assert "IndexedList(" in inspect.getsource(CellStyleList._to_array)
+ assert "self._dict[val] = idx" in inspect.getsource(IndexedList)
+
+ @pytest.mark.parametrize(
+ "styles",
+ [
+ # The reported shape: fonts of one charset hash.
+ lambda v: _stylesheet(
+ fonts=f'<font><charset val="{1 + _HASH_MODULUS}"/></font>'
+ ),
+ # Ids the guard and openpyxl key dicts by.
+ lambda v: _stylesheet([(164 + _HASH_MODULUS, "0.0")], [164]),
+ lambda v: _stylesheet(style_ids=[_HASH_MODULUS]),
+ # A child element's text and a float attribute.
+ lambda v: _stylesheet(
+ fonts=f"<font><color><theme>{2**32}</theme></color></font>"
+ ),
+ lambda v: _stylesheet(
+ fills=f'<fill><gradientFill degree="{v}"/></fill>'
+ ),
+ lambda v: _stylesheet(fonts=f'<font><sz val="{v}"/></font>'),
+ # A child's text is read even when the child has children.
+ lambda v: _stylesheet(
+ fills="<fill><gradientFill>"
+ f"<degree>{v}<x/></degree></gradientFill></fill>"
+ ),
+ ],
+ ids=[
+ "charset",
+ "numFmtId",
+ "xfId",
+ "theme-text",
+ "degree",
+ "sz",
+ "degree-text-before-a-child",
+ ],
+ )
+ def test_out_of_range_style_numbers_are_refused(self, styles):
+ guard = _guard()
+ for value in ("1e300", "nan", "-inf", str(2**33)):
+ with pytest.raises(
+ guard.DecompressionBombError, match="out of range"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(styles(value)), ".xlsx"
+ )
+
+ def test_style_numbers_in_range_pass(self):
+ guard = _guard()
+ styles = _stylesheet(
+ fonts=(
+ f'<font><charset val="{guard.XLSX_STYLE_INT_MAX}"/>'
+ '<sz val="409"/><color indexed="64" tint="-0.249977111117893"/>'
+ "</font>"
+ f'<font><charset val="{guard.XLSX_STYLE_INT_MIN}"/></font>'
+ ),
+ fills='<fill><gradientFill degree="90"><stop position="0">'
+ '<color theme="1"/></stop></gradientFill></fill>',
+ )
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+ _load_xlsx(_xlsx_with_styles(styles)).close()
+
+ @pytest.mark.parametrize(
+ "what, styles",
+ [
+ (
+ "fonts",
+ lambda values: _stylesheet(
+ fonts="".join(
+ f'<font><sz val="{v}"/></font>' for v in values
+ )
+ ),
+ ),
+ (
+ "fills",
+ lambda values: _stylesheet(
+ fills="".join(
+ f'<fill><gradientFill degree="{v}"/></fill>'
+ for v in values
+ )
+ ),
+ ),
+ (
+ "borders",
+ lambda values: _stylesheet(
+ borders="".join(
+ f'<border><left style="thin"><color tint="{v}"/>'
+ "</left></border>"
+ for v in values
+ )
+ ),
+ ),
+ (
+ "alignments",
+ lambda values: _cell_formats(
+ [
+ f'<xf numFmtId="0"><alignment indent="{v}"/></xf>'
+ for v in values
+ ]
+ ),
+ ),
+ # Each named style's format adds its alignment as it binds.
+ (
+ "alignments",
+ lambda values: _stylesheet(
+ named=len(values) + 1,
+ style_ids=list(range(len(values) + 1)),
+ ).replace(
+ b"</cellStyleXfs>",
+ "".join(
+ f'<xf numFmtId="0"><alignment indent="{v}"/></xf>'
+ for v in values
+ ).encode()
+ + b"</cellStyleXfs>",
+ ),
+ ),
+ # Any tag in the fonts list is a font, in any namespace.
+ (
+ "fonts",
+ lambda values: _stylesheet(
+ fonts="".join(
+ f'<x:f xmlns:x="urn:x"><x:sz val="{v}"/></x:f>'
+ for v in values
+ )
+ ),
+ ),
+ ],
+ )
+ def test_distinct_style_objects_of_one_hash_are_refused(self, what, styles):
+ guard = _guard()
+ limit = guard.MAX_XLSX_STYLE_HASH_CHAIN
+ values = _one_hash_floats(limit + 1)
+ guard.validate_zip_container(
+ _xlsx_with_styles(styles(values[:limit])), ".xlsx"
+ )
+ # Equal entries, however often repeated or however spelled, are
+ # one value.
+ respelled = [f"+{v}" for v in values[:limit]]
+ guard.validate_zip_container(
+ _xlsx_with_styles(styles((values[:limit] + respelled) * 50)),
+ ".xlsx",
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match=f"distinct {what} of one hash"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(styles(values)), ".xlsx"
+ )
+
+ def test_cell_formats_of_one_hash_are_refused(self, monkeypatch):
+ # Free 32-bit fields of a cell format's style array can be
+ # steered to one tuple hash; a constant hash stands in for that.
+ pytest.importorskip("openpyxl")
+ from openpyxl.styles.cell_style import StyleArray
+
+ guard = _guard()
+ limit = guard.MAX_XLSX_STYLE_HASH_CHAIN
+ styles = _cell_formats(
+ [f'<xf numFmtId="0" fontId="{n + 1}"/>' for n in range(limit)]
+ )
+ monkeypatch.setattr(StyleArray, "__hash__", lambda self: 7)
+ with pytest.raises(
+ guard.DecompressionBombError, match="distinct cell formats"
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+ monkeypatch.undo()
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+
+ @pytest.mark.parametrize(
+ "container, entry",
+ [
+ ("fonts", "<font><sz val='{n}'/></font>"),
+ ("fills", "<fill><gradientFill degree='{n}'/></fill>"),
+ (
+ "borders",
+ "<border><left style='thin'><color indexed='{n}'/></left></border>",
+ ),
+ ],
+ )
+ def test_style_lists_are_capped(self, container, entry):
+ guard = _guard()
+ limit = guard.MAX_XLSX_STYLE_LIST_ENTRIES
+ assert limit >= 512 # Excel's own font limit per workbook
+
+ def styles(count: int, lists: int = 1) -> bytes:
+ per_list = count // lists
+ body = "".join(entry.format(n=n) for n in range(per_list))
+ return _stylesheet(**{container: body}).replace(
+ f"<{container}>".encode(),
+ (f"<{container}>{body}</{container}>" * (lists - 1)).encode()
+ + f"<{container}>".encode(),
+ 1,
+ )
+
+ guard.validate_zip_container(_xlsx_with_styles(styles(limit)), ".xlsx")
+ for over in (styles(limit + 1), styles(limit + 2, lists=2)):
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"more than {limit} {container} entries",
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(over), ".xlsx")
+
+
+def _before_root(xml: bytes, nodes: bytes) -> bytes:
+ """*xml* with *nodes* inserted before its root element (after its
+ XML declaration, if any)."""
+ at = xml.index(b"?>") + 2 if xml.startswith(b"<?xml") else 0
+ return xml[:at] + nodes + xml[at:]
+
+
+_XLSX_LIST_SITES = {
+ # NestedSequence lists: openpyxl builds an entry per child node.
+ "fonts": ("<fonts><font/>", "<fonts><font/>{node}"),
+ "fills": (
+ "<fills><fill><patternFill/></fill>",
+ "<fills><fill><patternFill/></fill>{node}",
+ ),
+ "borders": ("<borders><border/>", "<borders><border/>{node}"),
+ "dxfs": ("</styleSheet>", "<dxfs><dxf/>{node}</dxfs></styleSheet>"),
+ "indexedColors": (
+ "</styleSheet>",
+ "<colors><indexedColors><rgbColor rgb='FF000000'/>{node}"
+ "</indexedColors></colors></styleSheet>",
+ ),
+ "mruColors": (
+ "</styleSheet>",
+ "<colors><mruColors><color rgb='FF000000'/>{node}</mruColors>"
+ "</colors></styleSheet>",
+ ),
+ # Sequence lists and single entries, which openpyxl skips them in.
+ "numFmts": ("<numFmts>", "<numFmts>{node}"),
+ "cellStyleXfs": ("<cellStyleXfs>", "<cellStyleXfs>{node}"),
+ "cellXfs": ("<cellXfs>", "<cellXfs>{node}"),
+ "cellStyles": ("<cellStyles>", "<cellStyles>{node}"),
+ "tableStyles": (
+ "</styleSheet>",
+ "<tableStyles count='0'>{node}</tableStyles></styleSheet>",
+ ),
+ "font": ("<fonts><font/>", "<fonts><font>{node}</font>"),
+ "fill": (
+ "<fills><fill><patternFill/></fill>",
+ "<fills><fill><patternFill/>{node}</fill>",
+ ),
+ "gradientFill": (
+ "<fills><fill><patternFill/></fill>",
+ "<fills><fill><patternFill/></fill><fill><gradientFill>"
+ "<stop position='0'><color rgb='FF000000'/></stop>{node}"
+ "</gradientFill></fill>",
+ ),
+ "xf": ('xfId="0"/>', 'xfId="0">{node}</xf>'),
+}
+
+
+class TestXmlCommentsAndProcessingInstructions:
+ # openpyxl parses xl/styles.xml and the workbook skeleton with lxml,
+ # which keeps comments and processing instructions as nodes, and
+ # NestedSequence builds an entry per child node: 2,000,000 empty
+ # comments after one font, a 25 KB file the guard accepted (it
+ # counted elements), took openpyxl 37 s and 960 MB to load as
+ # 2,000,001 fonts.
+
+ def test_premise_openpyxl_builds_an_entry_per_child_node(self):
+ import inspect
+
+ pytest.importorskip("lxml")
+ pytest.importorskip("openpyxl")
+ from openpyxl import xml as openpyxl_xml
+ from openpyxl.descriptors.sequence import NestedSequence
+
+ assert openpyxl_xml.LXML
+ source = inspect.getsource(NestedSequence.from_tree)
+ assert "for el in node" in source
+ for node in ("<!---->", "<?p?>"):
+ for site, expected in (
+ ("fonts", lambda wb: len(wb._fonts)),
+ ("borders", lambda wb: len(wb._borders)),
+ ("dxfs", lambda wb: len(wb._differential_styles.styles)),
+ ):
+ old, new = _XLSX_LIST_SITES[site]
+ styles = _stylesheet().replace(
+ old.encode(), new.format(node=node * 3).encode(), 1
+ )
+ workbook = _load_xlsx(_xlsx_with_styles(styles))
+ assert expected(workbook) == 4, (site, node)
+ workbook.close()
+ # Where openpyxl skips them (between the lists), nothing is built.
+ workbook = _load_xlsx(
+ _xlsx_with_styles(
+ _stylesheet().replace(b"<fills>", b"<!----><?p?><fills>", 1)
+ )
+ )
+ assert len(workbook._fonts) == 1
+ workbook.close()
+
+ @pytest.mark.parametrize("node", ["<!---->", "<?p?>"])
+ @pytest.mark.parametrize("site", sorted(_XLSX_LIST_SITES))
+ def test_styles_comment_below_the_top_level_is_refused(self, site, node):
+ guard = _guard()
+ old, new = _XLSX_LIST_SITES[site]
+ base = _stylesheet()
+ assert base.count(old.encode()) >= 1, site
+ control = base.replace(old.encode(), new.format(node="").encode(), 1)
+ guard.validate_zip_container(_xlsx_with_styles(control), ".xlsx")
+ styles = base.replace(old.encode(), new.format(node=node).encode(), 1)
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match="comment or processing instruction below its top level",
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+
+ def test_reported_shape_is_refused_quickly(self):
+ guard = _guard()
+ styles = _stylesheet(fonts="<font/>" + "<!---->" * 2_000_000)
+ data = _xlsx_with_styles(styles)
+ assert len(data) < 64 * 1024
+ start = time.perf_counter()
+ with pytest.raises(
+ guard.DecompressionBombError, match="below its top level"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ @pytest.mark.parametrize("node", ["<!--c-->", "<?p x?>"])
+ def test_styles_comment_at_the_top_level_is_accepted(self, node):
+ """Between the lists, before and after the root: openpyxl skips
+ them, at the cost of a tree node each."""
+ guard = _guard()
+ styles = _before_root(
+ b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
+ + _stylesheet()
+ .replace(b"<fills>", f"{node}<fills>".encode(), 1)
+ .replace(b"</styleSheet>", f"{node}</styleSheet>".encode())
+ + node.encode(),
+ node.encode(),
+ )
+ data = _xlsx_with_styles(styles)
+ guard.validate_zip_container(data, ".xlsx")
+ workbook = _load_xlsx(data)
+ assert len(workbook._fonts) == 1
+ workbook.close()
+
+ @pytest.mark.parametrize("node", ["<!---->", "<?p?>"])
+ @pytest.mark.parametrize(
+ "part, old, new",
+ [
+ # NestedSequence lists of the workbook.
+ ("xl/workbook.xml", "<bookViews>", "<bookViews>{node}"),
+ ("xl/workbook.xml", "<sheets>", "<sheets>{node}"),
+ # Elsewhere below the root's children.
+ (
+ "xl/workbook.xml",
+ "<definedNames/>",
+ "<definedNames>{node}</definedNames>",
+ ),
+ ("xl/workbook.xml", 'r:id="rId1"/>', 'r:id="rId1">{node}</sheet>'),
+ ("[Content_Types].xml", "/>", ">{node}</Default>"),
+ (
+ "xl/_rels/workbook.xml.rels",
+ 'Id="rId1"/>',
+ 'Id="rId1">{node}</Relationship>',
+ ),
+ ],
+ )
+ def test_skeleton_comment_below_the_top_level_is_refused(
+ self, part, old, new, node
+ ):
+ guard = _guard()
+ base = _real_package(".xlsx")
+
+ def rewrite(fill: str) -> bytes:
+ def change(xml: bytes) -> bytes:
+ assert old.encode() in xml, (part, old)
+ return xml.replace(
+ old.encode(), new.format(node=fill).encode(), 1
+ )
+
+ return _rewrite_zip(base, {part: change})
+
+ guard.validate_zip_container(rewrite(""), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match="workbook skeleton part has a comment or processing",
+ ):
+ guard.validate_zip_container(rewrite(node), ".xlsx")
+
+ def test_reported_workbook_shape_is_refused_quickly(self):
+ # 2,390,000 comments among the bookViews of a 16 MiB workbook
+ # part took the guard's own openpyxl parse 19.6 s and 1.1 GB.
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "xl/workbook.xml": lambda xml: xml.replace(
+ b"<bookViews>", b"<bookViews>" + b"<!---->" * 200_000, 1
+ )
+ },
+ )
+ start = time.perf_counter()
+ with pytest.raises(
+ guard.DecompressionBombError, match="below its top level"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ @pytest.mark.parametrize("node", ["<!--c-->", "<?p x?>"])
+ def test_skeleton_comment_at_the_top_level_is_accepted(self, node):
+ guard = _guard()
+ top = node.encode()
+ data = _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ part: lambda xml, root=root: _before_root(
+ xml.replace(root, top + root, 1) + top, top
+ )
+ for part, root in (
+ ("xl/workbook.xml", b"<sheets>"),
+ ("[Content_Types].xml", b"<Default "),
+ )
+ },
+ )
+ guard.validate_zip_container(data, ".xlsx")
+ workbook = _load_xlsx(data)
+ assert workbook.sheetnames == ["Sheet"]
+ workbook.close()
+ # The relationships list is read as every child node of the
+ # root (ElementList), so there openpyxl itself drops the whole
+ # list and cannot find the sheets; the guard, which runs
+ # openpyxl's reader, refuses it as malformed.
+ rels = _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "xl/_rels/workbook.xml.rels": lambda xml: xml.replace(
+ b"<Relationship ", top + b"<Relationship ", 1
+ )
+ },
+ )
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(rels, ".xlsx")
+ with pytest.raises(KeyError):
+ _load_xlsx(rels)
+
+ @pytest.mark.parametrize(
+ "ext, part",
+ [
+ (".xlsx", "xl/styles.xml"),
+ (".pptx", "ppt/slides/slide1.xml"),
+ (".docx", "word/header1.xml"),
+ (".docx", "word/document.xml"),
+ ],
+ )
+ def test_nodes_outside_the_root_are_capped(self, ext, part):
+ """lxml's iterparse emits the comment event for a node before
+ the root in time linear in the nodes before it: 60,000 empty
+ comments before a slide's root, a 420 KB part, kept the guard
+ busy for 16.7 s."""
+ guard = _guard()
+ limit = guard.MAX_XML_OUTSIDE_ROOT_NODES
+ assert limit <= 1_024
+ base = {
+ ".xlsx": lambda: _xlsx_with_styles(_stylesheet()),
+ ".pptx": lambda: _deck(1),
+ ".docx": lambda: _docx_with_sections(1),
+ }[ext]()
+
+ def padded(before: int, after: int = 0) -> bytes:
+ return _rewrite_zip(
+ base,
+ {
+ part: lambda xml: (
+ _before_root(xml, b"<!---->" * before)
+ + b"<?p?>" * after
+ )
+ },
+ )
+
+ guard.validate_zip_container(padded(limit), ext)
+ guard.validate_zip_container(padded(limit - 1, 1), ext)
+ for over in (padded(limit + 1), padded(limit, 1)):
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"more than {limit} comments or processing",
+ ):
+ guard.validate_zip_container(over, ext)
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(padded(200_000), ext)
+ assert time.perf_counter() - start < 5
+
+
+def _xlsx_with_workbook(change) -> bytes:
+ """An openpyxl-written workbook whose ``xl/workbook.xml`` is passed
+ through *change* (bytes to bytes)."""
+ return _rewrite_zip(_real_package(".xlsx"), {"xl/workbook.xml": change})
+
+
+_R_DECL = (
+ b' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/'
+ b'relationships"'
+)
+
+
+def _workbook_lists(xml: bytes, lists: bytes) -> bytes:
+ """*xml* (a workbook part) with *lists* before its ``definedNames``
+ and the relationships namespace declared on its root."""
+ xml = xml.replace(b"<workbook ", b"<workbook" + _R_DECL + b" ", 1)
+ return xml.replace(b"<definedNames/>", lists + b"<definedNames/>", 1)
+
+
+# (constant, list entries as a function of a count, list name)
+_STYLE_LIST_CASES = {
+ "numFmts": (
+ "MAX_XLSX_NUMBER_FORMATS",
+ lambda n: _stylesheet([(164 + k, "0") for k in range(n)]),
+ ),
+ "dxfs": (
+ "MAX_XLSX_DIFFERENTIAL_FORMATS",
+ lambda n: _stylesheet().replace(
+ b"</styleSheet>",
+ b"<dxfs>" + b"<dxf/>" * (n - n // 2) + b"</dxfs>"
+ b"<dxfs>" + b"<dxf/>" * (n // 2) + b"</dxfs></styleSheet>",
+ ),
+ ),
+ "tableStyles": (
+ "MAX_XLSX_TABLE_STYLES",
+ lambda n: _stylesheet().replace(
+ b"</styleSheet>",
+ b"<tableStyles>"
+ + b"".join(b"<tableStyle name='t%d'/>" % k for k in range(n))
+ + b"</tableStyles></styleSheet>",
+ ),
+ ),
+ "tableStyle": (
+ "MAX_XLSX_TABLE_STYLE_ELEMENTS",
+ lambda n: _stylesheet().replace(
+ b"</styleSheet>",
+ b"<tableStyles><tableStyle name='t'>"
+ + b"<tableStyleElement type='wholeTable'/>" * n
+ + b"</tableStyle></tableStyles></styleSheet>",
+ ),
+ ),
+ "indexedColors": (
+ "MAX_XLSX_COLOR_LIST_ENTRIES",
+ lambda n: _stylesheet().replace(
+ b"</styleSheet>",
+ b"<colors><indexedColors>"
+ + b"<rgbColor rgb='FF000000'/>" * n
+ + b"</indexedColors></colors></styleSheet>",
+ ),
+ ),
+ "mruColors": (
+ "MAX_XLSX_COLOR_LIST_ENTRIES",
+ lambda n: _stylesheet().replace(
+ b"</styleSheet>",
+ b"<colors><mruColors>"
+ + b"<color rgb='FF000000'/>" * n
+ + b"</mruColors></colors></styleSheet>",
+ ),
+ ),
+ "extLst": (
+ "MAX_XLSX_EXTENSIONS",
+ # Counted over every extension list of the part.
+ lambda n: (
+ _stylesheet(
+ cell_formats=[0, 0],
+ )
+ .replace(
+ b'xfId="0"/>',
+ b'xfId="0"><extLst>'
+ + b"<ext uri='u'/>" * (n // 2)
+ + b"</extLst></xf>",
+ 1,
+ )
+ .replace(
+ b"</styleSheet>",
+ b"<extLst>"
+ + b"<ext uri='u'/>" * (n - n // 2)
+ + b"</extLst></styleSheet>",
+ )
+ ),
+ ),
+ "cellXfs": (
+ # Every child of a cell-format list counts, not only <xf>.
+ "MAX_XLSX_CELL_FORMATS",
+ lambda n: _stylesheet().replace(
+ b"<cellXfs>", b"<cellXfs>" + b"<x/>" * (n - 1), 1
+ ),
+ ),
+}
+
+
+class TestXlsxListCeilings:
+ # openpyxl builds an object from every entry of every list of the
+ # stylesheet and of the workbook part, and from every child it knows
+ # of every other element, keeping only the last of a repeated one:
+ # 500,000 <font/> in one dxf, a 10 KB file, took 7.4 s to load, and
+ # 1,800,000 <calcPr/> in a 16 MiB workbook part 17 s, in the guard's
+ # own parse as long again.
+
+ def test_premise_every_list_openpyxl_builds_is_covered(self):
+ """The list-valued fields openpyxl reads from the stylesheet and
+ the workbook part, walked from its classes: an upgrade adding
+ one fails here until the guard counts it."""
+ pytest.importorskip("openpyxl")
+ from openpyxl.descriptors import Descriptor
+ from openpyxl.descriptors.sequence import Sequence
+ from openpyxl.descriptors.serialisable import Serialisable
+ from openpyxl.packaging.workbook import WorkbookPackage
+ from openpyxl.styles.stylesheet import Stylesheet
+
+ def lists(root) -> set:
+ found, seen, pending = set(), set(), [root]
+ while pending:
+ cls = pending.pop()
+ if cls in seen:
+ continue
+ seen.add(cls)
+ pending.extend(cls.__subclasses__())
+ for name in dir(cls):
+ desc = getattr(cls, name, None)
+ if not isinstance(desc, Descriptor):
+ continue
+ if isinstance(desc, Sequence):
+ found.add(f"{cls.__name__}.{name}")
+ kind = getattr(desc, "expected_type", None)
+ if isinstance(kind, type) and issubclass(
+ kind, Serialisable
+ ):
+ pending.append(kind)
+ return found
+
+ # Each with the guard's bound: its list (by the container's
+ # name), or, for stops, MAX_XLSX_GRADIENT_STOPS(_TOTAL).
+ assert lists(Stylesheet) == {
+ "Stylesheet.fonts", # fonts
+ "Stylesheet.fills", # fills
+ "Stylesheet.borders", # borders
+ "Stylesheet.dxfs", # dxfs
+ "NumberFormatList.numFmt", # numFmts
+ "CellStyleList.xf", # cellXfs, cellStyleXfs
+ # (their other children; openpyxl fails to load these)
+ "CellStyleList.alignment",
+ "CellStyleList.protection",
+ "_NamedCellStyleList.cellStyle", # cellStyles
+ "TableStyleList.tableStyle", # tableStyles
+ "TableStyle.tableStyleElement", # tableStyle
+ "ColorList.indexedColors", # indexedColors
+ "ColorList.mruColors", # mruColors
+ "GradientFill.stop", # gradient stops
+ "ExtensionList.ext", # extLst
+ }
+ guard = _guard()
+ covered = set(guard._XLSX_WORKBOOK_LISTS)
+ assert lists(WorkbookPackage) == {
+ "WorkbookPackage.bookViews",
+ "WorkbookPackage.sheets",
+ "WorkbookPackage.customWorkbookViews",
+ "WorkbookPackage.externalReferences",
+ "WorkbookPackage.pivotCaches",
+ "SmartTagList.smartTagType",
+ "FunctionGroupList.functionGroup",
+ "WebPublishObjectList.webPublishObject",
+ # (count: the part's 16 MiB ceiling; each value, and the
+ # print titles and areas: _check_xlsx_defined_names)
+ "DefinedNameList.definedName",
+ "ExtensionList.ext",
+ }
+ assert covered == {
+ "bookViews",
+ "sheets",
+ "customWorkbookViews",
+ "externalReferences",
+ "pivotCaches",
+ "smartTagTypes",
+ "functionGroups",
+ "webPublishObjects",
+ }
+ assert set(guard._XLSX_STYLE_LISTS) | set(guard._XLSX_COLOR_LISTS) == {
+ "numFmts",
+ "fonts",
+ "fills",
+ "borders",
+ "cellStyleXfs",
+ "cellXfs",
+ "cellStyles",
+ "dxfs",
+ "tableStyles",
+ "indexedColors",
+ "mruColors",
+ }
+
+ def test_premise_openpyxl_builds_every_entry_and_repeat(self):
+ pytest.importorskip("openpyxl")
+ styles = _stylesheet().replace(
+ b"</styleSheet>",
+ b"<dxfs>"
+ + b"<dxf><font/><font><b/></font></dxf>" * 3
+ + b"</dxfs></styleSheet>",
+ )
+ workbook = _load_xlsx(_xlsx_with_styles(styles))
+ dxfs = workbook._differential_styles.styles
+ assert len(dxfs) == 3
+ # The repeated font was built and replaced by the last one.
+ assert all(dxf.font.b for dxf in dxfs)
+ workbook.close()
+
+ @pytest.mark.parametrize("name", sorted(_STYLE_LIST_CASES))
+ def test_style_list_accepts_its_cap_and_refuses_one_more(
+ self, name, monkeypatch
+ ):
+ guard = _guard()
+ constant, styles = _STYLE_LIST_CASES[name]
+ monkeypatch.setattr(guard, constant, 6)
+ guard.validate_zip_container(_xlsx_with_styles(styles(6)), ".xlsx")
+ _load_xlsx(_xlsx_with_styles(styles(6))).close()
+ with pytest.raises(
+ guard.DecompressionBombError, match=f"more than 6 {name} entries"
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles(7)), ".xlsx")
+
+ def test_differential_format_elements_are_capped(self, monkeypatch):
+ guard = _guard()
+ monkeypatch.setattr(guard, "MAX_XLSX_DIFFERENTIAL_FORMAT_ELEMENTS", 9)
+
+ def styles(dxfs: int) -> bytes:
+ # Each <dxf> is three elements.
+ return _stylesheet().replace(
+ b"</styleSheet>",
+ b"<dxfs>"
+ + b"<dxf><font><b/></font></dxf>" * dxfs
+ + b"</dxfs></styleSheet>",
+ )
+
+ guard.validate_zip_container(_xlsx_with_styles(styles(3)), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="more than 9 elements"
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles(4)), ".xlsx")
+
+ def test_gradient_stops_are_capped_together(self, monkeypatch):
+ guard = _guard()
+ monkeypatch.setattr(guard, "MAX_XLSX_GRADIENT_STOPS_TOTAL", 10)
+
+ def styles(in_fills: int, in_dxf: int) -> bytes:
+ return _stylesheet(
+ fills=_gradient_fill(in_fills - in_fills // 2)
+ + _gradient_fill(in_fills // 2)
+ ).replace(
+ b"</styleSheet>",
+ b"<dxfs><dxf>"
+ + _gradient_fill(in_dxf).encode()
+ + b"</dxf></dxfs></styleSheet>",
+ )
+
+ guard.validate_zip_container(_xlsx_with_styles(styles(6, 4)), ".xlsx")
+ _load_xlsx(_xlsx_with_styles(styles(6, 4))).close()
+ for over in (styles(6, 5), styles(11, 0)):
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match="more than 10 stops together",
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(over), ".xlsx")
+ # One gradient in a differential format is held like one in fills.
+ monkeypatch.undo()
+ limit = guard.MAX_XLSX_GRADIENT_STOPS
+ with pytest.raises(
+ guard.DecompressionBombError, match=f"more than {limit} stops"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(styles(0, limit + 1)), ".xlsx"
+ )
+
+ def test_top_level_elements_are_capped(self, monkeypatch):
+ from lxml import etree
+
+ guard = _guard()
+ base = _stylesheet()
+ top = len(etree.fromstring(base))
+ monkeypatch.setattr(guard, "MAX_XLSX_TOP_LEVEL_ELEMENTS", top + 3)
+
+ def styles(extra: int) -> bytes:
+ return base.replace(
+ b"</styleSheet>", b"<colors/>" * extra + b"</styleSheet>"
+ )
+
+ guard.validate_zip_container(_xlsx_with_styles(styles(3)), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"styles part has more than {top + 3} top-level",
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles(4)), ".xlsx")
+
+ @pytest.mark.parametrize(
+ "old, new",
+ [
+ ("<fonts><font/>", "<fonts><font><b/><b/></font>"),
+ (
+ "<fonts><font/>",
+ "<fonts><font><color rgb='FF000000'/><color/></font>",
+ ),
+ (
+ 'xfId="0"/>',
+ 'xfId="0"><alignment/><alignment horizontal="left"/></xf>',
+ ),
+ (
+ "<fills><fill><patternFill/></fill>",
+ "<fills><fill><patternFill><fgColor/><fgColor/></patternFill></fill>",
+ ),
+ ("<borders><border/>", "<borders><border><left/><left/></border>"),
+ (
+ "</styleSheet>",
+ "<dxfs><dxf><font/><font/></dxf></dxfs></styleSheet>",
+ ),
+ (
+ "</styleSheet>",
+ "<colors><mruColors/><mruColors/></colors></styleSheet>",
+ ),
+ (
+ "</styleSheet>",
+ "<dxfs><dxf><fill><gradientFill><stop position='0'/>"
+ "<bottom/><bottom/></gradientFill></fill></dxf></dxfs>"
+ "</styleSheet>",
+ ),
+ ],
+ )
+ def test_repeated_child_of_an_entry_is_refused(self, old, new):
+ guard = _guard()
+ base = _stylesheet()
+ assert old.encode() in base
+ styles = base.replace(old.encode(), new.encode(), 1)
+ with pytest.raises(
+ guard.DecompressionBombError, match="repeats its .* child"
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+
+ def test_reported_repeat_shapes_are_refused_quickly(self):
+ guard = _guard()
+ for styles in (
+ _stylesheet().replace(
+ b"</styleSheet>",
+ b"<dxfs><dxf>"
+ + b"<font/>" * 500_000
+ + b"</dxf></dxfs></styleSheet>",
+ ),
+ _stylesheet().replace(
+ b"</styleSheet>", b"<colors/>" * 500_000 + b"</styleSheet>"
+ ),
+ ):
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_excel_like_lists_and_extensions_pass(self):
+ """Excel's own shapes: repeated children inside an extension
+ (which openpyxl does not read), several stops in a gradient, a
+ table style of several elements and differential formats with a
+ font, fill and border each."""
+ guard = _guard()
+ styles = _stylesheet(
+ fills="<fill><patternFill/></fill>" + _gradient_fill(3)
+ ).replace(
+ b"</styleSheet>",
+ b"<dxfs><dxf><font><b/><color rgb='FF9C0006'/></font><fill>"
+ b"<patternFill><bgColor rgb='FFFFC7CE'/></patternFill></fill>"
+ b"<border><left/><right/></border></dxf><dxf><font><i/></font>"
+ b"</dxf></dxfs><tableStyles count='1'><tableStyle name='t'>"
+ b"<tableStyleElement type='wholeTable' dxfId='0'/>"
+ b"<tableStyleElement type='headerRow' dxfId='1'/></tableStyle>"
+ b"</tableStyles><colors><mruColors><color rgb='FF00B050'/>"
+ b"<color rgb='FF0070C0'/></mruColors></colors><extLst>"
+ b"<ext uri='{EB79DEF2-80B8-43e5-95BD-54CBDDF9F1E1}' "
+ b"xmlns:x14='urn:x14'><x14:slicerStyles><x14:slicerStyle "
+ b"name='a'/><x14:slicerStyle name='b'/></x14:slicerStyles>"
+ b"</ext><ext uri='u2'/></extLst></styleSheet>",
+ )
+ data = _xlsx_with_styles(styles)
+ guard.validate_zip_container(data, ".xlsx")
+ workbook = _load_xlsx(data)
+ assert len(workbook._differential_styles.styles) == 2
+ workbook.close()
+
+ @pytest.mark.parametrize(
+ "name, entry",
+ [
+ ("bookViews", "<workbookView/>"),
+ ("customWorkbookViews", "<customWorkbookView/>"),
+ ("externalReferences", "<externalReference/>"),
+ ("pivotCaches", "<pivotCache/>"),
+ ("smartTagTypes", "<smartTagType/>"),
+ ("functionGroups", "<functionGroup/>"),
+ ("webPublishObjects", "<webPublishObject/>"),
+ ("extLst", "<ext uri='u'/>"),
+ ],
+ )
+ def test_workbook_list_accepts_its_cap_and_refuses_one_more(
+ self, name, entry, monkeypatch
+ ):
+ guard = _guard()
+ constant = (
+ "MAX_XLSX_EXTENSIONS"
+ if name == "extLst"
+ else "MAX_XLSX_WORKBOOK_LIST_ENTRIES"
+ )
+ monkeypatch.setattr(guard, constant, 6)
+ from lxml import etree
+
+ with zipfile.ZipFile(io.BytesIO(_real_package(".xlsx"))) as archive:
+ root = etree.fromstring(archive.read("xl/workbook.xml"))
+ listed = sum(len(c) for c in root if etree.QName(c).localname == name)
+
+ def workbook(count: int) -> bytes:
+ # Over two lists of that name, beside those openpyxl writes.
+ count -= listed
+ body = "".join(
+ f"<{name}>{entry * n}</{name}>"
+ for n in (count - count // 2, count // 2)
+ ).encode()
+ return _xlsx_with_workbook(lambda xml: _workbook_lists(xml, body))
+
+ # The guard's own workbook checks (openpyxl may fail to load
+ # these placeholder entries later; that is refused as malformed).
+ with pytest.raises(
+ guard.DecompressionBombError, match=f"more than 6 {name} entries"
+ ):
+ guard.validate_zip_container(workbook(7), ".xlsx")
+ try:
+ guard.validate_zip_container(workbook(6), ".xlsx")
+ except guard.DecompressionBombError as exc:
+ assert str(exc) == "malformed spreadsheet package", exc
+
+ def test_sheets_without_ids_count_towards_the_sheet_cap(self, monkeypatch):
+ guard = _guard()
+ monkeypatch.setattr(guard, "MAX_XLSX_SHEETS", 5)
+
+ def workbook(extra: int) -> bytes:
+ return _xlsx_with_workbook(
+ lambda xml: xml.replace(
+ b"</sheets>",
+ b"".join(
+ b"<sheet name='n%d' sheetId='%d'/>" % (k, k + 2)
+ for k in range(extra)
+ )
+ + b"</sheets>",
+ 1,
+ )
+ )
+
+ guard.validate_zip_container(workbook(4), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="more than 5 sheets"
+ ):
+ guard.validate_zip_container(workbook(5), ".xlsx")
+
+ def test_workbook_top_level_and_repeats(self, monkeypatch):
+ guard = _guard()
+ base = _real_package(".xlsx")
+ with zipfile.ZipFile(io.BytesIO(base)) as archive:
+ xml = archive.read("xl/workbook.xml")
+ from lxml import etree
+
+ with zipfile.ZipFile(io.BytesIO(base)) as archive:
+ styles_top = len(etree.fromstring(archive.read("xl/styles.xml")))
+ top = len(etree.fromstring(xml))
+ # The cap is shared with the styles part, which must stay under it.
+ cap = max(top, styles_top) + 2
+ monkeypatch.setattr(guard, "MAX_XLSX_TOP_LEVEL_ELEMENTS", cap)
+
+ def extra(count: int) -> bytes:
+ return _xlsx_with_workbook(
+ lambda x: x.replace(
+ b"</workbook>", b"<calcPr/>" * count + b"</workbook>"
+ )
+ )
+
+ # Repeated top-level elements are allowed up to the cap.
+ guard.validate_zip_container(extra(cap - top), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match=f"workbook part has more than {cap} top-level",
+ ):
+ guard.validate_zip_container(extra(cap - top + 1), ".xlsx")
+ monkeypatch.undo()
+ for change in (
+ # A repeated child of a list entry, or of a top-level element.
+ lambda x: x.replace(
+ b"<workbookView ",
+ b"<workbookView><extLst/><extLst/></workbookView><workbookView ",
+ 1,
+ ),
+ lambda x: x.replace(
+ b"<workbookPr/>", b"<workbookPr><a/><a/></workbookPr>", 1
+ ),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="repeats its .* child"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_workbook(change), ".xlsx"
+ )
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(extra(1_000_000), ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_excel_like_workbook_passes(self):
+ """Excel writes repeated children inside its calculation-feature
+ extension, which openpyxl does not read."""
+ guard = _guard()
+ data = _xlsx_with_workbook(
+ lambda xml: xml.replace(
+ b"</workbook>",
+ b"<extLst><ext uri='{140A7094-0E35-4892-8432-C4D2E57EDEB5}'"
+ b" xmlns:x15='urn:x15'><x15:workbookPr chartTrackingRefBase='1'/>"
+ b"</ext><ext uri='{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}' "
+ b"xmlns:xcalcf='urn:xcalcf'><xcalcf:calcFeatures>"
+ b"<xcalcf:feature name='microsoft.com:RD'/>"
+ b"<xcalcf:feature name='microsoft.com:Single'/>"
+ b"</xcalcf:calcFeatures></ext></extLst></workbook>",
+ )
+ )
+ guard.validate_zip_container(data, ".xlsx")
+ workbook = _load_xlsx(data)
+ assert workbook.sheetnames == ["Sheet"]
+ workbook.close()
+
+ def test_new_ceilings_are_generous_and_pinned(self):
+ guard = _guard()
+ assert guard.MAX_XLSX_NUMBER_FORMATS >= 250 # Excel's own limit
+ assert (
+ guard.MAX_XLSX_DIFFERENTIAL_FORMATS == guard.MAX_XLSX_CELL_FORMATS
+ )
+ assert guard.MAX_XLSX_COLOR_LIST_ENTRIES >= 64 # Excel's palette
+ assert guard.MAX_XLSX_TABLE_STYLE_ELEMENTS >= 28 # table parts
+ assert guard.MAX_XLSX_TABLE_STYLES >= 1_024
+ assert guard.MAX_XLSX_EXTENSIONS >= 2 * guard.MAX_XLSX_CELL_FORMATS
+ assert guard.MAX_XLSX_WORKBOOK_LIST_ENTRIES >= 1_024
+ assert guard.MAX_XLSX_TOP_LEVEL_ELEMENTS >= 64
+ assert guard.MAX_XLSX_GRADIENT_STOPS_TOTAL >= 256 * 256
+ assert guard.MAX_XLSX_DIFFERENTIAL_FORMAT_ELEMENTS <= 500_000
+
+ def test_document_with_a_comment_before_its_root_is_read(self):
+ """One comment before document.xml's root (a generator's note)
+ is outside python-docx's tree, and the guard accepts it."""
+ docx = pytest.importorskip("docx")
+ guard = _guard()
+ base = docx.Document()
+ base.add_paragraph("hello")
+ buf = io.BytesIO()
+ base.save(buf)
+ data = _rewrite_zip(
+ buf.getvalue(),
+ {"word/document.xml": lambda xml: _before_root(xml, b"<!--g-->")},
+ )
+ guard.validate_zip_container(data, ".docx")
+ assert [p.text for p in docx.Document(io.BytesIO(data)).paragraphs] == [
+ "hello"
+ ]
+
+
+def _with_defined_names(entries: str) -> bytes:
+ """An openpyxl-written workbook with *entries* as its defined names."""
+ return _xlsx_with_workbook(
+ lambda xml: xml.replace(
+ b"<definedNames/>",
+ b"<definedNames>" + entries.encode() + b"</definedNames>",
+ 1,
+ )
+ )
+
+
+def _defined_name(name: str, value: str, sheet: int | None = 0) -> str:
+ local = "" if sheet is None else f' localSheetId="{sheet}"'
+ return f'<definedName name="{name}"{local}>{value}</definedName>'
+
+
+def _stops(count: int) -> str:
+ return "".join(
+ f'<stop position="{n / max(count, 1):.6f}"><color rgb="FF000000"/></stop>'
+ for n in range(count)
+ )
+
+
+def _with_sheet_names(*names: str) -> bytes:
+ """An openpyxl-written workbook of one sheet per name (each with its
+ part), the names written into the workbook part as given."""
+ openpyxl = pytest.importorskip("openpyxl")
+ workbook = openpyxl.Workbook()
+ workbook.active.title = "s0"
+ for n in range(1, len(names)):
+ workbook.create_sheet(f"s{n}")
+ buf = io.BytesIO()
+ workbook.save(buf)
+
+ def rename(xml: bytes) -> bytes:
+ for n, name in enumerate(names):
+ xml = xml.replace(
+ f'name="s{n}"'.encode(), f'name="{name}"'.encode(), 1
+ )
+ return xml
+
+ return _rewrite_zip(buf.getvalue(), {"xl/workbook.xml": rename})
+
+
+def _with_sheet_root(change) -> bytes:
+ """An openpyxl-written workbook whose first worksheet's root start
+ tag (bytes up to its ``>``) is passed through *change*."""
+
+ def sheet(xml: bytes) -> bytes:
+ start = xml.index(b"<worksheet")
+ end = xml.index(b">", start)
+ return xml[:start] + change(xml[start:end]) + xml[end:]
+
+ return _rewrite_zip(
+ _real_package(".xlsx"), {"xl/worksheets/sheet1.xml": sheet}
+ )
+
+
+class TestXlsxReadPathStringWork:
+ # Text openpyxl's read path (pandas' read-only load) processes in
+ # time worse than linear in its length: the print titles and print
+ # areas among the defined names (regular expressions, quadratic),
+ # sheet names (compared with every other name), and namespace URIs
+ # (copied into every element name lxml hands back). Every other
+ # regular expression on that path is anchored or bounded and runs in
+ # linear time.
+
+ def test_premise_print_names_are_parsed_on_every_load(self):
+ import inspect
+
+ pytest.importorskip("openpyxl")
+ from openpyxl.reader.excel import ExcelReader
+ from openpyxl.reader.workbook import WorkbookParser
+ from openpyxl.workbook.defined_name import DefinedName
+ from openpyxl.worksheet.print_settings import PrintArea
+
+ assert "assign_names()" in inspect.getsource(ExcelReader.read)
+ source = inspect.getsource(WorkbookParser.assign_names)
+ assert "PrintTitles.from_string(defn.value)" in source
+ assert "PrintArea.from_string(defn.value)" in source
+ # The reserved names are matched as a prefix.
+ assert DefinedName(name="_xlnm.Print_AreaZ").is_reserved == "Print_Area"
+ # So one sheet's distinct spellings are each parsed.
+ data = _with_defined_names(
+ _defined_name("_xlnm.Print_Area", "s!$A$1:$B$2")
+ + _defined_name("_xlnm.Print_AreaZ", "s!$A$1:$B$3")
+ )
+ calls: list = []
+ real = PrintArea.from_string.__func__
+
+ def spy(cls, value):
+ calls.append(value)
+ return real(cls, value)
+
+ with patch.object(PrintArea, "from_string", classmethod(spy)):
+ _load_xlsx(data).close()
+ assert sorted(calls) == ["s!$A$1:$B$2", "s!$A$1:$B$3"]
+
+ def test_premise_print_name_parse_is_quadratic(self):
+ pytest.importorskip("openpyxl")
+ from openpyxl.worksheet.print_settings import PRINT_AREA_RE
+
+ def cost(length: int) -> float:
+ best = math.inf
+ for _ in range(3):
+ start = time.perf_counter()
+ list(PRINT_AREA_RE.finditer("'" * length))
+ best = min(best, time.perf_counter() - start)
+ return best
+
+ # Four times the length, about sixteen times the time.
+ assert cost(4_000) > 6 * cost(1_000)
+
+ def test_defined_name_value_is_capped(self):
+ guard = _guard()
+ guard.validate_zip_container(
+ _with_defined_names(_defined_name("n", "1" * 8_192, None)),
+ ".xlsx",
+ )
+ for entry in (
+ _defined_name("n", "1" * 8_193, None),
+ # A child's text, which openpyxl reads in place of a field.
+ f'<definedName name="n"><comment>{"1" * 8_193}</comment>'
+ "</definedName>",
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="longer than 8192"
+ ):
+ guard.validate_zip_container(
+ _with_defined_names(entry), ".xlsx"
+ )
+
+ def test_premise_from_tree_reads_the_value_from_an_attribute(self):
+ pytest.importorskip("openpyxl")
+ from lxml import etree
+ from openpyxl.workbook.defined_name import DefinedName
+
+ for attribute in ("attr_text", "attr-text"):
+ node = etree.fromstring(
+ f'<definedName name="n" {attribute}="Sheet!$A$1"/>'
+ )
+ assert DefinedName.from_tree(node).value == "Sheet!$A$1"
+ # Text, when there is any, replaces the attribute.
+ node = etree.fromstring(
+ '<definedName name="n" attr_text="a">Sheet!$A$1</definedName>'
+ )
+ assert DefinedName.from_tree(node).value == "Sheet!$A$1"
+
+ @pytest.mark.parametrize("attribute", ["attr_text", "attr-text"])
+ @pytest.mark.parametrize(
+ "name", ["_xlnm.Print_Area", "_xlnm.Print_Titles", "n"]
+ )
+ def test_defined_name_value_in_an_attribute_is_measured(
+ self, name, attribute
+ ):
+ guard = _guard()
+
+ def entry(length: int) -> str:
+ return (
+ f'<definedName name="{name}" localSheetId="0" '
+ f'{attribute}="{"#" * length}"/>'
+ )
+
+ guard.validate_zip_container(_with_defined_names(entry(100)), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="longer than 8192"
+ ):
+ guard.validate_zip_container(
+ _with_defined_names(entry(8_193)), ".xlsx"
+ )
+
+ def test_print_names_in_attributes_are_priced(self, monkeypatch):
+ guard = _guard()
+ base = guard.XLSX_PRINT_NAME_BASE_UNITS
+ monkeypatch.setattr(
+ guard, "MAX_XLSX_PRINT_NAME_WORK", 2 * (100**2 + base)
+ )
+ value = "#" * 100
+ names = (
+ f'<definedName name="_xlnm.Print_Area" localSheetId="0" '
+ f'attr_text="{value}"/>'
+ )
+ guard.validate_zip_container(
+ _with_defined_names(names + names.replace("Area", "Titles")),
+ ".xlsx",
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="print areas and titles"
+ ):
+ guard.validate_zip_container(
+ _with_defined_names(
+ names
+ + names.replace("Area", "Titles")
+ + names.replace("Area", "Area2")
+ ),
+ ".xlsx",
+ )
+
+ def test_reported_attribute_print_name_shape_is_refused_quickly(self):
+ guard = _guard()
+ for name in ("_xlnm.Print_Titles", "_xlnm.Print_Area"):
+ data = _with_defined_names(
+ f'<definedName name="{name}" localSheetId="0" '
+ f'attr_text="{"#" * 40_000}"/>'
+ )
+ assert len(data) < 8_000
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_reported_print_name_shapes_are_refused_quickly(self):
+ guard = _guard()
+ for name in ("_xlnm.Print_Titles", "_xlnm.Print_Area"):
+ data = _with_defined_names(_defined_name(name, "#" * 40_000))
+ assert len(data) < 8_000
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_print_names_are_priced_together(self, monkeypatch):
+ guard = _guard()
+ base = guard.XLSX_PRINT_NAME_BASE_UNITS
+ monkeypatch.setattr(
+ guard, "MAX_XLSX_PRINT_NAME_WORK", 3 * (100**2 + base)
+ )
+ value = "#" * 100
+ names = (
+ _defined_name("_xlnm.Print_Area", value)
+ + _defined_name("_xlnm.Print_Titles", value, 1)
+ # Spelled through a child element, which openpyxl reads in
+ # place of the attribute.
+ + f'<definedName localSheetId="0">{value}'
+ "<name>_xlnm.Print_AreaZ</name></definedName>"
+ # Other names are not parsed and not counted.
+ + _defined_name("n", "#" * 8_000) * 20
+ )
+ guard.validate_zip_container(_with_defined_names(names), ".xlsx")
+ for extra in (
+ _defined_name("_xlnm.Print_Area2", value),
+ _defined_name("_xlnm.Print_Titles", "#", 3),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="print areas and titles"
+ ):
+ guard.validate_zip_container(
+ _with_defined_names(names + extra), ".xlsx"
+ )
+
+ def test_print_name_at_the_length_ceiling_is_accepted(self):
+ guard = _guard()
+ limit = guard.MAX_XLSX_DEFINED_NAME_CHARS
+ assert guard.MAX_XLSX_PRINT_NAME_WORK == (
+ limit**2 + guard.XLSX_PRINT_NAME_BASE_UNITS
+ )
+ guard.validate_zip_container(
+ _with_defined_names(_defined_name("_xlnm.Print_Area", "'" * limit)),
+ ".xlsx",
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="print areas and titles"
+ ):
+ guard.validate_zip_container(
+ _with_defined_names(
+ _defined_name("_xlnm.Print_Area", "'" * limit)
+ + _defined_name("_xlnm.Print_Titles", "")
+ ),
+ ".xlsx",
+ )
+
+ def test_excel_like_print_names_pass(self):
+ guard = _guard()
+ data = _with_defined_names(
+ _defined_name("_xlnm.Print_Area", "Sheet!$A$1:$H$50")
+ + _defined_name("_xlnm.Print_Titles", "Sheet!$1:$2,Sheet!$A:$A")
+ + _defined_name("Rates", "Sheet!$B$2:$B$9", None)
+ )
+ guard.validate_zip_container(data, ".xlsx")
+ workbook = _load_xlsx(data)
+ assert workbook.sheetnames == ["Sheet"]
+ workbook.close()
+
+ def test_premise_chartsheets_are_renamed_by_a_search_of_every_name(self):
+ import inspect
+
+ pytest.importorskip("openpyxl")
+ from openpyxl.workbook.child import avoid_duplicate_name
+
+ source = inspect.getsource(avoid_duplicate_name)
+ assert "n.lower() == value.lower()" in source
+ assert '",".join(names)' in source and "findall" in source
+
+ def test_sheet_name_length_is_capped(self):
+ guard = _guard()
+ guard.validate_zip_container(_with_sheet_names("a" * 255), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="longer than 255"
+ ):
+ guard.validate_zip_container(_with_sheet_names("a" * 256), ".xlsx")
+
+ def test_sheets_of_one_name_are_refused(self):
+ guard = _guard()
+ guard.validate_zip_container(
+ _with_sheet_names("Data", "Data2"), ".xlsx"
+ )
+ for data in (
+ _with_sheet_names("Data", "DATA"),
+ _with_sheet_names("Straße", "STRASSE".lower().replace("ss", "ß")),
+ # A sheet without a relationship counts too.
+ _xlsx_with_workbook(
+ lambda xml: xml.replace(
+ b"</sheets>", b'<sheet name="sheet" sheetId="9"/></sheets>'
+ )
+ ),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="two sheets of one name"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_premise_lxml_copies_the_uri_into_every_name(self):
+ from lxml import etree
+
+ uri = "urn:" + "a" * 100
+ root = etree.fromstring(f'<r xmlns:q="{uri}"><q:z/><q:z/></r>')
+ first, second = (child.tag for child in root)
+ assert first == second == "{%s}z" % uri
+ assert first is not second # built anew on every read
+
+ def test_long_namespace_uri_is_refused_in_any_part_openpyxl_parses(self):
+ guard = _guard()
+
+ def declared(length: int):
+ uri = ("urn:" + "a" * length)[:length]
+ return f' xmlns:q="{uri}"'.encode()
+
+ guard.validate_zip_container(
+ _with_sheet_root(lambda tag: tag + declared(1_024)), ".xlsx"
+ )
+ for data in (
+ _with_sheet_root(lambda tag: tag + declared(1_025)),
+ # Declared deeper, in a part openpyxl reads only on load.
+ _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "xl/worksheets/sheet1.xml": lambda xml: xml.replace(
+ b"</worksheet>",
+ b"<q:x" + declared(1_025) + b"/></worksheet>",
+ )
+ },
+ ),
+ # The document properties openpyxl parses with lxml.
+ _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "docProps/core.xml": lambda xml: xml.replace(
+ b"<cp:coreProperties ",
+ b"<cp:coreProperties" + declared(1_025) + b" ",
+ 1,
+ )
+ },
+ ),
+ ):
+ with pytest.raises(
+ guard.DecompressionBombError, match="namespace URI"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ # docProps/app.xml is never parsed (not by openpyxl, pandas,
+ # unstructured or msoffcrypto), so it is not scanned.
+ guard.validate_zip_container(
+ _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "docProps/app.xml": lambda xml: xml.replace(
+ b"<Properties ",
+ b"<Properties" + declared(1_025) + b" ",
+ 1,
+ )
+ },
+ ),
+ ".xlsx",
+ )
+
+ def test_reported_namespace_shape_is_refused_quickly(self):
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "xl/worksheets/sheet1.xml": lambda xml: xml.replace(
+ b"<worksheet ",
+ b'<worksheet xmlns:q="urn:' + b"a" * 1_000_000 + b'" ',
+ 1,
+ ).replace(b"</worksheet>", b"<q:z/>" * 2_000 + b"</worksheet>")
+ },
+ )
+ assert len(data) < 10_000
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError, match="namespace"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_premise_libxml2_stops_where_expat_reads_on(self):
+ from lxml import etree
+
+ # openpyxl's iterparse when defusedxml is installed (expat).
+ defused = pytest.importorskip("defusedxml.ElementTree")
+
+ for document in (
+ b"<r><" + b"n" * 50_001 + b"/></r>",
+ b'<r a="' + b"v" * 10_500_000 + b'"/>',
+ b"<r><!--" + b"c" * 10_500_000 + b"--></r>",
+ ):
+ with pytest.raises(etree.XMLSyntaxError):
+ etree.fromstring(document)
+ # openpyxl reads worksheets and shared strings this way.
+ list(defused.iterparse(io.BytesIO(document)))
+
+ @pytest.mark.parametrize(
+ "lead",
+ [
+ b"<" + b"n" * 50_001 + b"/>",
+ b'<lead a="' + b"v" * 10_500_000 + b'"/>',
+ b"<!--" + b"c" * 10_500_000 + b"-->",
+ ],
+ ids=["long-name", "long-attribute", "long-comment"],
+ )
+ def test_uri_after_what_only_expat_reads_is_refused(self, lead):
+ """openpyxl's expat parse of a worksheet reads on past markup
+ where libxml2 stops, so a declaration after it is checked."""
+ guard = _guard()
+
+ def sheet(uri_chars: int, elements: int):
+ uri = b"urn:" + b"a" * (uri_chars - 4)
+ tail = (
+ lead
+ + b'<q:w xmlns:q="'
+ + uri
+ + b'">'
+ + b"<q:z/>" * elements
+ + b"</q:w></worksheet>"
+ )
+ return _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "xl/worksheets/sheet1.xml": lambda xml: xml.replace(
+ b"</worksheet>", tail
+ )
+ },
+ )
+
+ guard.validate_zip_container(sheet(1_024, 10), ".xlsx")
+ with pytest.raises(guard.DecompressionBombError, match="namespace"):
+ guard.validate_zip_container(sheet(1_025, 10), ".xlsx")
+ # The reported shape: a 1,000,000-character URI used 40,000
+ # times.
+ data = sheet(1_000_000, 40_000)
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError, match="namespace"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_dtd_in_a_worksheet_is_refused(self):
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(".xlsx"),
+ {
+ "xl/worksheets/sheet1.xml": lambda xml: xml.replace(
+ b"<worksheet ", b"<!DOCTYPE worksheet><worksheet ", 1
+ )
+ },
+ )
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_namespace_scan_reads_each_parsed_member_once(self):
+ """The scan streams each part openpyxl's load parses once, with
+ that load's parser family, and nothing else (the theme, whose
+ bytes openpyxl keeps unparsed, the package relationships,
+ ``docProps/app.xml``, media)."""
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(".xlsx"), add={"xl/media/image1.png": _small_png()}
+ )
+ scanned: list = []
+ real_scan = guard._scan_xlsx_part
+
+ def spy(archive, info, families):
+ scanned.append((info.filename, families))
+ return real_scan(archive, info, families)
+
+ opened: list = []
+ real_open = zipfile.ZipFile.open
+
+ def open_spy(self, name, *args, **kwargs):
+ opened.append(
+ name.filename if isinstance(name, zipfile.ZipInfo) else name
+ )
+ return real_open(self, name, *args, **kwargs)
+
+ with (
+ patch.object(guard, "_scan_xlsx_part", spy),
+ patch.object(zipfile.ZipFile, "open", open_spy),
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ lxml, expat = guard._LXML, guard._EXPAT
+ assert sorted(scanned) == sorted(
+ [
+ ("[Content_Types].xml", frozenset({lxml, expat})),
+ ("xl/workbook.xml", frozenset({lxml})),
+ ("xl/_rels/workbook.xml.rels", frozenset({lxml})),
+ ("docProps/core.xml", frozenset({lxml})),
+ ("xl/styles.xml", frozenset({lxml})),
+ ("xl/worksheets/sheet1.xml", frozenset({expat})),
+ ]
+ )
+ for name in (
+ "xl/theme/theme1.xml",
+ "_rels/.rels",
+ "docProps/app.xml",
+ "xl/media/image1.png",
+ ):
+ assert name not in opened
+
+ def test_premise_an_extension_list_entry_is_read_as_a_fill(self):
+ """openpyxl reads every child of ``fills`` as a fill, and a
+ fill's first child as a gradient unless it is a pattern, so an
+ ``extLst`` there is not an extension list."""
+ pytest.importorskip("openpyxl")
+ for fills in (
+ "<fill><patternFill/></fill><extLst><ext>"
+ + _stops(5)
+ + "</ext></extLst>",
+ "<fill><patternFill/></fill><fill><extLst>"
+ + _stops(5)
+ + "</extLst></fill>",
+ ):
+ workbook = _load_xlsx(_xlsx_with_styles(_stylesheet(fills=fills)))
+ assert [len(fill.stop) for fill in workbook._fills[1:]] == [5]
+ workbook.close()
+
+ @pytest.mark.parametrize(
+ "fills, dxfs",
+ [
+ ("<fill><patternFill/></fill><extLst><ext>{}</ext></extLst>", ""),
+ ("<fill><patternFill/></fill><fill><extLst>{}</extLst></fill>", ""),
+ (
+ "<fill><patternFill/></fill>",
+ "<dxfs><dxf><fill><extLst>{}</extLst></fill></dxf></dxfs>",
+ ),
+ ],
+ )
+ def test_gradient_stops_under_an_extension_tag_are_counted(
+ self, fills, dxfs
+ ):
+ guard = _guard()
+
+ def styles(stops: int) -> bytes:
+ return _stylesheet(fills=fills.format(_stops(stops))).replace(
+ b"</styleSheet>",
+ dxfs.format(_stops(stops)).encode() + b"</styleSheet>",
+ )
+
+ guard.validate_zip_container(_xlsx_with_styles(styles(256)), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="more than 256 stops"
+ ):
+ guard.validate_zip_container(
+ _xlsx_with_styles(styles(257)), ".xlsx"
+ )
+
+ def test_reported_extension_stop_shape_is_refused_quickly(self):
+ guard = _guard()
+ data = _xlsx_with_styles(
+ _stylesheet(
+ fills="<fill><patternFill/></fill><extLst><ext>"
+ + _stops(40_000)
+ + "</ext></extLst>"
+ )
+ )
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError, match="stops"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ @pytest.mark.parametrize(
+ "old, new, held",
+ [
+ (
+ "<fills><fill><patternFill/></fill>",
+ "<fills><fill><patternFill/><extLst><ext>{}</ext></extLst>"
+ "</fill>",
+ 4,
+ ),
+ (
+ 'xfId="0"/>',
+ 'xfId="0"><extLst><ext uri="u">{}</ext></extLst></xf>',
+ 3,
+ ),
+ ("<fonts><font/>", "<fonts><font>{}</font>", 1),
+ ],
+ )
+ def test_style_entry_elements_are_capped(self, old, new, held, monkeypatch):
+ """*held* elements besides the filler: the entry and the
+ elements around the filler."""
+ guard = _guard()
+ base = _stylesheet()
+ assert old.encode() in base
+
+ def styles(elements: int) -> bytes:
+ # Distinct names: a repeat would be refused on its own.
+ filler = "".join(f"<x{n}/>" for n in range(elements - held))
+ return base.replace(old.encode(), new.format(filler).encode(), 1)
+
+ monkeypatch.setattr(guard, "MAX_XLSX_STYLE_ENTRY_ELEMENTS", 12)
+ guard.validate_zip_container(_xlsx_with_styles(styles(12)), ".xlsx")
+ with pytest.raises(
+ guard.DecompressionBombError, match="entry has more than 12"
+ ):
+ guard.validate_zip_container(_xlsx_with_styles(styles(13)), ".xlsx")
+
+ def test_large_style_entry_is_refused_quickly(self):
+ guard = _guard()
+ data = _xlsx_with_styles(
+ _stylesheet(
+ fills="<fill><patternFill/><extLst><ext uri='u'>"
+ + "<x/>" * 80_000
+ + "</ext></extLst></fill>"
+ )
+ )
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError, match="elements"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_excel_cell_format_extensions_pass(self):
+ guard = _guard()
+ styles = _stylesheet().replace(
+ b'xfId="0"/>',
+ b'xfId="0"><alignment horizontal="left"/><protection locked="0"/>'
+ b'<extLst><ext uri="{C7286773-470A-42A8-94C5-96B5CB345126}" '
+ b'xmlns:xfpb="urn:xfpb"><xfpb:xfComplement i="0"/></ext>'
+ b"</extLst></xf>",
+ 1,
+ )
+ guard.validate_zip_container(_xlsx_with_styles(styles), ".xlsx")
+
+ def test_new_ceilings_are_pinned(self):
+ guard = _guard()
+ assert guard.MAX_XLSX_DEFINED_NAME_CHARS == 8_192 # Excel's limit
+ assert guard.MAX_XLSX_SHEET_NAME_CHARS >= 100 # Google Sheets
+ assert guard.MAX_XLSX_NAMESPACE_URI_CHARS == 1_024
+ assert (
+ guard.MAX_XLSX_STYLE_ENTRY_ELEMENTS
+ >= 2 * guard.MAX_XLSX_GRADIENT_STOPS + 2
+ )
+
+
+def _with_part(name: str, change) -> bytes:
+ """An openpyxl-written workbook with member *name* passed through
+ *change*."""
+ return _rewrite_zip(_real_package(".xlsx"), {name: change})
+
+
+def _reencoded(
+ xml: bytes, codec: str, declared: str, bom: bytes = b""
+) -> bytes:
+ """*xml* (UTF-8, with or without a declaration) re-encoded in
+ *codec* under a declaration naming *declared*."""
+ text = xml.decode("utf-8")
+ if text.startswith("<?xml"):
+ text = text[text.index("?>") + 2 :]
+ declaration = f'<?xml version="1.0" encoding="{declared}"?>'
+ return bom + (declaration + text).encode(codec)
+
+
+def _without_declaration(xml: bytes) -> bytes:
+ """*xml* without its XML declaration, if it has one."""
+ if xml.startswith(b"<?xml"):
+ xml = xml[xml.index(b"?>") + 2 :]
+ return xml.lstrip(b"\r\n")
+
+
+def _utf16_lt_names(count: int) -> list[str]:
+ """*count* distinct attribute names of three CJK ideographs or
+ Hangul syllables each, every one with a UTF-16 low byte of ``3C``
+ (a ``<`` byte in either byte order)."""
+ letters = [
+ chr(c)
+ for c in [*range(0x4E3C, 0x9FA5, 0x100), *range(0xAC3C, 0xD7A3, 0x100)]
+ ]
+ names = []
+ for first in letters:
+ for second in letters:
+ for third in letters:
+ names.append(first + second + third)
+ if len(names) == count:
+ return names
+ raise AssertionError("not enough names")
+
+
+def _utf16_leading_space(xml: str, codec: str) -> bytes:
+ """*xml* in UTF-16 (*codec*), no byte-order mark, after a space."""
+ return (" " + xml).encode(codec)
+
+
+def _declared_utf16le(xml: str) -> bytes:
+ """An ASCII declaration naming ``UTF-16LE``, then *xml* in UTF-16LE
+ (the declaration's ``?>`` included)."""
+ return b'<?xml version="1.0" encoding="UTF-16LE"' + ("?>" + xml).encode(
+ "utf-16-le"
+ )
+
+
+def _with_shared_strings(xml: bytes) -> bytes:
+ """An openpyxl-written workbook with *xml* as its shared strings
+ part ``xl/sharedStrings.xml``."""
+
+ def types(ct: bytes) -> bytes:
+ return ct.replace(
+ b"</Types>",
+ b'<Override PartName="/xl/sharedStrings.xml" ContentType='
+ b'"application/vnd.openxmlformats-officedocument.'
+ b'spreadsheetml.sharedStrings+xml"/></Types>',
+ )
+
+ return _rewrite_zip(
+ _real_package(".xlsx"),
+ {"[Content_Types].xml": types},
+ add={"xl/sharedStrings.xml": xml},
+ )
+
+
+def _long_uri_core(elements: int, uri_chars: int = 1_000_000) -> str:
+ return (
+ "<cp:coreProperties xmlns:cp="
+ '"http://schemas.openxmlformats.org/package/2006/metadata/'
+ 'core-properties" xmlns:q="urn:'
+ + "a" * uri_chars
+ + '">'
+ + "<q:z/>" * elements
+ + "</cp:coreProperties>"
+ )
+
+
+def _long_uri_custom(elements: int, uri_chars: int = 1_000_000) -> str:
+ return (
+ "<Properties xmlns="
+ '"http://schemas.openxmlformats.org/officeDocument/2006/'
+ 'custom-properties" xmlns:q="urn:'
+ + "a" * uri_chars
+ + '">'
+ + "<q:z/>" * elements
+ + "</Properties>"
+ )
+
+
+def _with_custom_properties(xml: bytes) -> bytes:
+ def types(ct: bytes) -> bytes:
+ return ct.replace(
+ b"</Types>",
+ b'<Override PartName="/docProps/custom.xml" ContentType='
+ b'"application/vnd.openxmlformats-officedocument.custom-'
+ b'properties+xml"/></Types>',
+ )
+
+ return _rewrite_zip(
+ _real_package(".xlsx"),
+ {"[Content_Types].xml": types},
+ add={"docProps/custom.xml": xml},
+ )
+
+
+_SVG_WITH_DOCTYPE = (
+ b'<?xml version="1.0" encoding="UTF-8"?>\n'
+ b'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
+ b'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'
+ b'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="2" '
+ b'height="2"><rect width="2" height="2"/></svg>'
+)
+
+
+class TestXlsxScanFollowsTheLoaders:
+ """The namespace scan covers exactly the parts openpyxl's read-only
+ load (and msoffcrypto) parses, each with the parser that load uses
+ for it, and refuses encodings, nesting and start tags the loaders'
+ parsers handle differently or without a bound."""
+
+ def test_premise_lxml_reads_utf32_from_a_buffer_only(self):
+ """openpyxl parses the document properties with lxml
+ ``fromstring``, which decodes UTF-32 with a byte-order mark;
+ lxml's push parser and expat reject it at the first byte."""
+ from lxml import etree
+ from xml.parsers import expat
+
+ document = '<?xml version="1.0" encoding="UTF-32"?><r/>'.encode(
+ "utf-32"
+ )
+ etree.fromstring(document, etree.XMLParser(resolve_entities=False))
+ pushed = etree.XMLParser(resolve_entities=False)
+ with pytest.raises(etree.XMLSyntaxError):
+ pushed.feed(document)
+ pushed.close()
+ with pytest.raises(expat.ExpatError):
+ expat.ParserCreate(namespace_separator="}").Parse(document, True)
+
+ @pytest.mark.parametrize("part", ["core", "custom"])
+ def test_utf32_properties_with_a_long_uri_are_refused(self, part):
+ guard = _guard()
+
+ def data(elements: int, uri_chars: int = 1_000_000) -> bytes:
+ if part == "core":
+ xml = _long_uri_core(elements, uri_chars)
+ else:
+ xml = _long_uri_custom(elements, uri_chars)
+ body = ('<?xml version="1.0" encoding="UTF-32"?>' + xml).encode(
+ "utf-32"
+ )
+ if part == "core":
+ return _with_part("docProps/core.xml", lambda _xml: body)
+ return _with_custom_properties(body)
+
+ # openpyxl's load reads the part (a short URI, to stay quick).
+ workbook = _load_xlsx(data(10, uri_chars=10))
+ workbook.close()
+ # The reported shape: a 1,000,000-character URI over 20,000
+ # elements, about 10 KB, which took openpyxl 13 s or more to load.
+ reported = data(20_000)
+ assert len(reported) < 20_000
+ start = time.perf_counter()
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(reported, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ @pytest.mark.parametrize(
+ "codec, declared, bom",
+ [
+ ("utf-8", "ISO-8859-1", b""),
+ ("cp1252", "windows-1252", b""),
+ ("shift_jis", "Shift_JIS", b""),
+ ("utf-8", "US-ASCII", b""),
+ ("utf-32-le", "UTF-32", b""),
+ ("utf-32-be", "UTF-32BE", b""),
+ ("utf-32-le", "UTF-32", b"\xff\xfe\x00\x00"),
+ ("cp037", "cp037", b""),
+ ("utf-16-le", "ISO-8859-1", b"\xff\xfe"),
+ ("utf-8", "UTF-8' encoding='ISO-8859-1", b""),
+ ],
+ ids=[
+ "latin-1",
+ "windows-1252",
+ "shift-jis",
+ "ascii",
+ "utf-32le",
+ "utf-32be",
+ "utf-32-bom",
+ "ebcdic",
+ "utf-16-bom-latin-1-declared",
+ "two-encodings",
+ ],
+ )
+ @pytest.mark.parametrize(
+ "member",
+ ["xl/worksheets/sheet1.xml", "docProps/core.xml", "xl/styles.xml"],
+ )
+ def test_other_encodings_are_refused(self, member, codec, declared, bom):
+ """A declaration naming two encodings is not one XML 1.0 spells,
+ so it is refused as malformed."""
+ guard = _guard()
+ data = _with_part(
+ member, lambda xml: _reencoded(xml, codec, declared, bom)
+ )
+ with pytest.raises(
+ guard.DecompressionBombError,
+ match="not encoded in UTF-8|declaration is malformed",
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ @pytest.mark.parametrize(
+ "head",
+ [
+ b'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n',
+ b"\xef\xbb\xbf<?xml version='1.0' encoding='utf-8'?>",
+ b'\xef\xbb\xbf<?xml version = "1.0"\r\n\tencoding = "Utf-8" ?>',
+ b'<?xml version="1.0" standalone="yes"?>',
+ b"",
+ b"\xef\xbb\xbf",
+ ],
+ ids=[
+ "utf-8",
+ "utf-8-bom",
+ "bom-spaced-declaration",
+ "no-encoding",
+ "no-declaration",
+ "bom-only",
+ ],
+ )
+ def test_utf8_parts_pass_and_load(self, head):
+ """UTF-8, with or without a byte-order mark, with a declaration
+ naming UTF-8 or no encoding, or with no declaration at all."""
+ guard = _guard()
+ data = _real_package(".xlsx")
+ for member in (
+ "xl/worksheets/sheet1.xml",
+ "docProps/core.xml",
+ "xl/styles.xml",
+ "xl/workbook.xml",
+ ):
+ data = _rewrite_zip(
+ data, {member: lambda xml: head + _without_declaration(xml)}
+ )
+ guard.validate_zip_container(data, ".xlsx")
+ workbook = _load_xlsx(data)
+ list(workbook.worksheets[0].iter_rows())
+ workbook.close()
+
+ @pytest.mark.parametrize(
+ "codec, bom",
+ [("utf-16-le", b"\xff\xfe"), ("utf-16-be", b"\xfe\xff")],
+ ids=["utf-16le-bom", "utf-16be-bom"],
+ )
+ @pytest.mark.parametrize(
+ "member",
+ [
+ "xl/worksheets/sheet1.xml",
+ "docProps/core.xml",
+ "xl/styles.xml",
+ "xl/workbook.xml",
+ ],
+ )
+ def test_utf16_parts_with_a_bom_are_refused(self, member, codec, bom):
+ """These passed before, when the guard decoded UTF-16 to count
+ the ``<`` and ``=`` of a part; it now counts bytes and accepts
+ UTF-8 only (``_require_utf8_xml``), since the parsers detect
+ UTF-16 differently and no producer surveyed writes it. openpyxl
+ does load such a part, so this is a refusal of a spec-legal
+ (OPC allows UTF-16) but unwritten encoding."""
+ guard = _guard()
+ data = _with_part(
+ member, lambda xml: _reencoded(xml, codec, "UTF-16", bom)
+ )
+ workbook = _load_xlsx(data) # the premise: openpyxl reads it
+ workbook.close()
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_premise_expat_reads_a_zero_second_byte_as_utf16(self):
+ """expat reads a part whose first or second byte is zero as
+ UTF-16 without a byte-order mark (a leading space, ``20 00``,
+ then ``<``), where libxml2 sees UTF-8 and fails; in UTF-16 the
+ low byte of U+4E3C is ``3C``, a ``<`` to a byte count."""
+ from lxml import etree
+ from xml.parsers import expat
+
+ names = _utf16_lt_names(3)
+ for codec in ("utf-16-le", "utf-16-be"):
+ document = _utf16_leading_space(
+ "<r " + " ".join(f'{n}="1"' for n in names) + "/>", codec
+ )
+ assert document.count(b"<") == 1 + 3 * len(names)
+ seen = []
+ parser = expat.ParserCreate(namespace_separator="}")
+ parser.StartElementHandler = lambda _n, attrs: seen.append(attrs)
+ parser.Parse(document, True)
+ assert list(seen[0]) == names
+ with pytest.raises(etree.XMLSyntaxError):
+ etree.fromstring(document)
+
+ def test_premise_libxml2_switches_to_a_declared_utf16le(self):
+ """After an ASCII declaration naming ``UTF-16LE`` libxml2 reads
+ the rest as UTF-16LE (which expat rejects), so a byte count of
+ what follows misreads it."""
+ from lxml import etree
+ from xml.parsers import expat
+
+ document = _declared_utf16le('<r 㸿="1" 丼="2"/>')
+ root = etree.fromstring(document)
+ assert root.attrib.keys() == ["㸿", "丼"]
+ with pytest.raises(expat.ExpatError):
+ expat.ParserCreate(namespace_separator="}").Parse(document, True)
+
+ @pytest.mark.parametrize("codec", ["utf-16-le", "utf-16-be"])
+ @pytest.mark.parametrize(
+ "member", ["xl/worksheets/sheet1.xml", "xl/sharedStrings.xml"]
+ )
+ def test_bomless_utf16_expat_parts_are_refused(self, member, codec):
+ """A worksheet or shared-strings part (openpyxl streams both
+ with expat) that starts with a UTF-16 space and no byte-order
+ mark is refused before any parser reads it. Before, the guard
+ counted it as UTF-8, attribute names of U+4E3C and the like
+ reset its ``=`` count, and one start tag of 8.66 million
+ attributes took the guard to 2,252 MB before the names ceiling
+ refused it (200,000 attributes held about 34 MB here)."""
+ guard = _guard()
+ attributes = " ".join(
+ f'{n}="1"'
+ for n in _utf16_lt_names(guard.MAX_XML_TAG_ATTRIBUTE_SIGNS + 1)
+ )
+ if member == "xl/sharedStrings.xml":
+ xml = f'<sst xmlns="{_SHEET_MAIN}" {attributes}><si><t>a</t></si></sst>'
+ data = _with_shared_strings(_utf16_leading_space(xml, codec))
+ else:
+ xml = (
+ f'<worksheet xmlns="{_SHEET_MAIN}"><sheetData>'
+ f'<row r="1" {attributes}/></sheetData></worksheet>'
+ )
+ data = _with_part(
+ member, lambda _xml: _utf16_leading_space(xml, codec)
+ )
+ start = time.perf_counter()
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ @pytest.mark.parametrize(
+ "member", ["docProps/core.xml", "xl/styles.xml", "xl/workbook.xml"]
+ )
+ def test_a_declared_utf16_head_is_refused(self, member):
+ """An ASCII declaration naming ``UTF-16LE``, after which libxml2
+ (openpyxl's parser for these parts) reads UTF-16LE. Before, the
+ guard took the part for UTF-8 once a U+3E3F (bytes ``3F 3E``)
+ supplied the ``?>`` it looked for, and counted its ``<`` and
+ ``=`` in bytes: 4,000,000 attributes on ``core.xml`` cost about
+ 988 MB in the guard. A part of this shape that libxml2 reads in
+ full is refused now, without attributes."""
+ from lxml import etree
+
+ guard = _guard()
+
+ def declared(xml: bytes) -> bytes:
+ text = _without_declaration(xml).decode("utf-8")
+ end = text.index(">")
+ if text[end - 1] == "/":
+ end -= 1
+ return _declared_utf16le(text[:end] + ' 㸿="1"' + text[end:])
+
+ data = _with_part(member, declared)
+ with zipfile.ZipFile(io.BytesIO(data)) as zf:
+ assert "㸿" in etree.fromstring(zf.read(member)).attrib
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ @pytest.mark.parametrize(
+ "head",
+ [
+ b" \x00<\x00",
+ b"\x00<",
+ b"<\x00?\x00",
+ b"\x4c\x6f\xa7\x94",
+ b"\xef\xbb\xbf\xff\xfe<\x00",
+ b'<?xml version="1.0" encoding="UTF-8"?>\x00',
+ b'<?xml version="1.0" encoding="UTF8"?>',
+ b'<?xml version="1.0" encoding="UTF-16"?>',
+ b'<?xml encoding="UTF-8"?>',
+ ],
+ ids=[
+ "utf16le-leading-space",
+ "utf16be",
+ "utf16le",
+ "ebcdic",
+ "utf8-bom-then-utf16-bom",
+ "nul-after-declaration",
+ "utf8-alias",
+ "utf8-bytes-declared-utf16",
+ "no-version",
+ ],
+ )
+ def test_heads_both_parsers_may_not_read_as_utf8_are_refused(self, head):
+ guard = _guard()
+ data = _with_part(
+ "xl/worksheets/sheet1.xml",
+ lambda xml: head + _without_declaration(xml),
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="UTF-8|declaration"
+ ):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_an_overlong_xml_declaration_is_refused(self):
+ guard = _guard()
+ data = _with_part(
+ "xl/worksheets/sheet1.xml",
+ lambda xml: (
+ b'<?xml version="1.0"'
+ + b" " * guard._XML_SCAN_CHUNK
+ + b'encoding="UTF-8"?>'
+ + xml
+ ),
+ )
+ with pytest.raises(guard.DecompressionBombError, match="declaration"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ @pytest.mark.parametrize(
+ "member, root_end",
+ [
+ ("xl/worksheets/sheet1.xml", b"</worksheet>"),
+ ("[Content_Types].xml", b"</Types>"),
+ ],
+ )
+ def test_expat_parts_are_held_to_the_depth_ceiling(self, member, root_end):
+ """openpyxl streams worksheets with expat, and msoffcrypto reads
+ ``[Content_Types].xml`` with minidom; the root is one level."""
+ guard = _guard()
+
+ def nested(levels: int) -> bytes:
+ return _with_part(
+ member,
+ lambda xml: xml.replace(
+ root_end, b"<x>" * levels + b"</x>" * levels + root_end
+ ),
+ )
+
+ limit = guard.MAX_XLSX_XML_DEPTH
+ guard.validate_zip_container(nested(limit - 1), ".xlsx")
+ with pytest.raises(guard.DecompressionBombError, match="deep"):
+ guard.validate_zip_container(nested(limit), ".xlsx")
+
+ def test_lxml_parts_are_held_to_the_depth_ceiling(self):
+ """openpyxl's lxml tree parse fails beyond 256 levels, but
+ libxml2's push parser driving a target sets no limit."""
+ guard = _guard()
+
+ def nested(levels: int) -> bytes:
+ return _with_part(
+ "docProps/core.xml",
+ lambda xml: xml.replace(
+ b"</cp:coreProperties>",
+ b"<x>" * levels
+ + b"</x>" * levels
+ + b"</cp:coreProperties>",
+ ),
+ )
+
+ guard.validate_zip_container(nested(255), ".xlsx")
+ _load_xlsx(nested(255)).close()
+ with pytest.raises(guard.DecompressionBombError, match="deep"):
+ guard.validate_zip_container(nested(256), ".xlsx")
+ from lxml import etree
+
+ with pytest.raises(etree.XMLSyntaxError, match="depth"):
+ _load_xlsx(nested(256))
+
+ def test_premise_lxml_push_parser_with_a_target_has_no_depth_limit(self):
+ from lxml import etree
+
+ class Target:
+ def close(self):
+ return None
+
+ document = b"<a>" * 5_000 + b"</a>" * 5_000
+ parser = etree.XMLParser(target=Target(), resolve_entities=False)
+ parser.feed(document)
+ parser.close()
+ with pytest.raises(etree.XMLSyntaxError, match="depth"):
+ etree.fromstring(document, etree.XMLParser(resolve_entities=False))
+
+ def test_reported_deep_worksheet_is_refused_quickly(self):
+ """4 MiB of ``<a>``: expat kept about 145 bytes per open element
+ (128 MiB, a 130 KB file, about 6 GB) before the depth ceiling."""
+ guard = _guard()
+ data = _with_part(
+ "xl/worksheets/sheet1.xml",
+ lambda xml: xml.replace(
+ b"</worksheet>", b"<a>" * (4 * 1024 * 1024 // 3)
+ ),
+ )
+ assert len(data) < 50_000
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError, match="deep"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ @pytest.mark.parametrize(
+ "member, root_end",
+ [
+ ("xl/worksheets/sheet1.xml", b"</worksheet>"),
+ ("docProps/core.xml", b"</cp:coreProperties>"),
+ ],
+ )
+ def test_start_tags_are_held_to_the_attribute_ceiling(
+ self, member, root_end
+ ):
+ """Counted as the ``=`` between two ``<``, before either parser
+ stores the tag's attributes (in a value, ``=`` counts too)."""
+ guard = _guard()
+ limit = guard.MAX_XML_TAG_ATTRIBUTE_SIGNS
+
+ def tag(signs: int) -> bytes:
+ return _with_part(
+ member,
+ lambda xml: xml.replace(
+ root_end,
+ b'<x a0="" a1="' + b"=" * (signs - 2) + b'"/>' + root_end,
+ ),
+ )
+
+ guard.validate_zip_container(tag(limit), ".xlsx")
+ with pytest.raises(guard.DecompressionBombError, match="attributes"):
+ guard.validate_zip_container(tag(limit + 1), ".xlsx")
+
+ def test_reported_attribute_shape_is_refused_quickly(self):
+ """One start tag of 1,000,000 attributes, 11 MB of a worksheet,
+ held about 175 MB in the scan before."""
+ guard = _guard()
+ data = _with_part(
+ "xl/worksheets/sheet1.xml",
+ lambda xml: xml.replace(
+ b"</worksheet>",
+ b"<x "
+ + b" ".join(b'a%d=""' % i for i in range(1_000_000))
+ + b"/></worksheet>",
+ ),
+ )
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError, match="attributes"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_a_cell_of_32767_equals_signs_passes_and_loads(self):
+ """Excel holds up to 32,767 characters in a cell."""
+ guard = _guard()
+ text = "=" * 32_767
+ data = _with_part(
+ "xl/worksheets/sheet1.xml",
+ lambda xml: xml.replace(
+ b"<sheetData></sheetData>",
+ b'<sheetData><row r="1"><c r="A1" t="inlineStr"><is><t>'
+ + text.encode()
+ + b"</t></is></c></row></sheetData>",
+ ),
+ )
+ guard.validate_zip_container(data, ".xlsx")
+ workbook = _load_xlsx(data)
+ assert next(workbook.worksheets[0].values)[0] == text
+ workbook.close()
+
+ def test_a_member_no_loader_parses_is_not_scanned(self):
+ """A DTD, a long URI and deep nesting in an unreferenced member
+ cost the scan nothing: nothing parses it."""
+ guard = _guard()
+ junk = (
+ b"<!DOCTYPE r><r xmlns:q='urn:"
+ + b"a" * 100_000
+ + b"'>"
+ + b"<a>" * 1_000_000
+ )
+ data = _rewrite_zip(
+ _real_package(".xlsx"),
+ add={"junk/junk.xml": junk, "xl/junk.xml": junk},
+ )
+ opened: list = []
+ real_open = zipfile.ZipFile.open
+
+ def spy(self, name, *args, **kwargs):
+ opened.append(
+ name.filename if isinstance(name, zipfile.ZipInfo) else name
+ )
+ return real_open(self, name, *args, **kwargs)
+
+ # The guard's own verification inflates entries from the raw
+ # bytes; every ZipFile.open is the scan's or openpyxl's.
+ with patch.object(zipfile.ZipFile, "open", spy):
+ guard.validate_zip_container(data, ".xlsx")
+ assert "junk/junk.xml" not in opened
+ assert "xl/junk.xml" not in opened
+
+ def test_svg_with_a_doctype_in_media_passes_and_loads(self):
+ """Illustrator and icon SVGs carry the SVG 1.1 DOCTYPE; openpyxl
+ never parses an image."""
+ guard = _guard()
+
+ def types(ct: bytes) -> bytes:
+ return ct.replace(
+ b"</Types>",
+ b'<Default Extension="svg" ContentType="image/svg+xml"/>'
+ b"</Types>",
+ )
+
+ data = _rewrite_zip(
+ _real_package(".xlsx"),
+ {"[Content_Types].xml": types},
+ add={"xl/media/image1.svg": _SVG_WITH_DOCTYPE},
+ )
+ guard.validate_zip_container(data, ".xlsx")
+ _load_xlsx(data).close()
+ pd = pytest.importorskip("pandas")
+ pd.read_excel(io.BytesIO(data), sheet_name=None, engine="openpyxl")
+
+ @pytest.mark.parametrize(
+ "change",
+ [
+ b"<!DOCTYPE worksheet>",
+ b'<q:w xmlns:q="urn:' + b"a" * 1_025 + b'"/>',
+ b"<x>" * 300,
+ ],
+ ids=["dtd", "long-uri", "deep"],
+ )
+ def test_a_worksheet_at_a_media_path_is_still_scanned(self, change):
+ """openpyxl follows the workbook's relationship wherever it
+ points, so the part is scanned as a worksheet."""
+ guard = _guard()
+ sheet = (
+ f'<worksheet xmlns="{_SHEET_MAIN}"><sheetData/></worksheet>'
+ ).encode()
+ if change.startswith(b"<!DOCTYPE"):
+ sheet = change + sheet
+ else:
+ sheet = sheet.replace(b"</worksheet>", change + b"</worksheet>")
+ data = _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1"),
+ _ws_rel("rId1", "media/image1.svg"),
+ extra={"xl/media/image1.svg": sheet},
+ )
+ with pytest.raises(guard.DecompressionBombError):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_shared_strings_at_a_media_path_are_still_scanned(self):
+ """openpyxl reads the shared strings from the part the manifest
+ names, wherever it is."""
+ guard = _guard()
+ strings = (
+ f'<sst xmlns="{_SHEET_MAIN}"><si><t>a</t></si>'
+ + "<x>" * 300
+ + "</sst>"
+ ).encode()
+
+ def types(ct: bytes) -> bytes:
+ return ct.replace(
+ b"</Types>",
+ b'<Override PartName="/xl/media/image1.svg" ContentType='
+ b'"application/vnd.openxmlformats-officedocument.'
+ b'spreadsheetml.sharedStrings+xml"/></Types>',
+ )
+
+ data = _openpyxl_shaped_xlsx(
+ _sheet(1, "rId1"),
+ _ws_rel("rId1", "worksheets/sheet1.xml"),
+ extra={"xl/media/image1.svg": strings},
+ )
+ data = _rewrite_zip(data, {"[Content_Types].xml": types})
+ with pytest.raises(guard.DecompressionBombError, match="deep"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_chartsheets_and_sheet_relationships_are_scanned_with_lxml(self):
+ guard = _guard()
+ data = _xlsx_with_image_references(1, _small_png())
+ families: dict = {}
+ real_scan = guard._scan_xlsx_part
+
+ def spy(archive, info, scanned_with):
+ families[info.filename] = scanned_with
+ return real_scan(archive, info, scanned_with)
+
+ with patch.object(guard, "_scan_xlsx_part", spy):
+ guard.validate_zip_container(data, ".xlsx")
+ lxml = frozenset({guard._LXML})
+ assert families["xl/chartsheets/sheet2.xml"] == lxml
+ assert families["xl/chartsheets/_rels/sheet2.xml.rels"] == lxml
+ assert families["xl/worksheets/sheet1.xml"] == frozenset({guard._EXPAT})
+ # The drawing and its image are never read (openpyxl_hardening).
+ assert "xl/drawings/drawing1.xml" not in families
+ assert "xl/media/image1.png" not in families
+
+ def test_a_part_lxml_rejects_is_refused_where_openpyxl_parses_it(self):
+ """libxml2 stops at a name over 50,000 characters, so openpyxl's
+ load of such a part fails; expat would read on."""
+ guard = _guard()
+ data = _with_part(
+ "docProps/core.xml",
+ lambda xml: xml.replace(
+ b"</cp:coreProperties>",
+ b"<" + b"n" * 50_001 + b"/></cp:coreProperties>",
+ ),
+ )
+ with pytest.raises(guard.DecompressionBombError, match="malformed"):
+ guard.validate_zip_container(data, ".xlsx")
+
+ @pytest.mark.parametrize(
+ "member, root_end, name",
+ [
+ ("xl/worksheets/sheet1.xml", b"</worksheet>", "<n{}/>"),
+ ("xl/worksheets/sheet1.xml", b"</worksheet>", '<x a{}=""/>'),
+ ("xl/worksheets/sheet1.xml", b"</worksheet>", '<x xmlns:p{}="u"/>'),
+ ("docProps/core.xml", b"</cp:coreProperties>", "<n{}/>"),
+ ("docProps/core.xml", b"</cp:coreProperties>", '<x a{}=""/>'),
+ ],
+ ids=[
+ "expat-elements",
+ "expat-attributes",
+ "expat-prefixes",
+ "lxml-elements",
+ "lxml-attributes",
+ ],
+ )
+ def test_distinct_names_are_capped(self, member, root_end, name):
+ """Both parsers keep every distinct name for the whole parse."""
+ guard = _guard()
+
+ def names(count: int) -> bytes:
+ filler = "".join(name.format(i) for i in range(count)).encode()
+ return _with_part(
+ member, lambda xml: xml.replace(root_end, filler + root_end)
+ )
+
+ guard.validate_zip_container(names(1_000), ".xlsx")
+ with pytest.raises(guard.DecompressionBombError, match="distinct"):
+ guard.validate_zip_container(
+ names(guard.MAX_XLSX_PART_NAMES + 1), ".xlsx"
+ )
+
+ def test_reported_distinct_name_shape_is_refused_quickly(self):
+ """1,000,000 distinct element names, 8.9 MB of a worksheet, held
+ about 140 MB in the scan before the ceiling."""
+ guard = _guard()
+ data = _with_part(
+ "xl/worksheets/sheet1.xml",
+ lambda xml: xml.replace(
+ b"</worksheet>",
+ b"".join(b"<a%d/>" % i for i in range(1_000_000))
+ + b"</worksheet>",
+ ),
+ )
+ start = time.perf_counter()
+ with pytest.raises(guard.DecompressionBombError, match="distinct"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert time.perf_counter() - start < 5
+
+ def test_scan_ceilings_are_pinned(self):
+ guard = _guard()
+ assert guard.MAX_XLSX_PART_NAMES >= 1_000
+ assert guard.MAX_XLSX_XML_DEPTH == 256 # libxml2's own ceiling
+ assert guard.MAX_XML_TAG_ATTRIBUTE_SIGNS >= 32_767 # Excel's cell
+ assert guard._XML_SCAN_CHUNK <= guard.MAX_XML_TAG_ATTRIBUTE_SIGNS
+
+
+def _with_start_tag(data: bytes, member: str, anchor: bytes, attributes: int):
+ """*data* with one ``<x>`` of *attributes* empty attributes inserted
+ after *anchor* in *member* (into the first ``Relationship`` start
+ tag when *anchor* is empty)."""
+ names = b" ".join(b'a%d=""' % i for i in range(attributes))
+
+ def change(xml: bytes) -> bytes:
+ if not anchor:
+ return xml.replace(
+ b"<Relationship ", b"<Relationship " + names + b" ", 1
+ )
+ assert anchor in xml
+ return xml.replace(anchor, anchor + b"<x " + names + b"/>", 1)
+
+ return _rewrite_zip(data, {member: change})
+
+
+_STREAMED_PARTS = [
+ pytest.param(".docx", "word/document.xml", b"<w:body>", id="docx-document"),
+ pytest.param(
+ ".pptx", "ppt/slides/slide1.xml", b"<p:cSld>", id="pptx-slide"
+ ),
+ pytest.param(".docx", "word/_rels/document.xml.rels", b"", id="docx-rels"),
+ pytest.param(
+ ".pptx", "ppt/_rels/presentation.xml.rels", b"", id="pptx-rels"
+ ),
+]
+
+
+class TestStreamedPartsAreCountedBeforeParsing:
+ """Every ``.docx``/``.pptx`` part the guard streams with lxml's
+ ``iterparse`` (and every relationships part) is held to UTF-8 and
+ its start tags to ``MAX_XML_TAG_ATTRIBUTE_SIGNS`` before lxml reads
+ it: ``iterparse`` builds a start tag's element in full before the
+ per-element attribute ceilings see it, about 200 bytes per
+ attribute, with no limit of its own."""
+
+ def test_premise_iterparse_builds_a_huge_start_tag(self):
+ from lxml import etree
+
+ count = 70_000
+ document = (
+ b"<r><x "
+ + b" ".join(b'a%d=""' % i for i in range(count))
+ + b"/></r>"
+ )
+ for _event, element in etree.iterparse(
+ io.BytesIO(document), events=("start",)
+ ):
+ if element.tag == "x":
+ assert len(element.attrib) == count
+ break
+
+ @pytest.mark.parametrize("ext, member, anchor", _STREAMED_PARTS)
+ def test_a_start_tag_over_the_sign_ceiling_is_refused_before_parsing(
+ self, ext, member, anchor
+ ):
+ """Before, the guard's walk built such an element first (2,000,000
+ attributes in ``document.xml``, 23 MB, held 404 MB, so a 128 MiB
+ part about 2.4 GB) and a slide's was not refused at all."""
+ guard = _guard()
+ data = _with_start_tag(
+ _real_package(ext),
+ member,
+ anchor,
+ guard.MAX_XML_TAG_ATTRIBUTE_SIGNS + 1,
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="may carry more"
+ ):
+ guard.validate_zip_container(data, ext)
+
+ @pytest.mark.parametrize("ext, member, anchor", _STREAMED_PARTS)
+ def test_utf16_streamed_parts_are_refused(self, ext, member, anchor):
+ """A UTF-16 part (with a byte-order mark, which python-docx and
+ python-pptx would read) passed before; its bytes cannot be
+ counted, so it is refused like an ``.xlsx`` part."""
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(ext),
+ {
+ member: lambda xml: _reencoded(
+ xml, "utf-16-le", "UTF-16", b"\xff\xfe"
+ )
+ },
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(data, ext)
+
+ @pytest.mark.parametrize("ext, member, anchor", _STREAMED_PARTS)
+ def test_utf8_streamed_parts_with_a_bom_pass(self, ext, member, anchor):
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(ext),
+ {member: lambda xml: b"\xef\xbb\xbf" + xml},
+ )
+ guard.validate_zip_container(data, ext)
+
+
+@contextmanager
+def _parser_input(monkeypatch):
+ """Count every byte handed to an lxml or expat parser (``iterparse``
+ reads, ``fromstring`` buffers, ``XMLParser.feed`` and expat
+ ``Parse``) while the block runs; yields a one-element list."""
+ from lxml import etree
+ from xml.parsers import expat
+
+ received = [0]
+ real_iterparse, real_fromstring = etree.iterparse, etree.fromstring
+ real_parser, real_create = etree.XMLParser, expat.ParserCreate
+
+ class Metered:
+ def __init__(self, source):
+ self._source = source
+
+ def read(self, size=-1):
+ chunk = self._source.read(size)
+ received[0] += len(chunk)
+ return chunk
+
+ class MeteredParser(real_parser):
+ def feed(self, data):
+ received[0] += len(data)
+ return super().feed(data)
+
+ class MeteredExpat:
+ def __init__(self, parser):
+ object.__setattr__(self, "_parser", parser)
+
+ def __getattr__(self, name):
+ return getattr(self._parser, name)
+
+ def __setattr__(self, name, value):
+ setattr(self._parser, name, value)
+
+ def Parse(self, data, final=False):
+ received[0] += len(data)
+ return self._parser.Parse(data, final)
+
+ def fromstring(text, *args, **kwargs):
+ received[0] += len(text)
+ return real_fromstring(text, *args, **kwargs)
+
+ monkeypatch.setattr(
+ etree,
+ "iterparse",
+ lambda source, *a, **k: real_iterparse(Metered(source), *a, **k),
+ )
+ monkeypatch.setattr(etree, "fromstring", fromstring)
+ monkeypatch.setattr(etree, "XMLParser", MeteredParser)
+ monkeypatch.setattr(
+ expat,
+ "ParserCreate",
+ lambda *a, **k: MeteredExpat(real_create(*a, **k)),
+ )
+ try:
+ yield received
+ finally:
+ monkeypatch.undo()
+
+
+def _dtd_subset(shape: str, root: bytes, count: int) -> bytes:
+ """An internal subset of *count* declarations: attribute-list
+ declarations (no ``=`` anywhere), entity declarations, or ``xmlns:``
+ attribute defaults, which libxml2 adds to *root*'s start tag."""
+ if shape == "attlist":
+ return (
+ b"<!ATTLIST "
+ + root
+ + b" "
+ + b" ".join(b'a%d CDATA "x"' % i for i in range(count))
+ + b">"
+ )
+ if shape == "entity":
+ return b"".join(b'<!ENTITY e%d "x">' % i for i in range(count))
+ assert shape == "xmlns"
+ return (
+ b"<!ATTLIST "
+ + root
+ + b" "
+ + b" ".join(b'xmlns:p%d CDATA "u%d"' % (i, i) for i in range(count))
+ + b">"
+ )
+
+
+_ROOT_START = re.compile(rb"<(?![?!])([^\s/>]+)")
+
+
+def _with_dtd_subset(shape: str, count: int):
+ """A rewrite that puts a DTD of *count* *shape* declarations before
+ the part's root element (a part of about 2.5-3.5 MB at 150,000)."""
+
+ def rewrite(xml: bytes) -> bytes:
+ match = _ROOT_START.search(xml)
+ root = match.group(1)
+ return (
+ xml[: match.start()]
+ + b"<!DOCTYPE "
+ + root
+ + b" ["
+ + _dtd_subset(shape, root, count)
+ + b"]>"
+ + xml[match.start() :]
+ )
+
+ return rewrite
+
+
+def _after_root_start(insert: bytes):
+ """A rewrite that puts *insert* right after the root's start tag."""
+
+ def rewrite(xml: bytes) -> bytes:
+ match = _ROOT_START.search(xml)
+ end = xml.index(b">", match.end()) + 1
+ assert xml[end - 2 : end] != b"/>"
+ return xml[:end] + insert + xml[end:]
+
+ return rewrite
+
+
+def _package_for(source: str) -> bytes:
+ if source == "docx":
+ return _real_package(".docx")
+ if source == "docx-header":
+ return _docx_with_sections(1)
+ assert source == "pptx"
+ return _deck(1)
+
+
+#: (package, member, extension): every kind of site that parses a
+#: ``.docx``/``.pptx`` part: the walkers of ``document.xml`` and a slide,
+#: the relationships check, the header/footer union walker, and the
+#: buffered parses of ``_skeleton_xml``.
+_DTD_SITES = [
+ pytest.param("docx", "word/document.xml", ".docx", id="docx-document"),
+ pytest.param("pptx", "ppt/slides/slide1.xml", ".pptx", id="pptx-slide"),
+ pytest.param(
+ "docx", "word/_rels/document.xml.rels", ".docx", id="docx-rels"
+ ),
+ pytest.param("docx-header", "word/header1.xml", ".docx", id="docx-header"),
+ pytest.param(
+ "docx", "[Content_Types].xml", ".docx", id="docx-content-types"
+ ),
+ pytest.param("docx", "word/settings.xml", ".docx", id="docx-settings"),
+ pytest.param("docx", "word/styles.xml", ".docx", id="docx-styles"),
+ pytest.param(
+ "pptx", "ppt/presentation.xml", ".pptx", id="pptx-presentation"
+ ),
+ pytest.param(
+ "pptx", "[Content_Types].xml", ".pptx", id="pptx-content-types"
+ ),
+]
+
+#: The sites ``TestStreamedPartsAreCountedBeforeParsing`` does not
+#: cover: the header/footer union walker and ``_skeleton_xml``.
+_HEADER_AND_SKELETON_SITES = [
+ p
+ for p in _DTD_SITES
+ if p.id not in ("docx-document", "pptx-slide", "docx-rels")
+]
+
+
+class TestDtdIsRefusedInTheBytes:
+ """A document type declaration is refused in a part's bytes
+ (``_XmlProlog``, through ``_CountedXmlStream``) before any parser
+ the guard drives receives it. Checking at the root's first event,
+ as before, came after libxml2 had read and built the whole internal
+ subset: attribute-list declarations carry no ``=`` for the
+ start-tag count, so a 17.9 MB ``document.xml`` of one million held
+ 424 MB in the guard, and ``xmlns:`` defaults added namespace
+ declarations to the root its bytes did not show."""
+
+ def test_premise_libxml2_reads_the_whole_subset_before_the_root(self):
+ from lxml import etree
+
+ xml = _with_dtd_subset("attlist", 20_000)(b"<r/>")
+ read = [0]
+
+ class Source:
+ def __init__(self):
+ self._data = io.BytesIO(xml)
+
+ def read(self, size=-1):
+ chunk = self._data.read(size)
+ read[0] += len(chunk)
+ return chunk
+
+ for _event, element in etree.iterparse(
+ Source(), events=("start",), resolve_entities=False
+ ):
+ assert element.getroottree().docinfo.internalDTD is not None
+ break
+ assert read[0] == len(xml)
+
+ def test_premise_an_attlist_default_adds_namespaces_to_the_root(self):
+ from lxml import etree
+
+ xml = _with_dtd_subset("xmlns", 3)(b"<r/>")
+ assert b"=" not in xml.split(b"]>")[-1]
+ root = etree.fromstring(xml, etree.XMLParser(resolve_entities=False))
+ assert len(root.nsmap) == 3
+
+ @pytest.mark.parametrize("shape", ["attlist", "entity", "xmlns"])
+ @pytest.mark.parametrize("source, member, ext", _DTD_SITES)
+ def test_a_large_dtd_is_refused_before_a_parser_reads_it(
+ self, monkeypatch, source, member, ext, shape
+ ):
+ """Before, every parser site received the whole part (about
+ 3 MB here) and libxml2 built the subset first; now no parser
+ receives any of it (the other parts of the package total about
+ 0.4 MB)."""
+ guard = _guard()
+ data = _rewrite_zip(
+ _package_for(source), {member: _with_dtd_subset(shape, 150_000)}
+ )
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
+ assert archive.getinfo(member).file_size > 2_500_000
+ with _parser_input(monkeypatch) as received:
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ext)
+ assert received[0] < 1_000_000
+
+ @pytest.mark.parametrize(
+ "member, families",
+ [
+ ("xl/worksheets/sheet1.xml", "expat"),
+ ("xl/styles.xml", "lxml"),
+ ("[Content_Types].xml", "lxml and expat"),
+ ("xl/workbook.xml", "lxml"),
+ ],
+ )
+ def test_a_large_dtd_in_a_spreadsheet_part_is_refused_before_a_parser_reads_it(
+ self, monkeypatch, member, families
+ ):
+ """The scan's parsers refused at their doctype callbacks, but
+ lxml's push parser had first buffered the whole subset."""
+ openpyxl = pytest.importorskip("openpyxl")
+ guard = _guard()
+ buf = io.BytesIO()
+ openpyxl.Workbook().save(buf)
+ data = _rewrite_zip(
+ buf.getvalue(), {member: _with_dtd_subset("attlist", 150_000)}
+ )
+ with _parser_input(monkeypatch) as received:
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".xlsx")
+ assert received[0] < 1_000_000
+
+ def test_a_declaration_across_a_chunk_boundary_is_refused(
+ self, monkeypatch
+ ):
+ guard = _guard()
+
+ def rewrite(xml: bytes) -> bytes:
+ dtd = _with_dtd_subset("attlist", 150_000)(xml)
+ at = dtd.index(b"<!DOCTYPE")
+ pad = guard._XML_SCAN_CHUNK - 1 - at - len(b"<!---->")
+ assert pad > 0
+ # "<" ends the first chunk; "!DOCTYPE" starts the second.
+ return dtd[:at] + b"<!--" + b" " * pad + b"-->" + dtd[at:]
+
+ data = _rewrite_zip(
+ _real_package(".docx"), {"word/document.xml": rewrite}
+ )
+ with _parser_input(monkeypatch) as received:
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".docx")
+ assert received[0] < 1_000_000
+
+ @pytest.mark.parametrize(
+ "prolog",
+ [
+ b'<!ENTITY e "x">',
+ b'<!ATTLIST w:document a CDATA "x">',
+ b"<!ELEMENT w:document ANY>",
+ ],
+ ids=["entity", "attlist", "element"],
+ )
+ def test_a_declaration_without_a_doctype_is_refused(self, prolog):
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(".docx"),
+ {"word/document.xml": _with_doctype(prolog, b"<w:document")},
+ )
+ with pytest.raises(guard.DecompressionBombError, match="DTD"):
+ guard.validate_zip_container(data, ".docx")
+
+ def test_comments_cdata_and_instructions_holding_a_declaration_pass(self):
+ """``<!`` is examined only before the root element, outside
+ comments and processing instructions: a declaration spelled in
+ a comment, a processing instruction or a CDATA section is text."""
+ guard = _guard()
+ spelled = b'<!DOCTYPE w:document [<!ENTITY e "x">]>'
+
+ def rewrite(xml: bytes) -> bytes:
+ xml = _with_doctype(
+ b"<!-- " + spelled + b" --><?pi " + spelled + b"?><!---->",
+ b"<w:document",
+ )(xml)
+ return xml.replace(
+ b"<w:body>",
+ b"<w:body><!-- "
+ + spelled
+ + b" --><w:p><w:r><w:t><![CDATA["
+ + spelled
+ + b"]]></w:t></w:r></w:p>",
+ 1,
+ )
+
+ data = _rewrite_zip(
+ _real_package(".docx"), {"word/document.xml": rewrite}
+ )
+ guard.validate_zip_container(data, ".docx")
+
+ def test_a_comment_in_a_spreadsheet_part_holding_a_declaration_passes(self):
+ openpyxl = pytest.importorskip("openpyxl")
+ guard = _guard()
+ buf = io.BytesIO()
+ openpyxl.Workbook().save(buf)
+ data = _rewrite_zip(
+ buf.getvalue(),
+ {
+ "xl/worksheets/sheet1.xml": _with_doctype(
+ b"<!-- <!DOCTYPE worksheet> -->", b"<worksheet"
+ )
+ },
+ )
+ guard.validate_zip_container(data, ".xlsx")
+
+ def test_a_double_hyphen_in_a_comment_before_the_root_is_refused(self):
+ """Both parsers reject it; the scan would otherwise have to
+ guess where they end the comment."""
+ guard = _guard()
+ data = _rewrite_zip(
+ _real_package(".docx"),
+ {
+ "word/document.xml": _with_doctype(
+ b"<!-- a -- b -->", b"<w:document"
+ )
+ },
+ )
+ with pytest.raises(guard.DecompressionBombError, match="comment"):
+ guard.validate_zip_container(data, ".docx")
+
+ @pytest.mark.parametrize(
+ "xml, verdict",
+ [
+ (
+ b'<?xml version="1.0"?>\n<!-- <!DOCTYPE r> --><?p <!DOCTYPE?>'
+ b"<!----><r><![CDATA[<!DOCTYPE]]><!--<!DOCTYPE--></r>",
+ None,
+ ),
+ (b"<r/><!DOCTYPE r>", None),
+ (b"\xef\xbb\xbf <!DOCTYPE r><r/>", "DTD"),
+ (b'<?xml version="1.0"?><!ENTITY e "x"><r/>', "DTD"),
+ (b'<!-- a --><!ATTLIST r a CDATA "x"><r/>', "DTD"),
+ (b"<![CDATA[x]]><r/>", "DTD"),
+ (b"<?p ?? > <!-- ?><!doctype r><r/>", "DTD"),
+ (b"<!-- a -- b --><r/>", "comment"),
+ (b"<!-x--><r/>", "comment"),
+ (b"<!-- a ---><r/>", "comment"),
+ ],
+ )
+ def test_prolog_scan_is_the_same_at_every_chunk_boundary(
+ self, xml, verdict
+ ):
+ guard = _guard()
+
+ def scan(cuts) -> str | None:
+ prolog = guard._XmlProlog()
+ try:
+ start = 0
+ for cut in [*cuts, len(xml)]:
+ prolog.feed(xml[start:cut])
+ start = cut
+ except guard.DecompressionBombError as exc:
+ return "DTD" if "DTD" in str(exc) else "comment"
+ return None
+
+ assert scan([]) == verdict
+ assert scan(range(1, len(xml))) == verdict
+ for cut in range(len(xml) + 1):
+ assert scan([cut]) == verdict
+
+
+class TestHeaderAndSkeletonPartsAreCountedBeforeParsing:
+ """The header/footer union walker and ``_skeleton_xml`` (the content
+ types, ``presentation.xml``, and the settings and styles parts) take
+ their bytes through ``_CountedXmlStream`` as the other walkers do."""
+
+ @pytest.mark.parametrize("source, member, ext", _HEADER_AND_SKELETON_SITES)
+ def test_a_start_tag_over_the_sign_ceiling_is_refused(
+ self, source, member, ext
+ ):
+ guard = _guard()
+ names = b" ".join(
+ b'a%d=""' % i for i in range(guard.MAX_XML_TAG_ATTRIBUTE_SIGNS + 1)
+ )
+ data = _rewrite_zip(
+ _package_for(source),
+ {member: _after_root_start(b"<x " + names + b"/>")},
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="may carry more"
+ ):
+ guard.validate_zip_container(data, ext)
+
+ @pytest.mark.parametrize("source, member, ext", _HEADER_AND_SKELETON_SITES)
+ def test_utf16_parts_are_refused(self, source, member, ext):
+ guard = _guard()
+ data = _rewrite_zip(
+ _package_for(source),
+ {
+ member: lambda xml: _reencoded(
+ xml, "utf-16-le", "UTF-16", b"\xff\xfe"
+ )
+ },
+ )
+ with pytest.raises(
+ guard.DecompressionBombError, match="not encoded in UTF-8"
+ ):
+ guard.validate_zip_container(data, ext)
+
+ @pytest.mark.parametrize("source, member, ext", _HEADER_AND_SKELETON_SITES)
+ def test_controls_pass(self, source, member, ext):
+ _guard().validate_zip_container(_package_for(source), ext)
diff --git a/tests/security/test_pandoc_conversion_bounds.py b/tests/security/test_pandoc_conversion_bounds.py
new file mode 100644
index 0000000000..134e97a94e
--- /dev/null
+++ b/tests/security/test_pandoc_conversion_bounds.py
@@ -0,0 +1,936 @@
+"""Bounds for the pandoc conversion path (.rtf/.epub/.rst/.org/.odt).
+
+Five upload formats convert via a ``pandoc`` subprocess before parsing:
+unstructured's ``convert_file_to_html_text_using_pandoc`` (and
+``partition_odt`` for .odt) -> ``pypandoc.convert_file`` ->
+``Popen(...)`` + ``communicate()`` with **no timeout and no memory
+cap**. A hostile or pathological file therefore pins an indexing worker
+indefinitely or grows pandoc's heap without limit — the same class as
+the unbounded soffice conversion (#6513), reachable for content up to
+the upload size cap.
+
+These contracts pin the bounded seam: the binary resolves the way
+pypandoc resolves it (the shipped pypandoc-binary has no pandoc on
+PATH), a wall-clock timeout that reaches the subprocess, a new session
+plus a process-group kill on hang, a heap cap on the child, stdio sent
+to /dev/null, an output-size ceiling checked before the output is read,
+sandboxed pandoc argv, temp cleanup, and correct wiring (converted HTML
+is dispatched through the ``.html`` loader; ``.epub``/``.odt``
+containers still pass the zip guard first).
+"""
+
+from __future__ import annotations
+
+import inspect
+import io
+import os
+import signal
+import subprocess
+import sys
+import time
+import zipfile
+from contextlib import contextmanager
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+
+def _conv():
+ from local_deep_research.utilities import pandoc_conversion
+
+ return pandoc_conversion
+
+
+@contextmanager
+def _pandoc_available(conv, rts=True):
+ """Resolve the binary even on pandoc-less boxes, without probing."""
+ with (
+ patch.object(conv, "resolve_pandoc_binary", return_value="pandoc"),
+ patch.object(conv, "_pandoc_accepts_rts_heap_cap", return_value=rts),
+ ):
+ yield
+
+
+class _FakeProc:
+ pid = 8484
+ returncode = 0
+
+ def __init__(self, on_communicate=None, command=None, kwargs=None):
+ self._on_communicate = on_communicate
+ self.communicate_timeout = None
+ self.waited = False
+ self.command = command
+ self.kwargs = kwargs
+
+ def communicate(self, timeout=None):
+ self.communicate_timeout = timeout
+ if self._on_communicate is not None:
+ self._on_communicate()
+ return b"", b""
+
+ def wait(self):
+ self.waited = True
+ return 0
+
+
+PANDOC_BACKED = [".rtf", ".epub", ".rst", ".org", ".odt"]
+
+
+def _recording_popen(on_communicate=None, write_output=None):
+ """Popen double that records argv + kwargs of every launch."""
+ launched: list[_FakeProc] = []
+
+ def fake_popen(command, **kwargs):
+ def communicate():
+ if write_output is not None:
+ write_output(Path(command[command.index("-o") + 1]))
+ if on_communicate is not None:
+ on_communicate()
+
+ proc = _FakeProc(
+ on_communicate=communicate, command=command, kwargs=kwargs
+ )
+ launched.append(proc)
+ return proc
+
+ return fake_popen, launched
+
+
+class TestConversionBounds:
+ def test_the_timeout_reaches_the_subprocess(self, tmp_path):
+ conv = _conv()
+ proc = _FakeProc()
+
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", return_value=proc),
+ ):
+ try:
+ conv.pandoc_convert_bytes_to_html(
+ b"{\\rtf1}", ".rtf", work_dir=tmp_path
+ )
+ except conv.PandocConversionError:
+ pass # the fake writes no output; only timing matters
+
+ assert (
+ proc.communicate_timeout is not None
+ and proc.communicate_timeout >= 30
+ ), "pandoc runs without a real wall-clock timeout"
+
+ def test_hanging_conversion_is_killed_by_group_and_fails_typed(
+ self, tmp_path
+ ):
+ conv = _conv()
+
+ def hang(timeout=None):
+ raise subprocess.TimeoutExpired(cmd="pandoc", timeout=timeout)
+
+ proc = _FakeProc(on_communicate=hang)
+ kills: list = []
+
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", return_value=proc),
+ patch.object(conv, "_kill_process_group", side_effect=kills.append),
+ ):
+ with pytest.raises(conv.PandocConversionError) as excinfo:
+ conv.pandoc_convert_bytes_to_html(
+ b"{\\rtf1}", ".rtf", work_dir=tmp_path
+ )
+
+ assert "timed out" in str(excinfo.value).lower()
+ assert kills == [proc.pid], (
+ f"hung pandoc not killed by process group: {kills}"
+ )
+ assert proc.waited, "killed process was never reaped"
+
+ def test_runaway_output_is_refused_before_reading(self, tmp_path):
+ """Output over the ceiling is refused by size check, not read."""
+ conv = _conv()
+
+ def write_big(_proc):
+ (tmp_path / "out.html").write_bytes(b"<html>" + b"x" * 100_000)
+
+ with (
+ _pandoc_available(conv),
+ patch.object(
+ conv.subprocess,
+ "Popen",
+ side_effect=lambda *a, **k: _FakeProc(
+ on_communicate=lambda: write_big(None)
+ ),
+ ),
+ ):
+ with pytest.raises(conv.PandocConversionError) as excinfo:
+ conv.pandoc_convert_bytes_to_html(
+ b"{\\rtf1}",
+ ".rtf",
+ work_dir=tmp_path,
+ max_output_bytes=1000,
+ )
+
+ assert "larger than" in str(excinfo.value).lower()
+
+ def test_pandoc_argv_is_sandboxed(self, tmp_path):
+ """pandoc must run with --sandbox (restricted file access)."""
+ conv = _conv()
+ commands: list = []
+
+ def fake_popen(command, **kwargs):
+ commands.append(command)
+ return _FakeProc()
+
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ try:
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+ except conv.PandocConversionError:
+ pass
+
+ assert commands, "pandoc never launched"
+ argv = commands[0]
+ assert "--sandbox" in argv, f"pandoc argv not sandboxed: {argv}"
+ assert "out.html" in " ".join(argv) or "-o" in argv, (
+ f"pandoc does not write to a bounded output file: {argv}"
+ )
+
+ def test_temp_input_is_cleaned_up(self, tmp_path):
+ conv = _conv()
+
+ def check_input():
+ docs = list(tmp_path.rglob("*.rst"))
+ assert docs, "input missing while pandoc runs"
+
+ with (
+ _pandoc_available(conv),
+ patch.object(
+ conv.subprocess,
+ "Popen",
+ return_value=_FakeProc(on_communicate=check_input),
+ ),
+ ):
+ with pytest.raises(conv.PandocConversionError):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+
+ leftovers = list(tmp_path.rglob("*"))
+ assert not leftovers, f"conversion left files behind: {leftovers}"
+
+
+class TestWiring:
+ @pytest.mark.parametrize("ext", PANDOC_BACKED)
+ def test_pandoc_backed_uploads_dispatch_through_the_converter(
+ self, tmp_path, ext
+ ):
+ """Each pandoc-backed upload converts first, then loads as HTML."""
+ import local_deep_research.document_loaders.bytes_loader as bl
+
+ conv = _conv()
+ dispatched: list = []
+ guard_calls: list = []
+
+ from local_deep_research.document_loaders import zip_container_guard
+
+ def fake_popen(command, **kwargs):
+ out = Path(command[command.index("-o") + 1])
+ out.write_text(
+ "<html><body>converted</body></html>", encoding="utf-8"
+ )
+ return _FakeProc()
+
+ def recording_guard(content, extension, **kwargs):
+ guard_calls.append(extension)
+ # Behave like the real guard: containers validated, the
+ # rest pass through untouched.
+ if extension in zip_container_guard.ZIP_CONTAINER_EXTENSIONS:
+ zip_container_guard.validate_zip_container(content, extension)
+
+ def fake_get_loader(extension):
+ dispatched.append(extension)
+ return # load_from_bytes then raises "No loader found"
+
+ def payload_for(extension):
+ if extension in (".epub", ".odt"):
+ buf = io.BytesIO()
+ with zipfile.ZipFile(buf, "w") as zf:
+ zf.writestr("META-INF/container.xml", "<r/>")
+ return buf.getvalue()
+ return b"payload"
+
+ with (
+ _pandoc_available(conv),
+ patch.object(bl, "is_extension_supported", return_value=True),
+ patch.object(
+ bl,
+ "get_loader_class_for_extension",
+ side_effect=fake_get_loader,
+ ),
+ patch.object(bl, "validate_zip_container", recording_guard),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ # The fake loader registry entry is None, so the (already
+ # converted) dispatch ends in the expected ValueError.
+ with pytest.raises(ValueError, match="No loader found"):
+ bl.load_from_bytes(payload_for(ext), ext, f"hostile{ext}")
+
+ # The converted content was dispatched for HTML loading...
+ assert dispatched == [".html"], dispatched
+ # ...and the container guard ran on the ORIGINAL extension
+ # (notably .epub, before the conversion replaced it).
+ assert guard_calls == [ext], guard_calls
+
+ def test_live_round_trip(self, tmp_path):
+ """Control: a real minimal rst converts to HTML with the binary
+ the app actually ships (pypandoc-binary, not PATH)."""
+ conv = _conv()
+ if conv.resolve_pandoc_binary() is None:
+ pytest.skip("no pandoc via pypandoc or PATH")
+
+ html = conv.pandoc_convert_bytes_to_html(
+ b"Hello *pandoc*\n=====\n\nbody text", ".rst", work_dir=tmp_path
+ )
+
+ assert b"body text" in html.lower()
+
+ def test_live_odt_round_trip(self, tmp_path):
+ """Control: a genuine ODT converts through the bounded wrapper."""
+ pypandoc = pytest.importorskip("pypandoc")
+ conv = _conv()
+ if conv.resolve_pandoc_binary() is None:
+ pytest.skip("no pandoc via pypandoc or PATH")
+ odt_path = tmp_path / "src.odt"
+ pypandoc.convert_text(
+ "Otters build dams.", "odt", format="md", outputfile=str(odt_path)
+ )
+
+ work = tmp_path / "work"
+ work.mkdir()
+
+ html = conv.pandoc_convert_bytes_to_html(
+ odt_path.read_bytes(), ".odt", work_dir=work
+ )
+
+ assert b"Otters build dams." in html
+
+ def test_live_binary_honours_the_rts_heap_cap(self):
+ """The shipped binary accepts ``+RTS -M``, so the preferred
+ (thread-safe) memory cap is the one actually in force."""
+ conv = _conv()
+ pandoc = conv.resolve_pandoc_binary()
+ if pandoc is None or "pypandoc" not in pandoc:
+ pytest.skip("bundled pypandoc-binary pandoc not in use")
+ with patch.dict(conv._rts_probe_cache, clear=True):
+ assert conv._pandoc_accepts_rts_heap_cap(pandoc) is True
+
+
+class TestBinaryResolution:
+ """The shipped install is pypandoc-binary: pandoc lives at
+ ``pypandoc/files/pandoc`` and nothing named ``pandoc`` is on PATH.
+ A ``shutil.which``-only resolver fails every pandoc-backed upload."""
+
+ def test_resolver_uses_pypandoc_when_path_has_no_pandoc(self):
+ pypandoc = pytest.importorskip("pypandoc")
+ conv = _conv()
+ bundled = "/opt/site-packages/pypandoc/files/pandoc"
+
+ with (
+ patch.object(conv.shutil, "which", return_value=None),
+ patch.object(pypandoc, "get_pandoc_path", return_value=bundled),
+ ):
+ assert conv.resolve_pandoc_binary() == bundled
+
+ def test_conversion_launches_the_pypandoc_binary(self, tmp_path):
+ pypandoc = pytest.importorskip("pypandoc")
+ conv = _conv()
+ bundled = "/opt/site-packages/pypandoc/files/pandoc"
+ fake_popen, launched = _recording_popen(
+ write_output=lambda out: out.write_text(
+ "<p>ok</p>", encoding="utf-8"
+ )
+ )
+
+ with (
+ patch.object(conv.shutil, "which", return_value=None),
+ patch.object(pypandoc, "get_pandoc_path", return_value=bundled),
+ patch.object(
+ conv, "_pandoc_accepts_rts_heap_cap", return_value=True
+ ),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ html = conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+
+ assert html == b"<p>ok</p>"
+ assert launched[0].command[0] == bundled
+
+ def test_resolver_falls_back_to_path_without_pypandoc_pandoc(self):
+ pypandoc = pytest.importorskip("pypandoc")
+ conv = _conv()
+
+ with (
+ patch.object(conv.shutil, "which", return_value="/usr/bin/pandoc"),
+ patch.object(
+ pypandoc, "get_pandoc_path", side_effect=OSError("none")
+ ),
+ ):
+ assert conv.resolve_pandoc_binary() == "/usr/bin/pandoc"
+
+ def test_no_binary_anywhere_fails_typed(self, tmp_path):
+ conv = _conv()
+
+ with patch.object(conv, "resolve_pandoc_binary", return_value=None):
+ with pytest.raises(
+ conv.PandocConversionError, match="not available"
+ ):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+
+
+class TestProcessIsolation:
+ """A hang must be killable as a tree, and nothing may be buffered."""
+
+ def _launch(self, conv, tmp_path, **popen_opts):
+ fake_popen, launched = _recording_popen(**popen_opts)
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ try:
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+ except conv.PandocConversionError:
+ pass
+ assert launched, "pandoc never launched"
+ return launched[0]
+
+ def test_pandoc_runs_in_its_own_session(self, tmp_path):
+ """Without a new session, proc.pid is not a process-group id:
+ the group kill misses and ``proc.wait()`` blocks forever."""
+ conv = _conv()
+ kwargs = self._launch(conv, tmp_path).kwargs
+
+ assert (
+ kwargs.get("start_new_session") is True
+ or kwargs.get("process_group") == 0
+ ), f"pandoc not started in its own process group: {kwargs}"
+
+ def test_stdio_goes_to_devnull_not_a_pipe(self, tmp_path):
+ """``communicate()`` on a PIPE buffers every byte pandoc writes
+ (tens of MB of warnings were observed) in the worker."""
+ conv = _conv()
+ kwargs = self._launch(conv, tmp_path).kwargs
+
+ for stream in ("stdout", "stderr"):
+ assert kwargs.get(stream) == subprocess.DEVNULL, (
+ f"pandoc {stream} is buffered: {kwargs.get(stream)!r}"
+ )
+
+ @pytest.mark.skipif(
+ not hasattr(os, "killpg"), reason="no process groups here"
+ )
+ def test_timeout_kill_targets_the_process_group(self, tmp_path):
+ """The real kill helper must signal the GROUP, not just the
+ child: grandchildren would otherwise survive the timeout."""
+ conv = _conv()
+
+ def hang():
+ raise subprocess.TimeoutExpired(cmd="pandoc", timeout=1)
+
+ fake_popen, launched = _recording_popen(on_communicate=hang)
+ group_kills: list = []
+ pid_kills: list = []
+
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ patch.object(
+ conv.os, "killpg", side_effect=lambda *a: group_kills.append(a)
+ ),
+ patch.object(
+ conv.os, "kill", side_effect=lambda *a: pid_kills.append(a)
+ ),
+ ):
+ with pytest.raises(conv.PandocConversionError, match="timed out"):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+
+ assert group_kills == [(launched[0].pid, signal.SIGKILL)], (
+ f"hung pandoc not killed as a group: killpg={group_kills} "
+ f"kill={pid_kills}"
+ )
+ assert launched[0].waited, "killed process was never reaped"
+
+
+class TestMemoryCap:
+ """pandoc's zip reader inflates entries regardless of a lying
+ declared size, so the child needs its own memory ceiling."""
+
+ def test_rts_heap_cap_is_on_the_argv(self, tmp_path):
+ conv = _conv()
+ fake_popen, launched = _recording_popen()
+
+ with (
+ _pandoc_available(conv, rts=True),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(conv.PandocConversionError):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+
+ argv = launched[0].command
+ cap = f"-M{conv.DEFAULT_MAX_HEAP_MB}m"
+ assert argv[1:4] == ["+RTS", cap, "-RTS"], (
+ f"pandoc runs without a heap cap: {argv}"
+ )
+
+ def test_default_heap_cap_is_bounded(self):
+ conv = _conv()
+ default = (
+ inspect.signature(conv.pandoc_convert_bytes_to_html)
+ .parameters["max_heap_mb"]
+ .default
+ )
+
+ assert default == conv.DEFAULT_MAX_HEAP_MB
+ assert 512 <= conv.DEFAULT_MAX_HEAP_MB <= 4096
+
+ @pytest.mark.skipif(
+ not sys.platform.startswith("linux"), reason="RLIMIT_AS is Linux-only"
+ )
+ def test_rlimit_as_fallback_without_rts_options(self, tmp_path):
+ """A pandoc build without ``-rtsopts`` rejects ``+RTS``; the
+ cap then moves to RLIMIT_AS in the child instead of vanishing."""
+ import resource
+
+ conv = _conv()
+ fake_popen, launched = _recording_popen()
+
+ with (
+ _pandoc_available(conv, rts=False),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(conv.PandocConversionError):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path, max_heap_mb=1000
+ )
+
+ proc = launched[0]
+ assert "+RTS" not in proc.command
+ preexec = proc.kwargs.get("preexec_fn")
+ assert preexec is not None, "no memory cap without RTS options"
+
+ applied: list = []
+ with patch.object(
+ resource, "setrlimit", side_effect=lambda *a: applied.append(a)
+ ):
+ preexec()
+ expected = (1000 + conv._RLIMIT_AS_HEADROOM_MB) * 1024 * 1024
+ assert applied == [(resource.RLIMIT_AS, (expected, expected))]
+
+ def test_rlimit_headroom_is_sane(self):
+ """Headroom covers code, RTS bookkeeping and mmaps; a huge value
+ would quietly turn the fallback cap into no cap."""
+ conv = _conv()
+
+ assert 256 <= conv._RLIMIT_AS_HEADROOM_MB <= 1024
+
+ @pytest.mark.parametrize(
+ ("rts", "expected"),
+ [
+ (True, "2048 MiB heap cap"),
+ (False, "2560 MiB address-space limit"),
+ ],
+ )
+ def test_heap_exhaustion_fails_typed_with_the_effective_limit(
+ self, tmp_path, rts, expected
+ ):
+ """The failure names the limit actually in force: the heap cap,
+ or (fallback) heap + headroom as an address-space limit."""
+ conv = _conv()
+ if not rts and not sys.platform.startswith("linux"):
+ pytest.skip("RLIMIT_AS fallback is Linux-only")
+
+ class _Exhausted(_FakeProc):
+ returncode = 251
+
+ with (
+ _pandoc_available(conv, rts=rts),
+ patch.object(conv.subprocess, "Popen", return_value=_Exhausted()),
+ ):
+ with pytest.raises(conv.PandocConversionError) as excinfo:
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path, max_heap_mb=2048
+ )
+
+ message = str(excinfo.value)
+ assert "out of memory" in message
+ assert expected in message, message
+
+
+class TestRtsProbeCache:
+ """A successful probe is remembered; a failed one is retried, but
+ at most once per ``_RTS_PROBE_FAILURE_TTL_S``."""
+
+ @staticmethod
+ def _run(conv, results, times):
+ probes: list = []
+
+ def probe(pandoc):
+ probes.append(pandoc)
+ return results[min(len(probes), len(results)) - 1]
+
+ answers = []
+ clock = iter(times)
+ with (
+ patch.dict(conv._rts_probe_cache, clear=True),
+ patch.object(conv, "_probe_rts_heap_cap", side_effect=probe),
+ patch.object(
+ conv, "time", SimpleNamespace(monotonic=lambda: next(clock))
+ ),
+ ):
+ for _ in times:
+ answers.append(conv._pandoc_accepts_rts_heap_cap("pandoc"))
+ return answers, probes
+
+ def test_success_is_cached(self):
+ conv = _conv()
+
+ answers, probes = self._run(conv, [True], [0.0, 1.0, 10_000.0])
+
+ assert answers == [True, True, True]
+ assert len(probes) == 1
+
+ def test_failure_is_retried_after_the_ttl_only(self):
+ conv = _conv()
+ ttl = conv._RTS_PROBE_FAILURE_TTL_S
+
+ answers, probes = self._run(
+ conv, [False, True], [0.0, ttl / 2, ttl + 1.0, ttl + 2.0]
+ )
+
+ # Cached failure inside the window, re-probed after it, and the
+ # later success sticks.
+ assert answers == [False, False, True, True]
+ assert len(probes) == 2
+
+ def test_failure_ttl_is_bounded(self):
+ conv = _conv()
+
+ assert 30 <= conv._RTS_PROBE_FAILURE_TTL_S <= 3600
+
+ def test_probe_timeout_counts_as_failure(self):
+ conv = _conv()
+
+ def slow(*args, **kwargs):
+ raise subprocess.TimeoutExpired(cmd="pandoc", timeout=30)
+
+ with patch.object(conv.subprocess, "run", side_effect=slow):
+ assert conv._probe_rts_heap_cap("pandoc") is False
+
+
+class TestDefaultsAndHygiene:
+ def test_default_timeout_is_bounded_and_reaches_the_subprocess(
+ self, tmp_path
+ ):
+ conv = _conv()
+ fake_popen, launched = _recording_popen()
+
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(conv.PandocConversionError):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+
+ assert launched[0].communicate_timeout == (
+ conv.DEFAULT_CONVERSION_TIMEOUT_S
+ )
+ assert 30 <= conv.DEFAULT_CONVERSION_TIMEOUT_S <= 300
+
+ def test_default_output_ceiling_refuses_one_byte_over(self, tmp_path):
+ """The default ceiling is 64 MiB and applies without kwargs; a
+ sparse file keeps the check cheap."""
+ conv = _conv()
+ assert conv.DEFAULT_MAX_OUTPUT_BYTES == 64 * 1024 * 1024
+
+ def sparse(out):
+ with out.open("wb") as fh:
+ fh.truncate(conv.DEFAULT_MAX_OUTPUT_BYTES + 1)
+
+ fake_popen, _ = _recording_popen(write_output=sparse)
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ with pytest.raises(conv.PandocConversionError, match="larger"):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path
+ )
+
+ def test_oversized_output_is_never_read(self, tmp_path):
+ """The size check must come BEFORE the read: reading first
+ materializes the whole runaway output in the worker."""
+ conv = _conv()
+ reads: list = []
+ real_read_bytes = Path.read_bytes
+
+ def spy(self):
+ reads.append(self.name)
+ return real_read_bytes(self)
+
+ fake_popen, _ = _recording_popen(
+ write_output=lambda out: out.write_bytes(b"x" * 5000)
+ )
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ patch.object(Path, "read_bytes", spy),
+ ):
+ with pytest.raises(conv.PandocConversionError, match="larger"):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=tmp_path, max_output_bytes=100
+ )
+
+ assert "out.html" not in reads, "oversized output was read"
+
+ @pytest.mark.parametrize("succeed", [True, False])
+ def test_owned_work_dir_is_removed(self, tmp_path, succeed):
+ """With no work_dir the wrapper owns a mkdtemp dir; it must be
+ gone afterwards on success and on failure."""
+ conv = _conv()
+ created: list[Path] = []
+ real_mkdtemp = conv.tempfile.mkdtemp
+
+ def recording_mkdtemp(*args, **kwargs):
+ path = real_mkdtemp(*args, dir=tmp_path, **kwargs)
+ created.append(Path(path))
+ return path
+
+ fake_popen, _ = _recording_popen(
+ write_output=(
+ (lambda out: out.write_text("<p>ok</p>", encoding="utf-8"))
+ if succeed
+ else None
+ )
+ )
+ with (
+ _pandoc_available(conv),
+ patch.object(conv.tempfile, "mkdtemp", recording_mkdtemp),
+ patch.object(conv.subprocess, "Popen", side_effect=fake_popen),
+ ):
+ if succeed:
+ assert conv.pandoc_convert_bytes_to_html(b"x", ".rst")
+ else:
+ with pytest.raises(conv.PandocConversionError):
+ conv.pandoc_convert_bytes_to_html(b"x", ".rst")
+
+ assert len(created) == 1, created
+ assert not created[0].exists(), "owned work dir left behind"
+
+
+class TestOdtIsPandocBacked:
+ def test_every_pandoc_loader_extension_is_routed(self):
+ """Every registered loader that shells out to pandoc must be
+ in the bounded set — .odt included (partition_odt ->
+ pypandoc.convert_file, unbounded)."""
+ from local_deep_research.document_loaders.loader_registry import (
+ LOADER_REGISTRY,
+ )
+
+ conv = _conv()
+ pandoc_loaders = {
+ "UnstructuredODTLoader",
+ "UnstructuredEPubLoader",
+ "UnstructuredRTFLoader",
+ "UnstructuredRSTLoader",
+ "UnstructuredOrgModeLoader",
+ }
+ registered = {
+ ext
+ for ext, entry in LOADER_REGISTRY.items()
+ if entry["loader_class"].__name__ in pandoc_loaders
+ }
+
+ assert ".odt" in conv.PANDOC_BACKED_EXTENSIONS
+ assert registered <= conv.PANDOC_BACKED_EXTENSIONS, (
+ registered - conv.PANDOC_BACKED_EXTENSIONS
+ )
+
+
+_FAKE_BINARY = """#!/bin/sh
+sleep 20 &
+echo $! > "{pidfile}"
+wait
+"""
+
+#: A pandoc without -rtsopts: rejects ``+RTS``, otherwise writes -o.
+_NO_RTSOPTS_BINARY = """#!/bin/sh
+if [ "$1" = "+RTS" ]; then
+ echo "Most RTS options are disabled" >&2
+ exit 1
+fi
+out=""
+while [ $# -gt 0 ]; do
+ if [ "$1" = "-o" ]; then out="$2"; fi
+ shift
+done
+echo "<p>converted without rtsopts</p>" > "$out"
+"""
+
+
+def _pid_alive(pid: int) -> bool:
+ try:
+ with open(f"/proc/{pid}/stat", encoding="utf-8") as fh:
+ state = fh.read().rsplit(")", 1)[1].split()[0]
+ except (FileNotFoundError, ProcessLookupError, IndexError):
+ return False
+ return state not in ("Z", "X")
+
+
+def _script(tmp_path: Path, name: str, body: str) -> Path:
+ """Write an executable script, skipping on a noexec tmp_path."""
+ path = tmp_path / name
+ path.write_text(body, encoding="utf-8")
+ path.chmod(0o755)
+ probe = tmp_path / "exec-probe"
+ probe.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")
+ probe.chmod(0o755)
+ try:
+ subprocess.run([str(probe)], check=True, timeout=10)
+ except (OSError, subprocess.SubprocessError):
+ pytest.skip("tmp_path does not allow executing scripts")
+ return path
+
+
+def _wait_for_pid(pidfile: Path, timeout_s: float = 5.0) -> int:
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ try:
+ text = pidfile.read_text(encoding="utf-8").strip()
+ except FileNotFoundError:
+ text = ""
+ if text:
+ return int(text)
+ time.sleep(0.05)
+ pytest.skip("child never reached its spawn point (loaded host)")
+
+
+ not sys.platform.startswith("linux"), reason="uses /proc and /bin/sh"
+)
+class TestRealProcessTree:
+ """A real child that spawns a sleeping grandchild: the timeout must
+ return promptly AND take the grandchild down with it."""
+
+ def test_timeout_kills_the_whole_tree(self, tmp_path):
+ conv = _conv()
+ pidfile = tmp_path / "grandchild.pid"
+ binary = _script(
+ tmp_path, "fake-pandoc", _FAKE_BINARY.format(pidfile=pidfile)
+ )
+ work = tmp_path / "work"
+ work.mkdir()
+
+ grandchild = None
+ try:
+ with (
+ patch.object(
+ conv, "resolve_pandoc_binary", return_value=str(binary)
+ ),
+ patch.object(
+ conv, "_pandoc_accepts_rts_heap_cap", return_value=True
+ ),
+ ):
+ started = time.monotonic()
+ with pytest.raises(conv.PandocConversionError, match="timed"):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=work, timeout_s=2
+ )
+ elapsed = time.monotonic() - started
+
+ assert elapsed < 12, f"timeout took {elapsed:.1f}s to return"
+ grandchild = _wait_for_pid(pidfile)
+ deadline = time.monotonic() + 5
+ while _pid_alive(grandchild) and time.monotonic() < deadline:
+ time.sleep(0.05)
+ assert not _pid_alive(grandchild), "grandchild survived the kill"
+ finally:
+ if grandchild is None and pidfile.exists():
+ text = pidfile.read_text(encoding="utf-8").strip()
+ grandchild = int(text) if text else None
+ if grandchild is not None:
+ try:
+ os.kill(grandchild, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+
+
+ not sys.platform.startswith("linux"),
+ reason="RLIMIT_AS fallback is Linux-only; uses /bin/sh",
+)
+class TestBinaryWithoutRtsopts:
+ """A pandoc built without ``-rtsopts`` against the real probe."""
+
+ def test_real_probe_falls_back_to_rlimit_and_converts(self, tmp_path):
+ conv = _conv()
+ binary = _script(tmp_path, "pandoc-no-rts", _NO_RTSOPTS_BINARY)
+ work = tmp_path / "work"
+ work.mkdir()
+ launched: list = []
+ real_popen = subprocess.Popen
+
+ def spy(command, **kwargs):
+ launched.append((command, kwargs))
+ return real_popen(command, **kwargs)
+
+ with (
+ patch.dict(conv._rts_probe_cache, clear=True),
+ patch.object(
+ conv, "resolve_pandoc_binary", return_value=str(binary)
+ ),
+ patch.object(conv.subprocess, "Popen", side_effect=spy),
+ ):
+ html = conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=work, timeout_s=20
+ )
+
+ assert b"converted without rtsopts" in html
+ command, kwargs = launched[-1]
+ assert "+RTS" not in command
+ assert kwargs.get("preexec_fn") is not None, "fallback cap missing"
+
+ def test_wrong_probe_costs_availability_not_the_cap(self, tmp_path):
+ """If the probe wrongly says yes, the binary rejects ``+RTS``
+ and the conversion fails typed — pandoc never runs uncapped."""
+ conv = _conv()
+ binary = _script(tmp_path, "pandoc-no-rts", _NO_RTSOPTS_BINARY)
+ work = tmp_path / "work"
+ work.mkdir()
+
+ with (
+ patch.object(
+ conv, "resolve_pandoc_binary", return_value=str(binary)
+ ),
+ patch.object(
+ conv, "_pandoc_accepts_rts_heap_cap", return_value=True
+ ),
+ ):
+ with pytest.raises(conv.PandocConversionError, match="exit 1"):
+ conv.pandoc_convert_bytes_to_html(
+ b"x", ".rst", work_dir=work, timeout_s=20
+ )