- 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/
140 lines
6.4 KiB
Python
140 lines
6.4 KiB
Python
"""Explicit allowlist, bounded actual-type validation and supplied intake samples."""
|
|
from pathlib import Path
|
|
from zipfile import ZipFile
|
|
from io import BytesIO
|
|
import struct
|
|
import pytest
|
|
from app.modules.documents.intake import IntakeError, prepare_file
|
|
from tests.support.formats import docx_bytes, image_bytes, format_bytes
|
|
|
|
|
|
@pytest.mark.parametrize("extension,mime", [
|
|
(".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"),
|
|
(".jpg", "image/jpeg"), (".jpeg", "image/jpeg"), (".png", "image/png")])
|
|
def test_formats_unicode_and_disabled_policy(tmp_path, settings, extension, mime):
|
|
path = tmp_path / ("\u0633\u0646\u062f\u200c\u4e2d\U0001f600" + extension.upper())
|
|
path.write_bytes(format_bytes(extension))
|
|
result = prepare_file(path, "\u0639\u0646\u0648\u0627\u0646\u200c\u4e2d\U0001f600", settings)
|
|
assert result["mime"] == mime and result["content"] == path.read_bytes()
|
|
assert result["filename"] == path.name
|
|
assert result["title"] == "\u0639\u0646\u0648\u0627\u0646\u200c\u4e2d\U0001f600"
|
|
with pytest.raises(IntakeError) as error:
|
|
prepare_file(path, None, settings.model_copy(update={"accepted_formats": (".md",)}))
|
|
assert error.value.code == "UNSUPPORTED_FILE_TYPE"
|
|
|
|
|
|
@pytest.mark.parametrize("extension,content", [
|
|
(".docx", b"not a zip"), (".docx", image_bytes()), (".docx", b"PK\x03\x04"),
|
|
(".jpg", docx_bytes()), (".jpg", image_bytes("PNG")), (".png", image_bytes()),
|
|
(".jpg", image_bytes()[:-20]), (".png", image_bytes("PNG")[:-20]),
|
|
(".docx", docx_bytes({"word/document.xml": b"not xml"})),
|
|
(".docx", docx_bytes({"../escape": b"x"})),
|
|
(".docx", docx_bytes({"word/document.xml": b'<!DOCTYPE document [<!ENTITY a "secret">]><document>&a;</document>'})),
|
|
(".docx", docx_bytes({"_rels/.rels": b'<Relationships/>'})),
|
|
(".docx", docx_bytes({"[Content_Types].xml": b'<Types/>'})),
|
|
])
|
|
def test_malformed_and_mismatched_formats(tmp_path, settings, extension, content):
|
|
path = tmp_path / ("input" + extension)
|
|
path.write_bytes(content)
|
|
with pytest.raises(IntakeError) as error:
|
|
prepare_file(path, None, settings)
|
|
assert error.value.code == "INVALID_FILE"
|
|
assert error.value.__context__ is None
|
|
|
|
|
|
@pytest.mark.parametrize("limit,value", [
|
|
("max_docx_entries", 2), ("max_docx_member_bytes", 20),
|
|
("max_docx_expanded_bytes", 30), ("max_docx_compression_ratio", 1)])
|
|
def test_archive_limits(tmp_path, settings, limit, value):
|
|
path = tmp_path / "input.docx"
|
|
path.write_bytes(docx_bytes({"word/large.xml": b"x" * 4096}))
|
|
with pytest.raises(IntakeError):
|
|
prepare_file(path, None, settings.model_copy(update={limit: value}))
|
|
|
|
|
|
@pytest.mark.parametrize("change", ["duplicate", "missing", "encrypted", "count", "forged_count", "crc"])
|
|
def test_archive_inventory_integrity(tmp_path, settings, change):
|
|
content = docx_bytes()
|
|
if change in ("duplicate", "missing"):
|
|
output = BytesIO()
|
|
with ZipFile(BytesIO(content)) as original, ZipFile(output, "w") as target:
|
|
for entry in original.infolist():
|
|
if change == "missing" and entry.filename == "word/document.xml":
|
|
continue
|
|
target.writestr(entry.filename, original.read(entry))
|
|
if change == "duplicate":
|
|
with pytest.warns(UserWarning):
|
|
target.writestr("word/document.xml", b"duplicate")
|
|
content = output.getvalue()
|
|
else:
|
|
data = bytearray(content)
|
|
if change == "encrypted":
|
|
central = data.index(b"PK\x01\x02")
|
|
struct.pack_into("<H", data, central + 8, 1)
|
|
elif change == "count":
|
|
end = data.rindex(b"PK\x05\x06")
|
|
struct.pack_into("<HH", data, end + 8, 65535, 65535)
|
|
elif change == "forged_count":
|
|
end = data.rindex(b"PK\x05\x06")
|
|
struct.pack_into("<HH", data, end + 8, 1, 1)
|
|
else:
|
|
central = data.index(b"PK\x01\x02")
|
|
struct.pack_into("<I", data, central + 16, 123)
|
|
content = bytes(data)
|
|
path = tmp_path / "input.docx"
|
|
path.write_bytes(content)
|
|
with pytest.raises(IntakeError):
|
|
prepare_file(path, None, settings)
|
|
|
|
|
|
@pytest.mark.parametrize("limit,value", [("max_image_width", 31), ("max_image_height", 23), ("max_image_pixels", 767)])
|
|
@pytest.mark.parametrize("extension", [".png", ".jpg"])
|
|
def test_image_limits_before_decode(tmp_path, settings, extension, limit, value):
|
|
path = tmp_path / ("input" + extension)
|
|
path.write_bytes(format_bytes(extension))
|
|
with pytest.raises(IntakeError):
|
|
prepare_file(path, None, settings.model_copy(update={limit: value}))
|
|
|
|
|
|
def test_image_bomb_is_safe_error(tmp_path, settings, monkeypatch):
|
|
from PIL import Image
|
|
monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 400)
|
|
path = tmp_path / "input.jpg"
|
|
path.write_bytes(image_bytes())
|
|
with pytest.raises(IntakeError):
|
|
prepare_file(path, None, settings)
|
|
|
|
|
|
def test_supplied_docx_jpeg_samples(settings):
|
|
root = Path(__file__).resolve().parents[2] / "data/documents"
|
|
samples = [root / "-2348240626507047168_13449360743721.docx",
|
|
root / "photo_1_2026-10-06_09-05-11.jpg"]
|
|
# Local sample evidence remains conditional; generated fixtures always run.
|
|
if not all(path.exists() for path in samples):
|
|
pytest.skip("User-supplied samples absent from this checkout")
|
|
for path in samples:
|
|
assert prepare_file(path, None, settings)["content"] == path.read_bytes()
|
|
|
|
|
|
def test_animated_png_is_not_supported(tmp_path, settings):
|
|
from PIL import Image
|
|
output = BytesIO()
|
|
Image.new("RGB", (4, 4), "white").save(output, format="PNG", save_all=True,
|
|
append_images=[Image.new("RGB", (4, 4), "black")])
|
|
path = tmp_path / "animated.png"
|
|
path.write_bytes(output.getvalue())
|
|
with pytest.raises(IntakeError): prepare_file(path, None, settings)
|
|
|
|
|
|
def test_archive_claimed_count_checked_before_inventory_allocation(tmp_path, settings, monkeypatch):
|
|
import app.modules.documents.formats as module
|
|
data = bytearray(docx_bytes())
|
|
end = data.rindex(b"PK\x05\x06")
|
|
struct.pack_into("<HH", data, end + 8, 1, 1)
|
|
path = tmp_path / "forged.docx"
|
|
path.write_bytes(data)
|
|
def forbidden(*args, **kwargs):
|
|
pytest.fail("Invalid directory must fail before ZipFile allocation")
|
|
monkeypatch.setattr(module, "ZipFile", forbidden)
|
|
with pytest.raises(IntakeError): prepare_file(path, None, settings)
|