"""Full raw-stream integrity and bounded rejection of forged ZIP declarations.""" from io import BytesIO from zipfile import ZipFile import pytest from app.modules.documents.intake import IntakeError, prepare_file from tests.support.formats import raw_docx @pytest.mark.parametrize("budget", ["member", "aggregate", "ratio"]) @pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"]) def test_forged_prefix_cannot_bypass_expansion_budgets(tmp_path, settings, budget, descriptor): payload = b"p" * 64 + b"x" * (1024 * 1024) content = raw_docx(payload, declared_length=64, descriptor=descriptor) # Demonstrate the reviewed ZipExtFile truncation and dishonest prefix CRC. with ZipFile(BytesIO(content)) as archive: assert archive.read("word/extra.bin") == payload[:64] overrides = {"member": {"max_docx_member_bytes": 4096}, "aggregate": {"max_docx_expanded_bytes": 2000}, "ratio": {"max_docx_compression_ratio": 20}}[budget] path = tmp_path / "forged.docx" path.write_bytes(content) with pytest.raises(IntakeError): prepare_file(path, None, settings.model_copy(update=overrides)) @pytest.mark.parametrize("method", [0, 8]) @pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"]) def test_stored_and_deflated_descriptor_acceptance(tmp_path, settings, method, descriptor): path = tmp_path / "valid.docx" path.write_bytes(raw_docx(method=method, descriptor=descriptor)) assert prepare_file(path, None, settings)["mime"].endswith("wordprocessingml.document") @pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"]) @pytest.mark.parametrize("fault", ["short_length", "truncated", "trailing", "concatenated", "stored_short", "full_crc"]) def test_full_stream_length_crc_completion_and_boundaries(tmp_path, settings, descriptor, fault): kwargs = {"descriptor": descriptor} if fault == "full_crc": kwargs["crc_prefix_length"] = 4 if fault == "short_length": kwargs["declared_length"] = 4 if fault == "stored_short": kwargs.update(method=0, declared_length=4) if fault == "truncated": kwargs["truncate"] = 1 if fault == "trailing": kwargs["compressed_suffix"] = b"extra bytes" if fault == "concatenated": kwargs["compressed_suffix"] = b"\x03\x00" path = tmp_path / "invalid.docx" path.write_bytes(raw_docx(b"faithful whole member", **kwargs)) with pytest.raises(IntakeError): prepare_file(path, None, settings) @pytest.mark.parametrize("method", [0, 8]) @pytest.mark.parametrize("descriptor", [None, "signed", "unsigned"]) def test_multiblock_crc_and_member_completion(tmp_path, settings, method, descriptor): import random path = tmp_path / "multiblock.docx" path.write_bytes(raw_docx(random.Random(17).randbytes(220000), method=method, descriptor=descriptor)) assert prepare_file(path, None, settings)["content"] == path.read_bytes() @pytest.mark.parametrize("method,budget", [(0, "member"), (0, "aggregate"), (8, "member"), (8, "aggregate"), (8, "ratio")]) def test_actual_budget_stops_promptly_with_bounded_output(tmp_path, settings, monkeypatch, method, budget): import zlib from app.modules.documents.formats import validate_docx payload = b"prefix" * 12 + b"x" * (8 * 1024 * 1024) content = raw_docx(payload, method=method, declared_length=64) overrides = {"member": {"max_docx_member_bytes": 4096}, "aggregate": {"max_docx_expanded_bytes": 2000}, "ratio": {"max_docx_compression_ratio": 20}}[budget] configured = settings.model_copy(update=overrides) original, emitted = zlib.decompressobj, [] class BoundedDecoder: def __init__(self, *args): self.decoder = original(*args) self.output = 0 emitted.append(self) def decompress(self, data, max_length=0): assert 0 < max_length <= 65536 result = self.decoder.decompress(data, max_length) self.output += len(result) return result def __getattr__(self, name): return getattr(self.decoder, name) def flush(self, *args): pytest.fail("Flush must not bypass output bounds") monkeypatch.setattr(zlib, "decompressobj", BoundedDecoder) with pytest.raises(ValueError, match="actual expansion budget"): validate_docx(content, configured) if method == 8: target = emitted[-1] if budget == "member": assert target.output <= 4097 if budget == "aggregate": assert sum(item.output for item in emitted) <= 2001 if budget == "ratio": with ZipFile(BytesIO(content)) as archive: bound = archive.getinfo("word/extra.bin").compress_size * 20 assert target.output <= bound + 1 assert target.output < len(payload) // 10 @pytest.mark.parametrize("method", [0, 8]) @pytest.mark.parametrize("descriptor", ["signed", "unsigned"]) @pytest.mark.parametrize("field", [0, 1, 2]) def test_descriptor_crc_and_sizes_are_checked(tmp_path, settings, method, descriptor, field): import struct content = bytearray(raw_docx(method=method, descriptor=descriptor)) end = content.rindex(b"PK\x05\x06") central_start = struct.unpack_from("