forked from mtusi2026/mtusi2026lab5
Исправить проверку целостности PNG
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
"""Regression: Pillow accepts truncated IEND, upload validator must reject it."""
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import zlib
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
||||
from messenger.image_check import main
|
||||
|
||||
|
||||
def chunk(kind, payload):
|
||||
return (struct.pack('>I', len(payload)) + kind + payload
|
||||
+ struct.pack('>I', zlib.crc32(kind + payload)))
|
||||
|
||||
|
||||
class ImageCheckTest(unittest.TestCase):
|
||||
def test_complete_chunk_integrity(self):
|
||||
png = (b'\x89PNG\r\n\x1a\n'
|
||||
+ chunk(b'IHDR', struct.pack('>IIBBBBB', 1, 1, 8, 2, 0, 0, 0))
|
||||
+ chunk(b'IDAT', zlib.compress(b'\x00\xff\x00\x00'))
|
||||
+ chunk(b'IEND', b''))
|
||||
cases = [('valid', png, 0)]
|
||||
cases += [(f'truncated-{n}', png[:-n], 15) for n in range(1, 13)]
|
||||
cases += [('bad-iend-crc', png[:-1] + bytes([png[-1] ^ 1]), 15),
|
||||
('bad-ancillary-crc', png[:-12] + b'\x00\x00\x00\x00tEXt\x00\x00\x00\x00'
|
||||
+ png[-12:], 15),
|
||||
('nonempty-iend', png[:-12] + chunk(b'IEND', b'x'), 15)]
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / 'image.png'
|
||||
for label, data, expected in cases:
|
||||
with self.subTest(case=label):
|
||||
path.write_bytes(data)
|
||||
with patch.object(sys, 'argv', ['image_check', str(path), 'image/png', '40000000']):
|
||||
self.assertEqual(main(), expected)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user