Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions packages/extraction/tests/adversarial.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
"""Create bounded adversarial test documents inside the disposable test container."""
from pathlib import Path
import base64
import struct
import zipfile
import zlib
from docx import Document
from pypdf import PdfReader, PdfWriter

Expand Down Expand Up @@ -69,6 +71,32 @@
ArrayObject, DecodedStreamObject, DictionaryObject, EncodedStreamObject,
NameObject, NumberObject,
)
def wrapped_table_pdf():
# Adjacent cells wrap above and below the row label's baseline. Keep every
# word separate even when the extractor keeps the fragments on one line.
writer = PdfWriter()
page = writer.add_blank_page(width=612, height=792)
font = writer._add_object(DictionaryObject({
NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/Type1'),
NameObject('/BaseFont'): NameObject('/Helvetica'),
NameObject('/Encoding'): NameObject('/WinAnsiEncoding'),
}))
page[NameObject('/Resources')] = DictionaryObject({NameObject('/Font'): DictionaryObject({NameObject('/F1'): font})})
stream = DecodedStreamObject()
stream.set_data(
b'BT /F1 10 Tf '
b'1 0 0 1 72 700 Tm (Row) Tj '
b'1 0 0 1 160 706 Tm (Alpha) Tj '
b'1 0 0 1 160 694 Tm (Beta) Tj '
b'1 0 0 1 240 706 Tm (Gamma) Tj '
b'1 0 0 1 240 694 Tm (Delta) Tj ET'
)
page[NameObject('/Contents')] = writer._add_object(stream)
with (root / 'wrapped-table.pdf').open('wb') as file:
writer.write(file)

wrapped_table_pdf()

for name, mode in [('form-limit.pdf', 'limit'), ('form-filter.pdf', 'filter'), ('form-valid.pdf', 'valid')]:
writer = PdfWriter()
writer.append(root / 'pages.pdf')
Expand All @@ -91,6 +119,42 @@
stream.set_data(stream.get_data() + b'\n/Form Do')
writer.write(root / name)

# All supported abbreviated filters must reach the same bounded decoders as
# their full names, both on page streams and nested form XObjects.
for short, full, encode in [
('Fl', 'FlateDecode', zlib.compress),
('AHx', 'ASCIIHexDecode', lambda data: data.hex().encode() + b'>'),
('A85', 'ASCII85Decode', lambda data: base64.a85encode(data) + b'~>'),
]:
for label in (short, full):
for array in (False, True):
writer = PdfWriter()
writer.append(root / 'pages.pdf')
page = writer.pages[0]
encoded = EncodedStreamObject()
encoded._data = encode(page['/Contents'].get_object().get_data())
encoded[NameObject('/Filter')] = ArrayObject([NameObject('/' + label)]) if array else NameObject('/' + label)
page[NameObject('/Contents')] = writer._add_object(encoded)
writer.write(root / f'filter-{label}-{"array" if array else "scalar"}.pdf')
writer = PdfWriter()
writer.append(root / 'form-valid.pdf')
form = writer.pages[0]['/Resources']['/XObject']['/Form'].get_object()
form._data = encode(form.get_data())
form[NameObject('/Filter')] = NameObject('/' + short)
writer.write(root / f'filter-form-{short}.pdf')

for array in (False, True):
writer = PdfWriter()
writer.append(root / 'inflate.pdf')
stream = writer.pages[0]['/Contents'].get_object()
stream[NameObject('/Filter')] = ArrayObject([NameObject('/Fl')]) if array else NameObject('/Fl')
writer.write(root / f'filter-limit-{"array" if array else "scalar"}.pdf')
for label, filters in [('unsupported', ['/LZW']), ('chain', ['/Fl', '/Fl'])]:
writer = PdfWriter()
writer.append(root / 'compressed.pdf')
writer.pages[0]['/Contents'][NameObject('/Filter')] = ArrayObject([NameObject(name) for name in filters])
writer.write(root / f'filter-{label}.pdf')

# A valid XML prefix with forged size AND CRC must not hide trailing inflation.
with zipfile.ZipFile(root / 'body.docx') as source, zipfile.ZipFile(root / 'forged-bomb.docx', 'w', compression=zipfile.ZIP_DEFLATED) as target:
prefix = source.read('word/document.xml')
Expand Down
25 changes: 25 additions & 0 deletions packages/extraction/tests/container-client.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,27 @@ assert.deepEqual(docx.value.segments, [
const form = await send('pdf', readFileSync(`${fixtures}/form-valid.pdf`));
assert.equal(form.status, 200);
assert.match(form.value.segments[0].text, /Form content/);
for (const filter of [
'Fl',
'FlateDecode',
'AHx',
'ASCIIHexDecode',
'A85',
'ASCII85Decode',
]) {
for (const shape of ['scalar', 'array']) {
const name = `filter-${filter}-${shape}.pdf`;
const response = await send('pdf', readFileSync(`${fixtures}/${name}`));
assert.equal(response.status, 200, name);
assert.deepEqual(response.value.segments, result.value.segments, name);
}
}
for (const filter of ['Fl', 'AHx', 'A85']) {
const name = `filter-form-${filter}.pdf`;
const response = await send('pdf', readFileSync(`${fixtures}/${name}`));
assert.equal(response.status, 200, name);
assert.deepEqual(response.value.segments, form.value.segments, name);
}
const nested = await send('docx', readFileSync(`${fixtures}/nested.docx`));
assert.equal(nested.status, 200);
assert.match(
Expand Down Expand Up @@ -211,6 +232,10 @@ for (const [name, expected] of [
assert.equal(response.value.segments[0].text, expected, name);
}
const rejectedFixtures = [
['filter-limit-scalar.pdf', 'pdf', 'DECOMPRESSION_LIMIT'],
['filter-limit-array.pdf', 'pdf', 'DECOMPRESSION_LIMIT'],
['filter-unsupported.pdf', 'pdf', 'UNSUPPORTED_ENCODING'],
['filter-chain.pdf', 'pdf', 'UNSUPPORTED_ENCODING'],
['font-replacement.pdf', 'pdf', 'UNSUPPORTED_ENCODING'],
['font-partial-simple.pdf', 'pdf', 'UNSUPPORTED_ENCODING'],
['font-no-resources.pdf', 'pdf', 'UNSUPPORTED_ENCODING'],
Expand Down
25 changes: 0 additions & 25 deletions packages/extraction/tests/fixtures/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,6 @@ def pdf(name, pages, compressed=False, padding=0):
with (root / name).open('wb') as file:
writer.write(file)

def wrapped_table_pdf():
# Adjacent cells wrap above and below the row label's baseline. Keep every
# word separate even when the extractor keeps the fragments on one line.
writer = PdfWriter()
page = writer.add_blank_page(width=612, height=792)
font = writer._add_object(DictionaryObject({
NameObject('/Type'): NameObject('/Font'), NameObject('/Subtype'): NameObject('/Type1'),
NameObject('/BaseFont'): NameObject('/Helvetica'),
NameObject('/Encoding'): NameObject('/WinAnsiEncoding'),
}))
page[NameObject('/Resources')] = DictionaryObject({NameObject('/Font'): DictionaryObject({NameObject('/F1'): font})})
stream = DecodedStreamObject()
stream.set_data(
b'BT /F1 10 Tf '
b'1 0 0 1 72 700 Tm (Row) Tj '
b'1 0 0 1 160 706 Tm (Alpha) Tj '
b'1 0 0 1 160 694 Tm (Beta) Tj '
b'1 0 0 1 240 706 Tm (Gamma) Tj '
b'1 0 0 1 240 694 Tm (Delta) Tj ET'
)
page[NameObject('/Contents')] = writer._add_object(stream)
with (root / 'wrapped-table.pdf').open('wb') as file:
writer.write(file)

wrapped_table_pdf()
pdf('pages.pdf', ['First page text', 'Second page text'])
pdf('compressed.pdf', ['Compressed page text'], True)
pdf('empty.pdf', [''])
Expand Down
Binary file removed packages/extraction/tests/fixtures/wrapped-table.pdf
Binary file not shown.
12 changes: 10 additions & 2 deletions packages/extraction/worker/extract.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def value(self):
def pdf_segments(data):
import pypdf
from pypdf import filters, _page
from pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject, NullObject, StreamObject
from pypdf.generic import ArrayObject, DecodedStreamObject, DictionaryObject, NameObject, NullObject, StreamObject
from pypdf._cmap import charset_encoding
from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS
from pypdf._text_extraction._text_extractor import TextExtraction
Expand Down Expand Up @@ -106,13 +106,21 @@ def decoded_data(stream):
return value

def decode(stream):
names = stream.get("/Filter", [])
declared = stream.get("/Filter", [])
names = declared
if not isinstance(names, list):
names = [names]
if len(names) > 1 or any(str(name) not in {
"/FlateDecode", "/Fl", "/ASCIIHexDecode", "/AHx", "/ASCII85Decode", "/A85"
} for name in names):
reject("UNSUPPORTED_ENCODING")
# pypdf 7 rejects stream-filter abbreviations. Normalize only the
# supported aliases after enforcing the single-filter boundary, while
# retaining DecodeParms and the bounded decompressor below.
aliases = {"/Fl": "/FlateDecode", "/AHx": "/ASCIIHexDecode", "/A85": "/ASCII85Decode"}
if any(str(name) in aliases for name in names):
normalized = [NameObject(aliases.get(str(name), str(name))) for name in names]
stream[NameObject("/Filter")] = ArrayObject(normalized) if isinstance(declared, list) else normalized[0]
try:
return original(stream)
except Rejected:
Expand Down
Loading