package ru.mtuci.messenger.service; import org.junit.jupiter.api.Test; import ru.mtuci.messenger.exception.PayloadTooLargeException; import ru.mtuci.messenger.exception.UnsupportedMediaException; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; class ImageFilesTest { @Test void readsFixtureWithoutDecodingPixels() throws Exception { byte[] png = Files.readAllBytes(Path.of("../tests/fixtures/sample.png")); ImageFiles.Image image = ImageFiles.inspect(png, "image/png", 40_000_000); assertEquals("image/png", image.contentType()); assertEquals(320, image.width()); assertEquals(200, image.height()); assertArrayEquals(png, ImageFiles.readLimited(new java.io.ByteArrayInputStream(png), 10_485_760)); } @Test void rejectsSpoofedMimeCorruptAndPixelBomb() { byte[] jpeg = new byte[] { (byte) 0xff, (byte) 0xd8, (byte) 0xff, (byte) 0xc0, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00, (byte) 0xff, (byte) 0xd9 }; assertEquals(1, ImageFiles.inspect(jpeg, "image/jpeg", 40_000_000).width()); assertThrows(UnsupportedMediaException.class, () -> ImageFiles.inspect(jpeg, "image/png", 40_000_000)); assertThrows(UnsupportedMediaException.class, () -> ImageFiles.inspect(new byte[] {1, 2, 3}, "image/png", 40_000_000)); byte[] bomb = png(8_000, 8_000); assertThrows(PayloadTooLargeException.class, () -> ImageFiles.inspect(bomb, "image/png", 40_000_000)); byte[] huge = new byte[8]; assertThrows(PayloadTooLargeException.class, () -> ImageFiles.readLimited(new java.io.ByteArrayInputStream(huge), 7)); } private static byte[] png(int width, int height) { byte[] data = new byte[8 + 12 + 13 + 12]; byte[] signature = new byte[] {(byte) 137, 80, 78, 71, 13, 10, 26, 10}; System.arraycopy(signature, 0, data, 0, 8); data[11] = 13; data[12] = 'I'; data[13] = 'H'; data[14] = 'D'; data[15] = 'R'; putInt(data, 16, width); putInt(data, 20, height); data[24] = 8; data[25] = 2; data[37] = 'I'; data[38] = 'E'; data[39] = 'N'; data[40] = 'D'; return data; } private static void putInt(byte[] data, int offset, int value) { data[offset] = (byte) (value >>> 24); data[offset + 1] = (byte) (value >>> 16); data[offset + 2] = (byte) (value >>> 8); data[offset + 3] = (byte) value; } }