using Febe.Core.Codecs.Images; namespace Febe.Tests.Imaging; /// /// Damaged files from the reference set, changed at random with fixed seeds: a decoder either reads them or throws /// , never anything else (no index out of range, no overflow, no huge allocation). /// [TestClass] public sealed class ImageFuzzTests { private const int MutationsPerFile = 120; private static readonly ImageLimits Small = new() { MaxPixels = 1_000_000, MaxWorkingBytes = 16 * 1024 * 1024, MaxMetadataBytes = 64 * 1024 }; public static IEnumerable Formats => [ [ReferenceFormat.Png], [ReferenceFormat.Gif], [ReferenceFormat.Bmp], [ReferenceFormat.Jpeg], ]; [TestMethod] [DynamicData(nameof(Formats))] public void ChangedBytesNeverBreakTheDecoder(ReferenceFormat format) { var seed = 1000 + (int)format; foreach (var reference in ReferenceImages.Of(format)) { var original = reference.ReadInput(); var random = new Random(seed++); for (var i = 0; i < MutationsPerFile; i++) { var mutated = Mutate(original, random); if (format == ReferenceFormat.Png && random.Next(3) > 0) { // Most changes to a PNG only meet a wrong CRC: fixing it lets them reach the pixels. TestImages.FixPngCrcs(mutated); } TryDecode(mutated, $"{reference.Name}, modifica {i}"); } } } [TestMethod] public void ChangedBytesNeverBreakTheFacade() { var random = new Random(77); foreach (var reference in ReferenceImages.All) { var mutated = Mutate(reference.ReadInput(), random); try { using var image = ImageDecoder.Decode(mutated, Small); ImageDecoder.Identify(mutated, Small); } catch (ImageDecodeException) { } } } private static void TryDecode(byte[] bytes, string what) { try { using var image = ImageDecoder.Decode(bytes, Small); Assert.IsGreaterThan(0, image.Width, what); } catch (ImageDecodeException) { } catch (Exception ex) { Assert.Fail($"{what}: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); } try { ImageDecoder.Identify(bytes, Small); } catch (ImageDecodeException) { } catch (Exception ex) { Assert.Fail($"{what} (Identify): {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); } } private static byte[] Mutate(byte[] original, Random random) { var bytes = original.ToArray(); switch (random.Next(4)) { case 0: // A few random bytes anywhere after the signature. for (var k = random.Next(1, 9); k > 0; k--) { bytes[random.Next(Math.Min(8, bytes.Length - 1), bytes.Length)] = (byte)random.Next(256); } return bytes; case 1: // A byte of the headers set to an extreme. bytes[random.Next(Math.Min(8, bytes.Length - 1), Math.Min(bytes.Length, 80))] = random.Next(2) == 0 ? (byte)0 : (byte)0xFF; return bytes; case 2: // Cut short. return bytes[..random.Next(1, bytes.Length)]; default: // A run of bytes flipped. var start = random.Next(8, bytes.Length); var length = Math.Min(bytes.Length - start, random.Next(1, 64)); for (var k = 0; k < length; k++) { bytes[start + k] ^= 0x5A; } return bytes; } } }