okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

waveringanaserve tests: bring back the DeepSeek V4.1 cases upstream cut with the enginecded60248

main
4.3 KiB109 linesraw
1"""#1229: a phone JPEG stored turned (EXIF Orientation 6 or 8) is turned upright before the vision encoder reads it."""
2import io
3import unittest
4from unittest import mock
5
6from serve.server import Vision
7
8try:
9    from PIL import Image
10except ImportError:                 # Pillow is optional: the image then goes through as it was
11    Image = None
12
13
14def jpeg(size, orientation=None) -> bytes:
15    im = Image.new("RGB", size, (200, 30, 30))
16    exif = Image.Exif()
17    if orientation is not None:
18        exif[0x0112] = orientation
19    out = io.BytesIO()
20    im.save(out, format="JPEG", exif=exif)
21    return out.getvalue()
22
23
24@unittest.skipIf(Image is None, "Pillow is not installed")
25class ExifOrientation(unittest.TestCase):
26    def test_a_turned_jpeg_comes_out_upright_as_a_png(self):
27        for tag in (6, 8):
28            out = Vision.normalize(jpeg((40, 20), tag))
29            self.assertEqual(out[:8], b"\x89PNG\r\n\x1a\n")
30            self.assertEqual(Image.open(io.BytesIO(out)).size, (20, 40))
31
32    def test_a_jpeg_without_the_tag_or_with_tag_1_passes_through_unchanged(self):
33        for tag in (None, 1):
34            data = jpeg((40, 20), tag)
35            self.assertIs(Vision.normalize(data), data)
36
37    def test_png_passes_through(self):
38        out = io.BytesIO()
39        Image.new("RGB", (4, 4)).save(out, format="PNG")
40        self.assertEqual(Vision.normalize(out.getvalue()), out.getvalue())
41
42    def test_a_broken_jpeg_is_left_as_it_was_sent(self):
43        data = b"\xff\xd8\xff" + b"not a jpeg"
44        self.assertEqual(Vision.normalize(data), data)
45
46
47@unittest.skipIf(Image is None, "Pillow is not installed")
48class DecoderAllowlist(unittest.TestCase):
49    """GHSA-78g4-xqwv-q3g8 (#4220): a crafted JPEG 2000 reached OpenJPEG's heap overflow through Image.open().load(), because
50    Pillow picks the decoder by the file's first bytes.  Only the formats the picture reader documents are opened."""
51
52    @staticmethod
53    def sample(fmt, **kw) -> bytes:
54        out = io.BytesIO()
55        Image.new("RGB", (16, 8), (10, 120, 200)).save(out, format=fmt, **kw)
56        return out.getvalue()
57
58    def test_a_jpeg_2000_picture_is_refused_before_any_decoder_runs(self):
59        try:
60            data = self.sample("JPEG2000")
61        except (KeyError, OSError, ValueError):
62            self.skipTest("this Pillow cannot write JPEG 2000")
63        with mock.patch.object(Image.Image, "load", side_effect=AssertionError("the JPEG 2000 decoder ran")):
64            with self.assertRaises(ValueError) as caught:
65                Vision.normalize(data)
66        self.assertIn("could not be read", str(caught.exception))
67
68    def test_other_formats_outside_the_list_are_refused_too(self):
69        for fmt in ("PPM", "ICO", "TGA"):
70            with self.subTest(fmt):
71                with self.assertRaises(ValueError):
72                    Vision.normalize(self.sample(fmt))
73
74    def test_the_documented_formats_still_become_a_png(self):
75        for fmt, kw in (("WEBP", {}), ("TIFF", {}), ("GIF", {}), ("PNG", {})):
76            with self.subTest(fmt):
77                data = self.sample(fmt, **kw)
78                out = Vision.normalize(data)
79                self.assertEqual(Image.open(io.BytesIO(out)).size, (16, 8))
80
81    def test_a_phone_mpo_file_is_still_read_and_turned(self):
82        a, b = Image.new("RGB", (40, 20), (200, 30, 30)), Image.new("RGB", (40, 20), (30, 200, 30))
83        exif = Image.Exif()
84        exif[0x0112] = 6
85        out = io.BytesIO()
86        a.save(out, format="MPO", save_all=True, append_images=[b], exif=exif)
87        self.assertEqual(Image.open(io.BytesIO(out.getvalue())).format, "MPO")
88        self.assertEqual(Image.open(io.BytesIO(Vision.normalize(out.getvalue()))).size, (20, 40))
89
90    def test_the_exif_probe_and_both_decoders_pass_the_list(self):
91        seen = []
92        real = Image.open
93
94        def spy(*a, **kw):
95            seen.append(kw.get("formats"))
96            return real(*a, **kw)
97
98        data = self.sample("WEBP")
99        with mock.patch.object(Image, "open", spy):
100            Vision.normalize(data)
101            Vision._exif_rotated(jpeg((8, 8), 6))
102            from serve.ds_pictures import DsPictures
103            DsPictures.decode(data)
104        self.assertEqual(len(seen), 3)
105        self.assertTrue(all(f and "JPEG2000" not in f and "JPEG" in f for f in seen), seen)
106
107
108if __name__ == "__main__":
109    unittest.main()