diff --git a/README.md b/README.md index 7a510ee..b121157 100644 --- a/README.md +++ b/README.md @@ -92,9 +92,10 @@ check(path, Policy(formats={"tiff", "pdf"}, max_pages=50)) | `formats` | jpeg, png, tiff, pdf | the same | What may pass at all. Nothing else is ever allowed, whatever the policy says | | `max_bytes` | 512 MiB | 128 MiB | The file. Checked before anything reads it | | `max_pixels` | 89,478,485 | 50,000,000 | Any one page or frame, decoded. For a PDF page, at `render_dpi`. The default is Pillow's own decompression-bomb threshold, enforced here rather than left to a global | -| `max_pages` | 500 | 100 | Pages of a PDF, frames of a TIFF or animated PNG. Also bounds the header walk itself | +| `max_pages` | 500 | 100 | Pages of a PDF, frames of a TIFF or animated PNG, pictures of a multi-picture JPEG. Also bounds the header walk itself | | `render_dpi` | 200 | 200 | What you will render PDF pages at, so a page's pixels are known before the renderer allocates them | | `name_must_match` | yes | yes | Refuse a JPEG called `.png`. The readers would cope; the lie is what you want to know about | +| `jpeg_frames` | baseline, extended, progressive | the same | How a JPEG's frame may be coded. Lossless, hierarchical and arithmetic frames are legal JPEG that no scanner writes and the decoder's least-exercised code; a lossless frame was the way into a heap overflow in Pillow's JPEG decoder (CVE-2026-112403) | | `allow_encrypted_pdf` | no | no | A scanned book is never encrypted | | `pdfinfo_timeout` | 30 s | 30 s | How long `pdfinfo` may take before the file is refused | @@ -131,7 +132,8 @@ refused scans/report.pdf 1,412 pages; the limit is 500 Exit status 0 when every file passed, 1 when any was refused, 2 when the command could not do its job. `--strict`, `--formats`, `--max-pages`, -`--max-pixels`, `--max-bytes` and `--any-name` adjust the policy; `--json` +`--max-pixels`, `--max-bytes`, `--jpeg-frames` and `--any-name` adjust the +policy; `--json` prints one object per line for a pipeline; `-q` prints only refusals. ## What it does, exactly @@ -145,11 +147,13 @@ prints one object per line for a pipeline; `-q` prints only refusals. unknown format". Refused by name, and no reader of ours runs on it. 3. **Name against contents.** `says PNG, is JPEG`. 4. **The header**, with a reader of its own for each raster format: the - dimensions from a JPEG's frame header, a PNG's `IHDR` (and `acTL` frame - count), and every directory in a TIFF's chain, which is walked with a - limit and a memory of where it has been, so that a chain that loops or - points off the end of the file is a refusal, not a hang. Every read is - bounded and every offset is checked against the file's size. For a PDF, + dimensions, coding and component count from a JPEG's frame header, and + every picture of a multi-picture (MPF) JPEG, each read the same way and + required to match the first; a PNG's `IHDR` (and `acTL` frame count); + and every directory in a TIFF's chain, which is walked with a limit and + a memory of where it has been, so that a chain that loops or points off + the end of the file is a refusal, not a hang. Every read is bounded and + every offset is checked against the file's size. For a PDF, `pdfinfo` reports the page count, whether it is encrypted and, if the count is within the limit, every page's size. 5. **The limits**, against what the header said. @@ -161,8 +165,9 @@ Say this plainly, because a security library carries an implied promise. - **It does not protect against a flaw in the readers you *do* allow.** A crafted JPEG that exploits a bug in your JPEG decoder passes this check, because it is a JPEG of a sensible size. What this library removes is the - attack surface of every format you did not mean to read, and the whole - class of files that are too big to be safe. For the readers you keep: + attack surface of every format you did not mean to read, the whole class + of files that are too big to be safe, and, where the header shows them, + the rare codings a scanner never writes. For the readers you keep: update them, and run them in a boxed process with memory and time limits (a recipe for that is planned; it is deliberately not a dependency). @@ -192,9 +197,11 @@ ruff check . && ruff format --check . && mypy && pytest --cov ``` The tests build the hostile corpus by hand at test time (`tests/corpus.py`): -renamed PostScript, a 100-byte PNG that claims ten billion pixels, a TIFF -with ten thousand frames, a TIFF whose frame chain loops, a PDF of a -thousand pages, a PDF with a page 200 inches wide. Nothing hostile is +renamed PostScript, a 100-byte PNG that claims ten billion pixels, a +lossless JPEG, a multi-picture JPEG whose second picture is four billion +pixels or changes colour mode, a TIFF with ten thousand frames, a TIFF +whose frame chain loops, a PDF of a thousand pages, a PDF with a page 200 +inches wide. Nothing hostile is checked in. The readers are also checked against Pillow's reading of real files, so that they agree with the decoder they stand in front of. diff --git a/src/sillybos/__init__.py b/src/sillybos/__init__.py index 02deb07..7104c6b 100644 --- a/src/sillybos/__init__.py +++ b/src/sillybos/__init__.py @@ -28,7 +28,7 @@ from __future__ import annotations from sillybos.check import Facts, Refused, Verdict, check, require -from sillybos.policy import DEFAULT, FORMATS, STRICT, Policy +from sillybos.policy import DEFAULT, FORMATS, JPEG_FRAMES, STRICT, Policy try: from sillybos._version import __version__ @@ -38,6 +38,7 @@ __all__ = [ "DEFAULT", "FORMATS", + "JPEG_FRAMES", "STRICT", "Facts", "Policy", diff --git a/src/sillybos/check.py b/src/sillybos/check.py index 3b2b6b0..a711160 100644 --- a/src/sillybos/check.py +++ b/src/sillybos/check.py @@ -10,7 +10,8 @@ does not allow is refused by name, and no reader of ours runs on it. 3. Whether its name agrees with its contents. 4. Its header, with the reader for its format (ours for JPEG, PNG and TIFF; - ``pdfinfo`` in a separate process for PDF): dimensions, frames, pages. + ``pdfinfo`` in a separate process for PDF): dimensions, frames, pages, + and how a JPEG is coded. 5. The policy's ceilings against what the header said. Every reason is a sentence an operator can act on, and the verdict carries @@ -25,7 +26,7 @@ from sillybos import headers, sniff from sillybos.pdf import pdf as read_pdf -from sillybos.policy import DEFAULT, FORMATS, Policy +from sillybos.policy import DEFAULT, FORMATS, JPEG_FRAMES, Policy @dataclass(frozen=True) @@ -46,6 +47,8 @@ class Facts: encrypted: Whether a PDF is encrypted. Always ``False`` for an image. pages_exact: ``False`` when the frame walk stopped at the limit, so ``pages`` is a floor, not a count. + coding: How a JPEG's frame is coded, by a name from + :data:`sillybos.JPEG_FRAMES`; ``None`` for the other formats. """ bytes: int @@ -55,6 +58,7 @@ class Facts: max_pixels: int | None encrypted: bool = False pages_exact: bool = True + coding: str | None = None @dataclass(frozen=True) @@ -189,6 +193,7 @@ def _facts(path: Path, fmt: str, f: headers.Reader, size: int, policy: Policy) - header.pages, header.max_pixels if header.complete else None, pages_exact=header.complete, + coding=header.coding, ) @@ -203,4 +208,16 @@ def _against_limits(facts: Facts, policy: Policy) -> list[str]: reasons.append(f"a page of {facts.max_pixels:,} pixels; the limit is {policy.max_pixels:,}") if facts.encrypted and not policy.allow_encrypted_pdf: reasons.append("the PDF is encrypted") + if facts.coding is not None and facts.coding not in policy.jpeg_frames: + allowed = [name for name in JPEG_FRAMES if name in policy.jpeg_frames] + article = "an" if facts.coding[0] in "aeiou" else "a" + reasons.append( + f"{article} {facts.coding} JPEG; the policy allows {_listed(allowed)} frames" + ) return reasons + + +def _listed(names: list[str]) -> str: + if len(names) < 2: + return "".join(names) + return ", ".join(names[:-1]) + " and " + names[-1] diff --git a/src/sillybos/cli.py b/src/sillybos/cli.py index becd1c7..d72f5ad 100644 --- a/src/sillybos/cli.py +++ b/src/sillybos/cli.py @@ -35,6 +35,8 @@ def _policy(args: argparse.Namespace) -> Policy: } if args.formats: changes["formats"] = frozenset(args.formats.split(",")) + if args.jpeg_frames: + changes["jpeg_frames"] = frozenset(args.jpeg_frames.split(",")) if args.any_name: changes["name_must_match"] = False return dataclasses.replace(base, **changes) if changes else base @@ -63,6 +65,15 @@ def build_parser() -> argparse.ArgumentParser: "--max-pixels", type=int, metavar="N", help="most pixels in any one page or frame" ) parser.add_argument("--max-pages", type=int, metavar="N", help="most pages or frames") + parser.add_argument( + "--jpeg-frames", + metavar="LIST", + help=( + "comma-separated JPEG frame codings to allow, from " + "baseline,extended,progressive,lossless,hierarchical,arithmetic " + "(default: the first three)" + ), + ) parser.add_argument( "--any-name", action="store_true", diff --git a/src/sillybos/headers.py b/src/sillybos/headers.py index ca53e29..d916948 100644 --- a/src/sillybos/headers.py +++ b/src/sillybos/headers.py @@ -49,6 +49,9 @@ class Header: max_pixels: The most pixels in any one frame the reader looked at. complete: ``False`` if the walk stopped at the limit, so ``pages`` and ``max_pixels`` describe only the frames it reached. + coding: For a JPEG, how its frame is coded, by a name from + :data:`sillybos.JPEG_FRAMES` (``"baseline"``, ``"progressive"``, + ``"lossless"``, ...). ``None`` for the other formats. """ width: int @@ -56,6 +59,7 @@ class Header: pages: int max_pixels: int complete: bool = True + coding: str | None = None def _read_exactly(f: Reader, n: int, what: str) -> bytes: @@ -74,19 +78,88 @@ def _dimensions(width: int, height: int, what: str) -> None: # --- JPEG ------------------------------------------------------------------- -# Start-of-frame markers, which carry the dimensions. C4 (DHT), C8 (JPG -# extension) and CC (DAC) share the range but are not frames. -_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} +# Start-of-frame markers, which carry the dimensions, and how each codes the +# image. C4 (DHT), C8 (JPG extension) and CC (DAC) share the range but are +# not frames. A scanner writes baseline or progressive frames; the rest are +# legal JPEG that no scanner produces and the decoder's rarest paths, and the +# policy says which may pass. The names are :data:`sillybos.JPEG_FRAMES`. +_FRAME_CODINGS = { + 0xC0: "baseline", + 0xC1: "extended", + 0xC2: "progressive", + 0xC3: "lossless", + 0xC5: "hierarchical", + 0xC6: "hierarchical", + 0xC7: "hierarchical", + 0xC9: "arithmetic", + 0xCA: "arithmetic", + 0xCB: "arithmetic", + 0xCD: "hierarchical", + 0xCE: "hierarchical", + 0xCF: "hierarchical", +} # Markers with no length field. _STANDALONE = {0x01, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8} +_APP2 = 0xE2 +_MPF = b"MPF\x00" +_MP_NUMBER_OF_IMAGES = 0xB001 +_MP_ENTRY = 0xB002 + + +@dataclass(frozen=True) +class _Frame: + width: int + height: int + coding: str + components: int def jpeg(f: Reader, size: int, limit: int) -> Header: - """Read a JPEG's frame header: walk the segments to the first SOF marker.""" - del limit # a JPEG has one frame - f.seek(0) + """Read a JPEG's frame header, and every picture of a multi-picture file. + + The segments are walked to the first SOF marker, which carries the + dimensions, the coding and the component count. An APP2 segment holding + a Multi-Picture Format index (the MPO files that cameras and phones + write, which Pillow steps through as frames) names further pictures by + offset and size. Each is read the same way and counted as a page, and + each must match the first in coding and components, because the decoder + that sized its buffers for the first picture is the one that will decode + the rest. As with a TIFF, the walk stops after ``limit + 1`` pictures. + """ + first, pictures = _frame(f, size, 0, "frame header", index=True) + pages = 1 + max_pixels = first.width * first.height + for number, offset in enumerate(pictures, start=2): + if pages > limit: + return Header(first.width, first.height, pages, max_pixels, False, first.coding) + if not 2 <= offset < size: + raise HeaderError(f"picture {number} lies outside the file") + picture, _ = _frame(f, size, offset, f"picture {number}", index=False) + if picture.coding != first.coding: + raise HeaderError( + f"picture {number} is {picture.coding} where picture 1 is {first.coding}" + ) + if picture.components != first.components: + raise HeaderError( + f"picture {number} has {picture.components} components " + f"where picture 1 has {first.components}" + ) + pages += 1 + max_pixels = max(max_pixels, picture.width * picture.height) + return Header(first.width, first.height, pages, max_pixels, coding=first.coding) + + +def _frame(f: Reader, size: int, start: int, what: str, *, index: bool) -> tuple[_Frame, list[int]]: + """Walk one picture's segments from ``start`` to its frame header. + + Returns the frame and, when ``index`` is set and the picture carries a + Multi-Picture index, the offset in the file of every further picture it + names. + """ + f.seek(start) if _read_exactly(f, 2, "header") != b"\xff\xd8": - raise HeaderError("no JPEG start-of-image marker") + raise HeaderError(f"no JPEG start-of-image marker in the {what}") + pictures: list[int] = [] for _ in range(MAX_SEGMENTS): byte = _read_exactly(f, 1, "segment marker") if byte != b"\xff": @@ -101,23 +174,86 @@ def jpeg(f: Reader, size: int, limit: int) -> Header: (length,) = struct.unpack(">H", _read_exactly(f, 2, "segment length")) if length < 2: raise HeaderError("a segment claims a length shorter than its own length field") - if marker in _SOF: - if length < 7: + if marker in _FRAME_CODINGS: + if length < 8: raise HeaderError("the frame header is too short to hold the dimensions") - _precision, height, width = struct.unpack(">BHH", _read_exactly(f, 5, "frame header")) + _precision, height, width, components = struct.unpack( + ">BHHB", _read_exactly(f, 6, "frame header") + ) if height == 0: # Legal (a DNL marker supplies it later) and never seen in a # scan; refusing it keeps every decoder's rarest path closed. raise HeaderError("the height is deferred to a DNL marker") - _dimensions(width, height, "frame header") - return Header(width, height, 1, width * height) - next_offset = f.tell() + length - 2 + _dimensions(width, height, what) + return _Frame(width, height, _FRAME_CODINGS[marker], components), pictures + payload = f.tell() + next_offset = payload + length - 2 if next_offset > size: raise HeaderError("a segment runs past the end of the file") + if ( + index + and marker == _APP2 + and length >= 2 + len(_MPF) + and _read_exactly(f, len(_MPF), "APP2 segment") == _MPF + ): + if pictures: + raise HeaderError("two multi-picture indexes") + data = _read_exactly(f, length - 2 - len(_MPF), "multi-picture index") + pictures = _mp_index(data, payload + len(_MPF)) f.seek(next_offset) raise HeaderError(f"no frame header in the first {MAX_SEGMENTS} segments") +def _mp_index(data: bytes, base: int) -> list[int]: + """Read the MP Index IFD of a Multi-Picture Format segment. + + ``data`` is the segment after its ``MPF`` identifier: a small TIFF of + its own, whose offsets count from its first byte, which sits at ``base`` + in the file. Returns the offset in the file of every picture after the + first. An index that names one picture, or none, is an ordinary JPEG, + which is how Pillow reads it too. Each entry also carries the picture's + size, which is ignored here as it is by Pillow's reader (and written + wrongly, from the third picture on, by Pillow's writer): a decoder that + never reads a field cannot be steered by it. + """ + if len(data) < 8: + raise HeaderError("the multi-picture index is too short") + endian = {b"II*\x00": "<", b"MM\x00*": ">"}.get(data[:4]) + if endian is None: + raise HeaderError("the multi-picture index has no byte-order mark") + (offset,) = struct.unpack(endian + "I", data[4:8]) + if offset + 2 > len(data): + raise HeaderError("the multi-picture index lies outside its segment") + (count,) = struct.unpack(endian + "H", data[offset : offset + 2]) + if offset + 2 + count * 12 > len(data): + raise HeaderError("the multi-picture index runs past its segment") + number = 1 + entries: list[tuple[int, int, int, int, int]] = [] + for position in range(offset + 2, offset + 2 + count * 12, 12): + tag, _kind, n, raw = struct.unpack(endian + "HHI4s", data[position : position + 12]) + if tag == _MP_NUMBER_OF_IMAGES: + (number,) = struct.unpack(endian + "I", raw) + elif tag == _MP_ENTRY: + (at,) = struct.unpack(endian + "I", raw) + if n % 16 or at + n > len(data): + raise HeaderError("the multi-picture entries lie outside their segment") + entries = [ + struct.unpack(endian + "IIIHH", data[at + k : at + k + 16]) for k in range(0, n, 16) + ] + if number <= 1 and len(entries) <= 1: + return [] + if number != len(entries): + raise HeaderError( + f"the multi-picture index names {number:,} pictures but lists {len(entries):,}" + ) + pictures = [] + for position, (attribute, _length, offset, _dep1, _dep2) in enumerate(entries[1:], start=2): + if (attribute >> 24) & 0x07: + raise HeaderError(f"picture {position} is not coded as JPEG") + pictures.append(base + offset) + return pictures + + # --- PNG -------------------------------------------------------------------- diff --git a/src/sillybos/policy.py b/src/sillybos/policy.py index e126c15..24f06d1 100644 --- a/src/sillybos/policy.py +++ b/src/sillybos/policy.py @@ -16,6 +16,18 @@ Everything else is refused by name. Adding a format is adding attack surface, so one is added only when someone shows a scan in it.""" +JPEG_FRAMES: tuple[str, ...] = ( + "baseline", + "extended", + "progressive", + "lossless", + "hierarchical", + "arithmetic", +) +"""Every way a JPEG frame can be coded, as its SOF marker says. A scanner +writes the first three. The rest are legal, rare, and the decoder's least +exercised code.""" + MIB = 1024 * 1024 @@ -45,6 +57,13 @@ class Policy: ``.png``). The readers would cope, but a file whose name lies is not one to trust, and the mismatch is the first thing an operator wants to know. + jpeg_frames: Which of :data:`JPEG_FRAMES` may pass. The default is + what a scanner writes: baseline, extended and progressive. A + lossless, hierarchical or arithmetic-coded frame goes down a + path of the decoder that almost no file exercises; a lossless + frame was the way into a heap overflow in Pillow's JPEG decoder + (CVE-2026-112403). A multi-picture JPEG's pictures count as + pages and are each read. allow_encrypted_pdf: Pass a PDF that ``pdfinfo`` reports as encrypted. A scanned book never is, so the default refuses. pdfinfo_timeout: Seconds to give ``pdfinfo`` before giving up on a @@ -58,6 +77,9 @@ class Policy: max_pages: int = 500 render_dpi: int = 200 name_must_match: bool = True + jpeg_frames: frozenset[str] = field( + default_factory=lambda: frozenset({"baseline", "extended", "progressive"}) + ) allow_encrypted_pdf: bool = False pdfinfo_timeout: float = 30.0 @@ -69,6 +91,14 @@ def __post_init__(self) -> None: ) if not self.formats: raise ValueError("a policy must allow at least one format") + unknown = set(self.jpeg_frames) - set(JPEG_FRAMES) + if unknown: + raise ValueError( + f"unknown JPEG frame coding(s) {sorted(unknown)}; " + f"the codings are {', '.join(JPEG_FRAMES)}" + ) + if not self.jpeg_frames: + raise ValueError("a policy must allow at least one JPEG frame coding") for name in ("max_bytes", "max_pixels", "max_pages", "render_dpi"): if getattr(self, name) < 1: raise ValueError(f"{name} must be at least 1") diff --git a/tests/corpus.py b/tests/corpus.py index a4fe277..3c4085d 100644 --- a/tests/corpus.py +++ b/tests/corpus.py @@ -44,13 +44,87 @@ def _segment(marker: int, payload: bytes) -> bytes: return bytes([0xFF, marker]) + struct.pack(">H", len(payload) + 2) + payload -def jpeg(width: int, height: int, *, before_sof: bytes = b"", sof: bool = True) -> bytes: - """A JPEG header: SOI, a JFIF APP0, optional padding segments, a baseline SOF0.""" +def jpeg( + width: int, + height: int, + *, + before_sof: bytes = b"", + sof: bool = True, + marker: int = 0xC0, + components: int = 1, +) -> bytes: + """A JPEG header: SOI, a JFIF APP0, optional padding segments, a SOF (baseline by default).""" app0 = _segment(0xE0, b"JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00") - frame = _segment(0xC0, struct.pack(">BHHB", 8, height, width, 1) + b"\x01\x11\x00") + layout = b"".join(bytes([n + 1, 0x11, 0]) for n in range(components)) + frame = _segment(marker, struct.pack(">BHHB", 8, height, width, components) + layout) return b"\xff\xd8" + app0 + before_sof + (frame if sof else b"") + b"\xff\xda\x00\x02\xff\xd9" +_MP_HEADER_AT = 2 + 18 + 4 + 4 +"""Where the MP header starts in a picture built here: after SOI, APP0, the +APP2 marker and length, and the ``MPF`` identifier. Its offsets count from here.""" + + +def mpo( + pictures: list[tuple[int, int]], + *, + markers: list[int] | None = None, + components: list[int] | None = None, + declared: int | None = None, + stray: bool = False, + not_jpeg: bool = False, + index: bytes | None = None, +) -> bytes: + """A multi-picture JPEG: the first picture carries an MP index naming the rest. + + Each picture is a :func:`jpeg` header; ``markers`` and ``components`` + give each its SOF marker and component count. ``declared`` overrides + the picture count the index states; ``stray`` points the last picture + past the end of the file; ``not_jpeg`` flags the second picture's data + format as something other than JPEG; ``index`` replaces the whole MP + index (after the ``MPF`` identifier) with the given bytes. + """ + n = len(pictures) + markers = markers or [0xC0] * n + components = components or [1] * n + data_at = 8 + 2 + 3 * 12 + 4 # MP header, then the three-entry index, then the entries + + def build(entries: bytes) -> bytes: + return ( + b"II*\x00" + + struct.pack(" bytes: """``n`` empty comment segments, to pad a header out.""" return _segment(0xFE, b"") * n diff --git a/tests/test_check.py b/tests/test_check.py index 70da2c7..76402ae 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -86,6 +86,37 @@ def test_a_pixel_bomb(self, tmp_path: Path) -> None: assert verdict.reasons == ("a page of 10,000,000,000 pixels; the limit is 89,478,485",) assert verdict.facts is not None and verdict.facts.max_pixels == 10_000_000_000 + def test_a_lossless_jpeg(self, tmp_path: Path) -> None: + verdict = check(corpus.write(tmp_path / "scan.jpg", corpus.jpeg(10, 10, marker=0xC3))) + assert verdict.reasons == ( + "a lossless JPEG; the policy allows baseline, extended and progressive frames", + ) + assert verdict.facts is not None and verdict.facts.coding == "lossless" + + def test_the_policy_can_allow_a_coding(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.jpg", corpus.jpeg(10, 10, marker=0xC9)) + assert check(path, Policy(jpeg_frames=frozenset({"arithmetic"}))).ok + verdict = check(path, Policy(jpeg_frames=frozenset({"baseline"}))) + assert verdict.reasons == ("an arithmetic JPEG; the policy allows baseline frames",) + + def test_a_multi_picture_jpeg_whose_second_picture_is_a_bomb(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.jpg", corpus.mpo([(10, 10), (65_535, 65_535)])) + verdict = check(path) + assert verdict.reasons == ("a page of 4,294,836,225 pixels; the limit is 89,478,485",) + assert verdict.facts is not None and verdict.facts.pages == 2 + + def test_a_multi_picture_jpeg_that_changes_mode(self, tmp_path: Path) -> None: + path = corpus.write( + tmp_path / "scan.jpg", corpus.mpo([(10, 10), (10, 10)], components=[1, 3]) + ) + assert check(path).reasons == ( + "the header could not be read: picture 2 has 3 components where picture 1 has 1", + ) + + def test_a_multi_picture_jpeg_with_too_many_pictures(self, tmp_path: Path) -> None: + path = corpus.write(tmp_path / "scan.jpg", corpus.mpo([(10, 10)] * 4)) + assert check(path, Policy(max_pages=3)).reasons == ("4 pages; the limit is 3",) + def test_a_tiff_with_ten_thousand_frames(self, tmp_path: Path) -> None: verdict = check(corpus.write(tmp_path / "frames.tif", corpus.tiff([(10, 10)] * 10_000))) assert verdict.reasons == ("more than 500 pages, which is the limit",) @@ -182,6 +213,8 @@ def test_presets(self) -> None: [ ({"formats": frozenset({"webp"})}, "unknown format"), ({"formats": frozenset()}, "at least one format"), + ({"jpeg_frames": frozenset({"baseline", "mpeg"})}, "unknown JPEG frame coding"), + ({"jpeg_frames": frozenset()}, "at least one JPEG frame coding"), ({"max_pages": 0}, "max_pages must be at least 1"), ({"pdfinfo_timeout": 0}, "must be positive"), ], diff --git a/tests/test_cli.py b/tests/test_cli.py index 6ac0f09..3bb9330 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -42,6 +42,9 @@ def test_options_adjust_the_policy(tmp_path: Path) -> None: jpeg_called_png = corpus.write(tmp_path / "lie.png", corpus.jpeg(10, 10)) assert main(["--max-pixels", "50", str(png)]) == 1 assert main(["--formats", "jpeg,tiff", str(png)]) == 1 + lossless = corpus.write(tmp_path / "lossless.jpg", corpus.jpeg(10, 10, marker=0xC3)) + assert main([str(lossless)]) == 1 + assert main(["--jpeg-frames", "baseline,lossless", str(lossless)]) == 0 assert main(["--any-name", str(jpeg_called_png)]) == 0 assert main(["--strict", "--max-bytes", "10", str(png)]) == 1 diff --git a/tests/test_headers.py b/tests/test_headers.py index 8e4204a..9095980 100644 --- a/tests/test_headers.py +++ b/tests/test_headers.py @@ -3,11 +3,12 @@ from __future__ import annotations import io +import struct import pytest from PIL import Image -from sillybos import headers +from sillybos import JPEG_FRAMES, headers from sillybos.headers import HeaderError from tests import corpus @@ -18,7 +19,9 @@ def read(fmt: str, data: bytes, limit: int = 500) -> headers.Header: class TestJpeg: def test_reads_the_dimensions_from_the_frame_header(self) -> None: - assert read("jpeg", corpus.jpeg(4000, 6000)) == headers.Header(4000, 6000, 1, 24_000_000) + assert read("jpeg", corpus.jpeg(4000, 6000)) == headers.Header( + 4000, 6000, 1, 24_000_000, coding="baseline" + ) def test_skips_segments_before_the_frame(self) -> None: data = corpus.jpeg(30, 20, before_sof=corpus.jpeg_padding(50)) @@ -26,7 +29,87 @@ def test_skips_segments_before_the_frame(self) -> None: def test_a_progressive_frame_counts_too(self) -> None: data = corpus.jpeg(30, 20).replace(b"\xff\xc0", b"\xff\xc2") - assert read("jpeg", data).height == 20 + assert read("jpeg", data) == headers.Header(30, 20, 1, 600, coding="progressive") + + @pytest.mark.parametrize( + ("marker", "coding"), + [ + (0xC0, "baseline"), + (0xC1, "extended"), + (0xC2, "progressive"), + (0xC3, "lossless"), + (0xC5, "hierarchical"), + (0xC7, "hierarchical"), + (0xC9, "arithmetic"), + (0xCB, "arithmetic"), + (0xCF, "hierarchical"), + ], + ) + def test_names_the_frame_coding(self, marker: int, coding: str) -> None: + assert read("jpeg", corpus.jpeg(30, 20, marker=marker)).coding == coding + + def test_every_coding_name_is_one_the_policy_knows(self) -> None: + assert set(headers._FRAME_CODINGS.values()) <= set(JPEG_FRAMES) + + def test_reads_every_picture_of_a_multi_picture_file(self) -> None: + data = corpus.mpo([(30, 20), (40, 50), (10, 10)]) + assert read("jpeg", data) == headers.Header(30, 20, 3, 2000, coding="baseline") + + def test_an_index_naming_one_picture_is_an_ordinary_jpeg(self) -> None: + assert read("jpeg", corpus.mpo([(30, 20)])).pages == 1 + + def test_stops_walking_pictures_at_the_limit(self) -> None: + data = corpus.mpo([(10, 10)] * 12) + header = read("jpeg", data, limit=5) + assert header.pages == 6 and not header.complete + assert read("jpeg", data).pages == 12 + + @pytest.mark.parametrize( + ("data", "reason"), + [ + (corpus.mpo([(10, 10), (0, 10)]), "picture 2 gives a zero width or height"), + (corpus.mpo([(10, 10), (10, 10)], markers=[0xC0, 0xC2]), "picture 2 is progressive"), + (corpus.mpo([(10, 10), (10, 10)], components=[1, 3]), "picture 2 has 3 components"), + (corpus.mpo([(10, 10), (10, 10)], declared=3), "names 3 pictures but lists 2"), + (corpus.mpo([(10, 10), (10, 10)], stray=True), "picture 2 lies outside the file"), + (corpus.mpo([(10, 10), (10, 10)], not_jpeg=True), "picture 2 is not coded as JPEG"), + (corpus.mpo([(10, 10), (10, 10)], index=b"II*\x00"), "index is too short"), + (corpus.mpo([(10, 10), (10, 10)], index=b"XX*\x00" + b"\x00" * 4), "byte-order"), + ( + corpus.mpo([(10, 10), (10, 10)], index=b"II*\x00" + struct.pack(" None: + with pytest.raises(HeaderError, match=reason): + read("jpeg", data) + + def test_a_second_picture_that_is_not_a_jpeg(self) -> None: + data = corpus.mpo([(10, 10), (10, 10)]) + second = data.rindex(b"\xff\xd8") + broken = data[:second] + b"\x00\x00" + data[second + 2 :] + with pytest.raises(HeaderError, match="no JPEG start-of-image marker in the picture 2"): + read("jpeg", broken) + + def test_two_indexes_are_refused(self) -> None: + data = corpus.mpo([(10, 10), (10, 10)]) + app2 = data[20 : 20 + 2 + struct.unpack(">H", data[22:24])[0]] + with pytest.raises(HeaderError, match="two multi-picture indexes"): + read("jpeg", data[:20] + app2 + data[20:]) @pytest.mark.parametrize( ("data", "reason"), @@ -122,7 +205,8 @@ def test_single_images(self, fmt: str, mode: str) -> None: buffer = io.BytesIO() Image.new(mode, (123, 45)).save(buffer, format=fmt) data = buffer.getvalue() - assert read(fmt.lower(), data) == headers.Header(123, 45, 1, 123 * 45) + coding = "baseline" if fmt == "JPEG" else None + assert read(fmt.lower(), data) == headers.Header(123, 45, 1, 123 * 45, coding=coding) def test_a_multi_frame_tiff(self) -> None: buffer = io.BytesIO() @@ -139,4 +223,17 @@ def test_a_progressive_jpeg_and_an_exif_jpeg(self) -> None: exif = image.getexif() exif[0x0110] = "a camera" image.save(buffer, format="JPEG", progressive=True, exif=exif) - assert read("jpeg", buffer.getvalue()).width == 64 + assert read("jpeg", buffer.getvalue()) == headers.Header( + 64, 32, 1, 2048, coding="progressive" + ) + + def test_a_multi_picture_jpeg(self) -> None: + buffer = io.BytesIO() + first, *rest = [Image.new("RGB", (20 + i, 30)) for i in range(3)] + first.save(buffer, format="MPO", save_all=True, append_images=rest) + header = read("jpeg", buffer.getvalue()) + with Image.open(buffer) as image: + assert header.pages == getattr(image, "n_frames", 1) == 3 + image.seek(2) + assert header.max_pixels == image.width * image.height == 22 * 30 + assert header.coding == "baseline"