forked from mtusi2026/mtusi2026lab4
289 lines
13 KiB
Python
289 lines
13 KiB
Python
"""Разбор изображений без сервера. Запускается внутри образа API (make test-images): нужен Pillow."""
|
|
import io
|
|
import random
|
|
import struct
|
|
import sys
|
|
import unittest
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path[:0] = [str(ROOT / "src"), str(ROOT / "student-tests")]
|
|
import images # noqa: E402
|
|
from samples import REAL_IMAGES, make_png, png_chunk # noqa: E402
|
|
|
|
LIMIT = 40_000_000
|
|
|
|
|
|
def inspect(data, limit=LIMIT):
|
|
return images.inspect(io.BytesIO(data), limit)
|
|
|
|
|
|
class RealImagesTest(unittest.TestCase):
|
|
def test_real_images_are_accepted(self):
|
|
for name, (content_type, data) in REAL_IMAGES.items():
|
|
with self.subTest(name):
|
|
self.assertEqual(inspect(data), content_type)
|
|
|
|
def test_course_fixture(self):
|
|
path = ROOT / "tests/fixtures/sample.png"
|
|
self.assertEqual(inspect(path.read_bytes()), "image/png")
|
|
|
|
def test_jpeg_with_data_after_end(self):
|
|
# камеры дописывают после конца изображения превью
|
|
self.assertEqual(inspect(REAL_IMAGES["jpeg_baseline"][1] + b"\xff\xd8" + b"x" * 50), "image/jpeg")
|
|
|
|
def test_marker_on_block_border(self):
|
|
data = bytearray(REAL_IMAGES["jpeg_baseline"][1])
|
|
start = data.index(b"\xff\xda")
|
|
length = struct.unpack(">H", data[start + 2:start + 4])[0]
|
|
padded = data[:start + 2 + length] + b"\x12" * (images.BLOCK - 3) + b"\xff\x00" * 40 + data[start + 2 + length:]
|
|
self.assertEqual(inspect(bytes(padded)), "image/jpeg")
|
|
|
|
|
|
class BrokenImagesTest(unittest.TestCase):
|
|
def assert_not_image(self, data):
|
|
with self.assertRaises(images.NotAnImage):
|
|
inspect(data)
|
|
|
|
def test_truncated(self):
|
|
for name, (_, data) in REAL_IMAGES.items():
|
|
for size in (0, 1, 2, 3, 8, 12, len(data) // 2, len(data) - 1):
|
|
with self.subTest(name=name, size=size):
|
|
self.assert_not_image(data[:size])
|
|
|
|
def test_not_images(self):
|
|
for data in (b"", b"GIF89a" + b"\x00" * 20, b"%PDF-1.7", b"<svg></svg>", b"\xff\xd8", b"\x89PNG\r\n\x1a\n"):
|
|
with self.subTest(start=data[:8]):
|
|
self.assert_not_image(data)
|
|
|
|
def test_png_bad_crc(self):
|
|
data = bytearray(make_png(8, 8))
|
|
data[-20] ^= 0xFF
|
|
self.assert_not_image(bytes(data))
|
|
|
|
def test_png_data_after_end(self):
|
|
self.assert_not_image(make_png(8, 8) + b"<script>")
|
|
|
|
def test_png_with_wrong_amount_of_pixels(self):
|
|
self.assert_not_image(make_png(8, 8, b"\x00" * 10))
|
|
self.assert_not_image(make_png(8, 8, b"\x00" * 10000))
|
|
|
|
def test_png_data_is_not_zlib(self):
|
|
header = struct.pack(">IIBBBBB", 8, 8, 8, 2, 0, 0, 0)
|
|
data = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", b"not zlib") + png_chunk(b"IEND", b"")
|
|
self.assert_not_image(data)
|
|
|
|
def test_png_zero_size(self):
|
|
self.assert_not_image(make_png(0, 8, b""))
|
|
|
|
def test_jpeg_without_frame_or_scan(self):
|
|
self.assert_not_image(b"\xff\xd8\xff\xd9")
|
|
self.assert_not_image(b"\xff\xd8\xff\xe0\x00\x04ab\xff\xd9")
|
|
|
|
def test_png_data_after_compressed_stream_in_zero_size(self):
|
|
self.assert_not_image(make_png(1, 0, b""))
|
|
|
|
def test_random_corruption_never_crashes(self):
|
|
random.seed(20261030)
|
|
for name, (_, original) in REAL_IMAGES.items():
|
|
for _ in range(300):
|
|
data = bytearray(original)
|
|
for _ in range(random.randint(1, 8)):
|
|
data[random.randrange(len(data))] = random.randrange(256)
|
|
try:
|
|
inspect(bytes(data))
|
|
except (images.NotAnImage, images.TooManyPixels):
|
|
pass
|
|
|
|
|
|
class ReviewCasesTest(unittest.TestCase):
|
|
"""Файлы из замечания: заголовки верны, а изображения в них нет."""
|
|
|
|
def test_png_with_invalid_filter_byte(self):
|
|
with self.assertRaises(images.NotAnImage):
|
|
inspect(make_png(1, 1, b"\xff\x00\x00\x00"))
|
|
|
|
def test_jpeg_without_image_data(self):
|
|
data = bytes.fromhex("ffd8ffc0000b080001000101011100ffda0008010100003f00ffd9")
|
|
self.assertEqual(len(data), 27)
|
|
with self.assertRaises(images.NotAnImage):
|
|
inspect(data)
|
|
|
|
|
|
class PngContentTest(unittest.TestCase):
|
|
def assert_not_image(self, data):
|
|
with self.assertRaises(images.NotAnImage):
|
|
inspect(data)
|
|
|
|
def test_bad_filter_in_any_row(self):
|
|
row = b"\x00" + b"\x07" * 12
|
|
for bad_row in (0, 1, 7, 15):
|
|
rows = [row] * 16
|
|
rows[bad_row] = b"\x05" + b"\x07" * 12
|
|
with self.subTest(row=bad_row):
|
|
self.assert_not_image(make_png(4, 16, b"".join(rows)))
|
|
|
|
def test_all_valid_filters(self):
|
|
raw = b"".join(bytes([number % 5]) + b"\x07" * 12 for number in range(16))
|
|
self.assertEqual(inspect(make_png(4, 16, raw)), "image/png")
|
|
|
|
def test_filter_check_crosses_inflate_blocks(self):
|
|
# строки длиннее блока распаковки: байт фильтра может оказаться в любом месте блока
|
|
row_size = 1 + 3 * 40000
|
|
raw = bytearray(b"\x00" * row_size * 5)
|
|
raw[row_size * 3] = 9
|
|
self.assert_not_image(make_png(40000, 5, bytes(raw)))
|
|
raw[row_size * 3] = 4
|
|
self.assertEqual(inspect(make_png(40000, 5, bytes(raw))), "image/png")
|
|
|
|
def test_many_short_rows_are_checked_quickly(self):
|
|
import time
|
|
|
|
height = 5_000_000
|
|
started = time.monotonic()
|
|
header = struct.pack(">IIBBBBB", 1, height, 1, 0, 0, 0, 0)
|
|
data = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header)
|
|
data += png_chunk(b"IDAT", zlib.compress(b"\x00\x80" * height)) + png_chunk(b"IEND", b"")
|
|
self.assertEqual(inspect(data), "image/png")
|
|
self.assertLess(time.monotonic() - started, 5)
|
|
|
|
def test_interlaced(self):
|
|
def adam7(width, height, filter_byte=0):
|
|
rows = images.png_passes(width, height, 24, True)
|
|
return b"".join((bytes([filter_byte]) + b"\x07" * (size - 1)) * count for size, count in rows)
|
|
|
|
def interlaced_png(width, height, raw):
|
|
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 1)
|
|
return (b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", zlib.compress(raw))
|
|
+ png_chunk(b"IEND", b""))
|
|
|
|
for width, height in ((1, 1), (2, 3), (5, 5), (8, 8), (33, 17)):
|
|
with self.subTest(size=(width, height)):
|
|
self.assertEqual(inspect(interlaced_png(width, height, adam7(width, height))), "image/png")
|
|
self.assert_not_image(interlaced_png(width, height, adam7(width, height, 7)))
|
|
self.assert_not_image(interlaced_png(width, height, adam7(width, height) + b"\x00"))
|
|
self.assert_not_image(interlaced_png(width, height, adam7(width, height)[:-1]))
|
|
|
|
def test_chunk_order(self):
|
|
signature, rest = b"\x89PNG\r\n\x1a\n", make_png(4, 4)[8:]
|
|
ihdr, tail = rest[:25], rest[25:]
|
|
end = tail[-12:]
|
|
idat = tail[:-12]
|
|
half = len(idat)
|
|
comment = png_chunk(b"tEXt", b"a\x00b")
|
|
self.assertEqual(inspect(signature + ihdr + comment + idat + comment + end), "image/png")
|
|
# два IDAT с другим блоком между ними
|
|
raw = zlib.compress(b"\x00" * 13 * 4)
|
|
split = png_chunk(b"IDAT", raw[:5]) + comment + png_chunk(b"IDAT", raw[5:])
|
|
self.assert_not_image(signature + ihdr + split + end)
|
|
# неизвестный обязательный блок, неизвестный необязательный, второй IHDR, данные в IEND
|
|
self.assert_not_image(signature + ihdr + png_chunk(b"XXXX", b"") + idat + end)
|
|
self.assertEqual(inspect(signature + ihdr + png_chunk(b"xxXx", b"") + idat + end), "image/png")
|
|
self.assert_not_image(signature + ihdr + ihdr + idat + end)
|
|
self.assert_not_image(signature + ihdr + idat + png_chunk(b"IEND", b"x"))
|
|
self.assertGreater(half, 0)
|
|
|
|
def test_palette_rules(self):
|
|
header = struct.pack(">IIBBBBB", 1, 1, 8, 3, 0, 0, 0)
|
|
idat = png_chunk(b"IDAT", zlib.compress(b"\x00\x00"))
|
|
start = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header)
|
|
end = png_chunk(b"IEND", b"")
|
|
self.assertEqual(inspect(start + png_chunk(b"PLTE", b"\x01\x02\x03") + idat + end), "image/png")
|
|
self.assert_not_image(start + idat + end)
|
|
self.assert_not_image(start + idat + png_chunk(b"PLTE", b"\x01\x02\x03") + end)
|
|
self.assert_not_image(start + png_chunk(b"PLTE", b"\x01\x02") + idat + end)
|
|
|
|
def test_garbage_after_compressed_data(self):
|
|
raw = zlib.compress(b"\x00" * 13 * 4) + b"junk"
|
|
header = struct.pack(">IIBBBBB", 4, 4, 8, 2, 0, 0, 0)
|
|
data = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", raw) + png_chunk(b"IEND", b"")
|
|
self.assert_not_image(data)
|
|
|
|
|
|
class JpegContentTest(unittest.TestCase):
|
|
def assert_not_image(self, data):
|
|
with self.assertRaises(images.NotAnImage):
|
|
inspect(data)
|
|
|
|
def segment(self, data, marker):
|
|
start = data.index(bytes([0xFF, marker]))
|
|
return start, 2 + struct.unpack(">H", data[start + 2:start + 4])[0]
|
|
|
|
def without_segments(self, data, marker):
|
|
stripped = bytearray(data)
|
|
while True:
|
|
try:
|
|
start, length = self.segment(bytes(stripped), marker)
|
|
except ValueError:
|
|
return bytes(stripped)
|
|
del stripped[start:start + length]
|
|
|
|
def test_without_quantization_tables(self):
|
|
self.assert_not_image(self.without_segments(REAL_IMAGES["jpeg_baseline"][1], 0xDB))
|
|
|
|
def test_without_huffman_tables_like_mjpeg(self):
|
|
# кадры MJPEG хранятся без таблиц Хаффмана, декодер подставляет стандартные: такой файл корректен
|
|
stripped = self.without_segments(REAL_IMAGES["jpeg_baseline"][1], 0xC4)
|
|
self.assertEqual(inspect(stripped), "image/jpeg")
|
|
|
|
def test_scan_replaced_by_almost_nothing(self):
|
|
data = REAL_IMAGES["jpeg_baseline"][1]
|
|
start, length = self.segment(data, 0xDA)
|
|
self.assert_not_image(data[:start + length] + b"\xff\xd9")
|
|
self.assert_not_image(data[:start + length] + b"\x12" + b"\xff\xd9")
|
|
|
|
def test_truncated_with_end_marker_added(self):
|
|
for name in ("jpeg_baseline", "jpeg_progressive"):
|
|
data = REAL_IMAGES[name][1]
|
|
start, length = self.segment(data, 0xDA)
|
|
with self.subTest(name):
|
|
self.assert_not_image(data[:start + length + 1] + b"\xff\xd9")
|
|
|
|
def test_big_frame_with_tiny_scan(self):
|
|
data = bytearray(REAL_IMAGES["jpeg_baseline"][1])
|
|
start, _ = self.segment(bytes(data), 0xC0)
|
|
data[start + 5:start + 9] = struct.pack(">HH", 4000, 4000)
|
|
self.assert_not_image(bytes(data))
|
|
|
|
def test_broken_frame_header(self):
|
|
data = bytearray(REAL_IMAGES["jpeg_baseline"][1])
|
|
start, _ = self.segment(bytes(data), 0xC0)
|
|
for offset, value in ((9, 2), (9, 5), (11, 0x00), (11, 0x55)):
|
|
broken = bytearray(data)
|
|
broken[start + offset] = value
|
|
with self.subTest(offset=offset, value=value):
|
|
self.assert_not_image(bytes(broken))
|
|
|
|
def test_too_many_scans(self):
|
|
# прогрессивный файл, где скан повторён тысячи раз: декодер прошёл бы всё изображение каждый раз
|
|
data = REAL_IMAGES["jpeg_progressive"][1]
|
|
start, length = self.segment(data, 0xDA)
|
|
scan = data[start:start + length] + b"\x00" * 4
|
|
self.assert_not_image(data[:start] + scan * (images.MAX_JPEG_SCANS + 1) + b"\xff\xd9")
|
|
|
|
|
|
class PixelLimitTest(unittest.TestCase):
|
|
def test_png_bomb_is_rejected_before_unpacking(self):
|
|
header = struct.pack(">IIBBBBB", 50000, 50000, 8, 2, 0, 0, 0)
|
|
# данные заголовка верны, а распаковать пришлось бы 7,5 ГБ
|
|
data = b"\x89PNG\r\n\x1a\n" + png_chunk(b"IHDR", header) + png_chunk(b"IDAT", zlib.compress(b"\x00" * 1000))
|
|
with self.assertRaises(images.TooManyPixels):
|
|
inspect(data)
|
|
|
|
def test_jpeg_over_limit(self):
|
|
data = bytearray(REAL_IMAGES["jpeg_baseline"][1])
|
|
start = data.index(b"\xff\xc0")
|
|
data[start + 5:start + 9] = struct.pack(">HH", 20000, 20000)
|
|
with self.assertRaises(images.TooManyPixels):
|
|
inspect(bytes(data))
|
|
|
|
def test_limit_is_exact(self):
|
|
self.assertEqual(inspect(make_png(10, 10), limit=100), "image/png")
|
|
with self.assertRaises(images.TooManyPixels):
|
|
inspect(make_png(10, 10), limit=99)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|