fix: a hostile PDF cannot hold the scanner: bounded DPI reading and a stuck scan is reported
All checks were successful
Build and deploy / Validate source (push) Successful in 8s
Build and deploy / Integration suite on a real stack (push) Successful in 8m38s
Build and deploy / Secret scan and release gate (push) Successful in 7s
Build and deploy / Publish images (push) Successful in 1m19s

The DPI of a stored PDF is read in a subprocess killed after
PDF_MAX_SECONDS + 5; inside it, only image draws count toward
PDF_MAX_DRAWS (heavy vector art still reads), content streams are parsed
once per object, and the deadline is checked every 1000 operators. A scan
busy for more than SCAN_STUCK_SECONDS marks the scanner unhealthy and logs
one error to Sentry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Cauê Faleiros
2026-11-30 10:50:14 -03:00
parent 37d747697a
commit 7e33e6fb1d
4 changed files with 191 additions and 37 deletions

View File

@@ -32,6 +32,14 @@ PDF_VECTOR_DPI = 300
# grade them, so neither does this.
PDF_MAX_BYTES = 150 * 1048576
HEAD_BYTES = 1048576
# How much of a PDF's drawing is walked for its DPI: images and forms drawn
# (Do), however many paths a vector page has. A page whose forms draw other
# forms, ten times each, eight deep, is 10^8 draws in a 2 KB file: it
# held the scanner's one thread for hours and every upload behind it
# (security review, 2026-11-27). Past either limit the DPI is unknown, as for
# a format this cannot read, and the order is reviewed by a person.
PDF_MAX_DRAWS = 5000
PDF_MAX_SECONDS = 10
# Rounding in the browser and here can differ by a point on the same file.
TOLERANCE = 2
@@ -84,10 +92,27 @@ def _multiply(a, b):
a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]]
class _TooMuch(Exception):
"""The PDF's drawing is larger than PDF_MAX_DRAWS or PDF_MAX_SECONDS."""
def pdf_dpi(path):
"""The page's area-weighted image DPI, 300 for vectors only, None if the
file is not a one-page PDF this can read."""
file is not a one-page PDF this can read, or draws more than it is worth
walking (PDF_MAX_DRAWS, PDF_MAX_SECONDS)."""
import time
import pikepdf
deadline = time.monotonic() + PDF_MAX_SECONDS
steps = [0]
parsed = {}
def instructions_of(stream):
# A form drawn many times is read once.
key = stream.objgen if stream.objgen != (0, 0) else id(stream)
if key not in parsed:
parsed[key] = pikepdf.parse_content_stream(stream)
return parsed[key]
try:
with pikepdf.open(path) as pdf:
if len(pdf.pages) != 1:
@@ -99,7 +124,9 @@ def pdf_dpi(path):
def walk(resources, instructions, ctm, depth):
stack = []
xobjects = resources.get('/XObject', {}) if resources is not None else {}
for operands, operator in instructions:
for count, (operands, operator) in enumerate(instructions):
if count % 1000 == 0 and time.monotonic() > deadline:
raise _TooMuch
op = str(operator)
if op == 'q':
stack.append(ctm)
@@ -108,6 +135,9 @@ def pdf_dpi(path):
elif op == 'cm':
ctm = _multiply(ctm, [float(v) for v in operands])
elif op == 'Do' and operands:
steps[0] += 1
if steps[0] > PDF_MAX_DRAWS or time.monotonic() > deadline:
raise _TooMuch
xobject = xobjects.get(str(operands[0]))
if xobject is None:
continue
@@ -120,9 +150,14 @@ def pdf_dpi(path):
elif subtype == '/Form' and depth < 8:
matrix = [float(v) for v in xobject.get('/Matrix', [1, 0, 0, 1, 0, 0])]
walk(xobject.get('/Resources', resources),
pikepdf.parse_content_stream(xobject), _multiply(ctm, matrix), depth + 1)
instructions_of(xobject), _multiply(ctm, matrix), depth + 1)
walk(page.obj.get('/Resources'), pikepdf.parse_content_stream(page), [1, 0, 0, 1, 0, 0], 0)
except _TooMuch:
import logging
logging.warning('PDF %s draws more than %s images and forms, or takes over %s s: its DPI is left unknown',
os.path.basename(path), PDF_MAX_DRAWS, PDF_MAX_SECONDS)
return None
except Exception:
return None
found = [(dpi, area) for dpi, area in found if dpi > 0]
@@ -132,14 +167,47 @@ def pdf_dpi(path):
return js_round(sum(dpi * area for dpi, area in found) / total)
def _pdf_dpi_child(result, path):
result.put(pdf_dpi(path))
def bounded_pdf_dpi(path):
"""pdf_dpi in a process of its own, ended past PDF_MAX_SECONDS: the PDF
library itself can be held by a file (a huge compressed stream), where
pdf_dpi's own limits cannot reach. None when it did not finish."""
import multiprocessing
from queue import Empty
context = multiprocessing.get_context('spawn')
result = context.Queue()
process = context.Process(target=_pdf_dpi_child, args=(result, path))
process.start()
try:
process.join(PDF_MAX_SECONDS + 5)
if process.is_alive():
process.kill()
process.join()
import logging
logging.warning('PDF %s took over %s s to read: its DPI is left unknown',
os.path.basename(path), PDF_MAX_SECONDS + 5)
return None
try:
return result.get(timeout=5)
except Empty:
return None
finally:
result.close()
result.join_thread()
def stored_pdf_dpi(storage, row):
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES."""
"""A stored PDF's DPI, read once; None when it is above PDF_MAX_BYTES or
takes too long to read (bounded_pdf_dpi)."""
if row['size'] > PDF_MAX_BYTES:
return None
with tempfile.NamedTemporaryFile(suffix='.pdf') as handle:
storage.client.download_fileobj(storage.bucket, row['object_key'], handle)
handle.flush()
return pdf_dpi(handle.name)
return bounded_pdf_dpi(handle.name)
class Files: