feat(ingestion): implement Phase 2 multi-format intake and raw storage
- Add format validation and inspection for PDF, DOCX, Markdown, Text, HTML, and images - Implement secure decompression defenses (zip bombs, ratio checks) and image dimension limits - Implement FileStore with content-addressable storage and intake repositories - Add unit and integration tests for document intake, format sniffing, and storage roots - Include sample acceptance document fixtures in data/documents/
This commit is contained in:
@@ -0,0 +1,248 @@
|
||||
"""Bounded intake identification, not extraction or evidence quality acceptance."""
|
||||
from io import BytesIO
|
||||
from pathlib import PurePosixPath
|
||||
import re
|
||||
import stat
|
||||
import struct
|
||||
import unicodedata
|
||||
import warnings
|
||||
import zlib
|
||||
from zipfile import ZipFile, BadZipFile, ZIP_STORED, ZIP_DEFLATED
|
||||
|
||||
from .errors import IntakeError
|
||||
|
||||
DOCX_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||
CONTENT_NS = "http://schemas.openxmlformats.org/package/2006/content-types"
|
||||
REL_NS = "http://schemas.openxmlformats.org/package/2006/relationships"
|
||||
WORD_NAMESPACES = ("http://schemas.openxmlformats.org/wordprocessingml/2006/main",
|
||||
"http://purl.oclc.org/ooxml/wordprocessingml/main")
|
||||
MAIN_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
|
||||
|
||||
|
||||
def _zip_payload_bounds(content, member, member_end):
|
||||
"""Derive the physical member span from adjacent local headers, not file_size."""
|
||||
offset = member.header_offset
|
||||
if offset < 0 or offset + 30 > member_end:
|
||||
raise ValueError("Invalid archive local header")
|
||||
signature, version, flags, method, _, _, crc, compressed, expanded, name_length, extra_length = struct.unpack_from(
|
||||
"<4s5H3L2H", content, offset)
|
||||
if (signature != b"PK\x03\x04" or version >= 45 or flags != member.flag_bits
|
||||
or flags & ~0x080e or method != member.compress_type):
|
||||
raise ValueError("Unsupported archive local header")
|
||||
data_start = offset + 30 + name_length + extra_length
|
||||
if data_start > member_end:
|
||||
raise ValueError("Invalid archive local header length")
|
||||
encoding = "utf-8" if flags & 0x800 else "cp437"
|
||||
if content[offset + 30:offset + 30 + name_length].decode(encoding) != member.orig_filename:
|
||||
raise ValueError("Local and central archive names differ")
|
||||
# Refuse ZIP64 fields even when small values would otherwise hide their use.
|
||||
cursor = offset + 30 + name_length
|
||||
while cursor < data_start:
|
||||
if cursor + 4 > data_start:
|
||||
raise ValueError("Invalid archive extra field")
|
||||
kind, length = struct.unpack_from("<2H", content, cursor)
|
||||
cursor += 4 + length
|
||||
if kind == 1 or cursor > data_start:
|
||||
raise ValueError("Unsupported archive extra field")
|
||||
expected = (member.CRC, member.compress_size, member.file_size)
|
||||
if flags & 8:
|
||||
# ZIP32 data descriptors may be signed (16 bytes) or unsigned (12).
|
||||
# Require the descriptor to occupy the entire physical trailing span.
|
||||
if any(value not in (0, wanted) for value, wanted in zip((crc, compressed, expanded), expected)):
|
||||
raise ValueError("Local and central archive metadata differ")
|
||||
for length in (16, 12):
|
||||
data_end = member_end - length
|
||||
if data_end < data_start or data_end - data_start != member.compress_size:
|
||||
continue
|
||||
descriptor = content[data_end:member_end]
|
||||
if length == 16:
|
||||
if descriptor[:4] != b"PK\x07\x08":
|
||||
continue
|
||||
descriptor = descriptor[4:]
|
||||
if struct.unpack("<3L", descriptor) == expected:
|
||||
return data_start, data_end
|
||||
raise ValueError("Invalid archive data descriptor")
|
||||
if (crc, compressed, expanded) != expected or member_end - data_start != member.compress_size:
|
||||
raise ValueError("Invalid archive physical member boundary")
|
||||
return data_start, member_end
|
||||
|
||||
|
||||
def _read_zip_member(content, member, member_end, settings, remaining_bytes, *, retain):
|
||||
"""Bound actual expansion; never use ZipExtFile's declared-size truncation."""
|
||||
start, end = _zip_payload_bounds(content, member, member_end)
|
||||
compressed_length = end - start
|
||||
budget = min(settings.max_docx_member_bytes, remaining_bytes,
|
||||
compressed_length * settings.max_docx_compression_ratio)
|
||||
expanded, crc, retained = 0, 0, bytearray()
|
||||
|
||||
def consume(block):
|
||||
nonlocal expanded, crc
|
||||
expanded += len(block)
|
||||
if expanded > budget:
|
||||
raise ValueError("Archive actual expansion budget exceeded")
|
||||
crc = zlib.crc32(block, crc)
|
||||
if retain:
|
||||
retained.extend(block)
|
||||
|
||||
position = start
|
||||
if member.compress_type == ZIP_STORED:
|
||||
while position < end:
|
||||
stop = min(end, position + 65536, position + budget - expanded + 1)
|
||||
consume(content[position:stop])
|
||||
position = stop
|
||||
else:
|
||||
decoder = zlib.decompressobj(-15)
|
||||
pending = b""
|
||||
while not decoder.eof:
|
||||
if not pending and position < end:
|
||||
stop = min(end, position + 65536)
|
||||
pending = content[position:stop]
|
||||
position = stop
|
||||
# One extra output byte detects overflow promptly, even if both
|
||||
# headers and a descriptor claim a short prefix with its valid CRC.
|
||||
block = decoder.decompress(pending, min(65536, budget - expanded + 1))
|
||||
consume(block)
|
||||
pending = decoder.unconsumed_tail
|
||||
if decoder.eof:
|
||||
if decoder.unused_data or pending or position != end:
|
||||
raise ValueError("Archive compressed stream has trailing bytes")
|
||||
elif not block and not pending and position == end:
|
||||
raise ValueError("Incomplete archive compressed stream")
|
||||
# No flush(): its argument is an allocation hint, not an output bound.
|
||||
if expanded != member.file_size or crc != member.CRC:
|
||||
raise ValueError("Archive full-stream length or CRC mismatch")
|
||||
return expanded, bytes(retained)
|
||||
|
||||
|
||||
def validate_docx(content, settings):
|
||||
from defusedxml.ElementTree import fromstring
|
||||
# Reject ZIP64/multidisk and bound entry count before ZipFile builds its inventory.
|
||||
offset = content.rfind(b"PK\x05\x06", max(0, len(content) - 65557))
|
||||
if not content.startswith(b"PK\x03\x04") or offset < 0 or offset + 22 > len(content):
|
||||
raise ValueError("Missing archive directory")
|
||||
_, disk, directory_disk, disk_count, count, size, start, comment = struct.unpack_from(
|
||||
"<4s4H2LH", content, offset)
|
||||
if (disk or directory_disk or disk_count != count or count == 65535
|
||||
or count > settings.max_docx_entries or start + size != offset
|
||||
or offset + 22 + comment != len(content)):
|
||||
raise ValueError("Unsupported or oversized archive directory")
|
||||
# The EOCD count is untrusted. Walk raw central headers first so a forged
|
||||
# small count cannot cause ZipFile to allocate an unbounded member list.
|
||||
cursor = start
|
||||
for _ in range(count):
|
||||
if cursor + 46 > offset or content[cursor:cursor + 4] != b"PK\x01\x02":
|
||||
raise ValueError("Invalid archive directory entry")
|
||||
name_length, extra_length, comment_length, member_disk = struct.unpack_from("<4H", content, cursor + 28)
|
||||
compressed, expanded = struct.unpack_from("<2L", content, cursor + 20)
|
||||
if (name_length > 1024 or member_disk or compressed == 0xffffffff or expanded == 0xffffffff):
|
||||
raise ValueError("Unsupported archive directory entry")
|
||||
cursor += 46 + name_length + extra_length + comment_length
|
||||
if cursor > offset:
|
||||
raise ValueError("Invalid archive directory length")
|
||||
if cursor != offset:
|
||||
raise ValueError("Archive directory count mismatch")
|
||||
required = {"[Content_Types].xml", "_rels/.rels", "word/document.xml"}
|
||||
xml = {}
|
||||
with ZipFile(BytesIO(content)) as archive:
|
||||
members = archive.infolist()
|
||||
if len(members) != count:
|
||||
raise ValueError("Invalid archive inventory")
|
||||
ordered = sorted(members, key=lambda member: member.header_offset)
|
||||
offsets = [member.header_offset for member in ordered]
|
||||
if not offsets or offsets[0] != 0 or len(set(offsets)) != len(offsets):
|
||||
raise ValueError("Invalid archive member offsets")
|
||||
names, total = set(), 0
|
||||
for index, member in enumerate(ordered):
|
||||
name = member.filename
|
||||
if (name in names or member.orig_filename != name or len(name) > 1024
|
||||
or name.startswith("/") or "\\" in name or ":" in name
|
||||
or ".." in PurePosixPath(name).parts
|
||||
or stat.S_ISLNK(member.external_attr >> 16)
|
||||
or member.flag_bits & ~0x080e or member.compress_type not in (ZIP_STORED, ZIP_DEFLATED)):
|
||||
raise ValueError("Unsupported archive member")
|
||||
names.add(name)
|
||||
member_end = offsets[index + 1] if index + 1 < len(offsets) else start
|
||||
if not member.header_offset < member_end <= start:
|
||||
raise ValueError("Invalid archive member physical span")
|
||||
actual_length, value = _read_zip_member(
|
||||
content, member, member_end, settings,
|
||||
settings.max_docx_expanded_bytes - total, retain=name in required)
|
||||
total += actual_length
|
||||
if name in required:
|
||||
xml[name] = fromstring(value, forbid_dtd=True, forbid_entities=True, forbid_external=True)
|
||||
if not required <= xml.keys():
|
||||
raise ValueError("Missing DOCX package structure")
|
||||
types = xml["[Content_Types].xml"]
|
||||
relationships = xml["_rels/.rels"]
|
||||
document = xml["word/document.xml"]
|
||||
if (types.tag != "{" + CONTENT_NS + "}Types"
|
||||
or not any(e.get("PartName") == "/word/document.xml" and e.get("ContentType") == MAIN_TYPE
|
||||
for e in types.findall("{" + CONTENT_NS + "}Override"))
|
||||
or relationships.tag != "{" + REL_NS + "}Relationships"
|
||||
or not any(e.get("Type") in (
|
||||
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument",
|
||||
"http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument")
|
||||
and e.get("Target") in ("word/document.xml", "/word/document.xml")
|
||||
and e.get("TargetMode", "Internal") == "Internal"
|
||||
for e in relationships.findall("{" + REL_NS + "}Relationship"))
|
||||
or not any(document.tag == "{" + ns + "}document" and document.find("{" + ns + "}body") is not None
|
||||
for ns in WORD_NAMESPACES)):
|
||||
raise ValueError("Invalid DOCX package structure")
|
||||
|
||||
return document
|
||||
|
||||
def validate_image(extension, content, settings):
|
||||
from PIL import Image
|
||||
expected = "PNG" if extension == ".png" else "JPEG"
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(BytesIO(content), formats=[expected]) as image:
|
||||
width, height = image.size
|
||||
if (width <= 0 or height <= 0 or width > settings.max_image_width
|
||||
or height > settings.max_image_height or width * height > settings.max_image_pixels
|
||||
or getattr(image, "n_frames", 1) != 1):
|
||||
raise ValueError("Image resource limit exceeded")
|
||||
image.verify()
|
||||
# JPEG verify alone does not decode pixels; validate bounded decode too.
|
||||
with Image.open(BytesIO(content), formats=[expected]) as image:
|
||||
image.load()
|
||||
return "image/png" if expected == "PNG" else "image/jpeg"
|
||||
|
||||
|
||||
def validate_format(extension, content, settings):
|
||||
if extension == ".pdf":
|
||||
if not re.match(rb"%PDF-[12]\.[0-9](?:\r|\n|\s)", content):
|
||||
raise IntakeError("INVALID_FILE", "PDF signature does not match the file type")
|
||||
return "application/pdf"
|
||||
if extension == ".md":
|
||||
try:
|
||||
decoded = content.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
raise IntakeError("INVALID_FILE", "Markdown must be UTF-8 text") from None
|
||||
if (decoded.lstrip().startswith("%PDF-")
|
||||
or any(unicodedata.category(c) == "Cc" and c not in "\t\r\n" for c in decoded)):
|
||||
raise IntakeError("INVALID_FILE", "Content does not match Markdown text")
|
||||
return "text/markdown"
|
||||
if extension == ".docx":
|
||||
from defusedxml.common import DefusedXmlException
|
||||
valid = False
|
||||
try:
|
||||
validate_docx(content, settings)
|
||||
valid = True
|
||||
except (ValueError, OSError, BadZipFile, RuntimeError, NotImplementedError,
|
||||
SyntaxError, DefusedXmlException, EOFError, zlib.error, struct.error):
|
||||
pass
|
||||
if not valid:
|
||||
raise IntakeError("INVALID_FILE", "Invalid DOCX package or configured archive limit exceeded")
|
||||
return DOCX_MIME
|
||||
if extension in (".jpg", ".jpeg", ".png"):
|
||||
from PIL import Image
|
||||
valid_mime = None
|
||||
try:
|
||||
valid_mime = validate_image(extension, content, settings)
|
||||
except (ValueError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
pass
|
||||
if valid_mime is None:
|
||||
raise IntakeError("INVALID_FILE", "Invalid image or configured image limit exceeded")
|
||||
return valid_mime
|
||||
raise IntakeError("UNSUPPORTED_FILE_TYPE", "Unsupported file format")
|
||||
Reference in New Issue
Block a user