From 1f98e0345d9e2cb5d2e6d5bccd93572468762cba Mon Sep 17 00:00:00 2001 From: Timothy Date: Tue, 21 Jul 2026 03:35:00 +0200 Subject: [PATCH] refactor(525): extract RemoteImageValidator; render path delegates to static --- .../Images/IRemoteImageValidator.cs | 13 ++ .../Images/RemoteImageValidatorTests.cs | 151 ++++++++++++++++++ .../Images/RemoteImageValidator.cs | 83 ++++++++++ .../Graphics/Image/ImageElementBase.cs | 57 +------ ErsatzTV/Startup.cs | 1 + 5 files changed, 250 insertions(+), 55 deletions(-) create mode 100644 ErsatzTV.Core/Interfaces/Images/IRemoteImageValidator.cs create mode 100644 ErsatzTV.Infrastructure.Tests/Images/RemoteImageValidatorTests.cs create mode 100644 ErsatzTV.Infrastructure/Images/RemoteImageValidator.cs diff --git a/ErsatzTV.Core/Interfaces/Images/IRemoteImageValidator.cs b/ErsatzTV.Core/Interfaces/Images/IRemoteImageValidator.cs new file mode 100644 index 000000000..f40995fa5 --- /dev/null +++ b/ErsatzTV.Core/Interfaces/Images/IRemoteImageValidator.cs @@ -0,0 +1,13 @@ +namespace ErsatzTV.Core.Interfaces.Images; + +/// +/// Validates that a stream is a decodable image within the decode budget, throwing if not. +/// Used by the logo save path and the artwork upload path (neither needs the decoded pixels, +/// only "is this safe to cache"). The graphics engine uses the static +/// RemoteImageValidator.DecodeAndValidate instead, which returns the Image it composites. +/// (ersatztv#525) +/// +public interface IRemoteImageValidator +{ + Task Validate(Stream stream, Uri uri, CancellationToken cancellationToken); +} diff --git a/ErsatzTV.Infrastructure.Tests/Images/RemoteImageValidatorTests.cs b/ErsatzTV.Infrastructure.Tests/Images/RemoteImageValidatorTests.cs new file mode 100644 index 000000000..624cbea6a --- /dev/null +++ b/ErsatzTV.Infrastructure.Tests/Images/RemoteImageValidatorTests.cs @@ -0,0 +1,151 @@ +using System.Buffers.Binary; +using ErsatzTV.Core.Images; +using ErsatzTV.Core.Interfaces.Images; +using ErsatzTV.Infrastructure.Images; +using NUnit.Framework; +using Shouldly; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.PixelFormats; +using Image = SixLabors.ImageSharp.Image; + +namespace ErsatzTV.Infrastructure.Tests.Images; + +[TestFixture] +public class RemoteImageValidatorTests +{ + private static readonly Uri Uri = new("https://example.com/logo.png"); + + // decode cases exercise the static method (used by the render path) + [Test] + public async Task Should_Decode_A_Normal_Image() + { + await using MemoryStream stream = await RealPng(64, 32); + using Image image = await RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None); + image.Width.ShouldBe(64); + image.Height.ShouldBe(32); + } + + [Test] + public async Task Should_Reject_A_Decompression_Bomb_By_Declared_Dimensions() + { + await using MemoryStream stream = PngHeaderDeclaring(30000, 30000); + InvalidOperationException ex = await Should.ThrowAsync( + () => RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None)); + ex.Message.ShouldContain("pixel limit"); + } + + [Test] + public async Task Should_Reject_An_Apng_Whose_Header_Under_Reports_Its_Frames() + { + await using MemoryStream stream = Apng(64, 64, RemoteImageDecodeBudget.MaxRemoteFrames + 100); + InvalidOperationException ex = await Should.ThrowAsync( + () => RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None)); + ex.Message.ShouldContain("frame limit"); + } + + [Test] + public async Task Should_Decode_An_Apng_That_A_Default_Identify_Cannot_Read() + { + await using MemoryStream stream = Apng(288, 288, 60); + stream.Position = 0; + await Should.ThrowAsync(() => Image.IdentifyAsync(stream)); + stream.Position = 0; + using Image image = await RemoteImageValidator.DecodeAndValidate(stream, Uri, CancellationToken.None); + image.Frames.Count.ShouldBe(60); + } + + // the Core interface Validate() is the save/upload contract: throws on invalid, returns on valid, + // never surfaces an ImageSharp type + [Test] + public async Task Validate_Returns_On_A_Good_Image() + { + IRemoteImageValidator validator = new RemoteImageValidator(); + await using MemoryStream stream = await RealPng(64, 32); + await Should.NotThrowAsync(() => validator.Validate(stream, Uri, CancellationToken.None)); + } + + [Test] + public async Task Validate_Throws_On_A_Bomb() + { + IRemoteImageValidator validator = new RemoteImageValidator(); + await using MemoryStream stream = PngHeaderDeclaring(30000, 30000); + await Should.ThrowAsync( + () => validator.Validate(stream, Uri, CancellationToken.None)); + } + + /// A real multi-frame APNG. Small on the wire, many frames — the shape that matters. + private static MemoryStream Apng(int width, int height, int frames) + { + using var image = new Image(width, height); + for (var i = 1; i < frames; i++) + { + image.Frames.CreateFrame(); + } + + var stream = new MemoryStream(); + image.Save(stream, new PngEncoder { ColorType = PngColorType.RgbWithAlpha }); + stream.Position = 0; + return stream; + } + + // PNG chunk CRC-32 (IEEE, reflected). hand-rolled because the repo does not reference + // System.IO.Hashing, and ImageSharp validates the CRC of critical chunks like IHDR. + private static uint Crc32(ReadOnlySpan data) + { + uint crc = 0xFFFFFFFF; + foreach (byte b in data) + { + crc ^= b; + for (var i = 0; i < 8; i++) + { + crc = (crc & 1) != 0 ? (crc >> 1) ^ 0xEDB88320 : crc >> 1; + } + } + + return crc ^ 0xFFFFFFFF; + } + + /// A real, decodable PNG. + private static async Task RealPng(int width, int height) + { + using var image = new Image(width, height); + var stream = new MemoryStream(); + await image.SaveAsync(stream, new PngEncoder()); + stream.Position = 0; + return stream; + } + + /// + /// A PNG signature plus a single valid IHDR chunk declaring x + /// and nothing else — enough for Identify, far too little to + /// decode. This is what a decompression bomb looks like at the point we have to reject it. + /// + private static MemoryStream PngHeaderDeclaring(int width, int height) + { + var stream = new MemoryStream(); + stream.Write([0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A]); + + var ihdr = new byte[17]; + "IHDR"u8.CopyTo(ihdr); + BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(4), width); + BinaryPrimitives.WriteInt32BigEndian(ihdr.AsSpan(8), height); + ihdr[12] = 8; // bit depth + ihdr[13] = 6; // color type: truecolor + alpha + ihdr[14] = 0; // compression + ihdr[15] = 0; // filter + ihdr[16] = 0; // interlace + + var length = new byte[4]; + BinaryPrimitives.WriteInt32BigEndian(length, 13); + stream.Write(length); + stream.Write(ihdr); + + var crc = new byte[4]; + BinaryPrimitives.WriteUInt32BigEndian(crc, Crc32(ihdr)); + stream.Write(crc); + + stream.Position = 0; + return stream; + } +} diff --git a/ErsatzTV.Infrastructure/Images/RemoteImageValidator.cs b/ErsatzTV.Infrastructure/Images/RemoteImageValidator.cs new file mode 100644 index 000000000..e7aeaa1c2 --- /dev/null +++ b/ErsatzTV.Infrastructure/Images/RemoteImageValidator.cs @@ -0,0 +1,83 @@ +using ErsatzTV.Core.Images; +using ErsatzTV.Core.Interfaces.Images; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; +using Image = SixLabors.ImageSharp.Image; + +namespace ErsatzTV.Infrastructure.Images; + +public class RemoteImageValidator : IRemoteImageValidator +{ + public async Task Validate(Stream stream, Uri uri, CancellationToken cancellationToken) + { + using Image _ = await DecodeAndValidate(stream, uri, cancellationToken); + } + + /// + /// Decodes a remote image only after the header says decoding it is affordable. + /// + /// + /// The fetcher's byte cap does NOT bound this: a decompression bomb is small on the wire and + /// huge in memory. A 4 KB PNG can declare 30000x30000 (~3.6 GB), and a 60 KiB GIF can + /// declare 2500x2500 across 600 frames (~14 GiB). The budget is therefore on the PRODUCT of + /// dimensions and frames, read from the header before the decoder allocates. + /// Local images are deliberately not checked — they are files an operator put on disk, not + /// bytes an arbitrary host returned. (ersatztv#511) + /// + public static async Task DecodeAndValidate(Stream stream, Uri uri, CancellationToken cancellationToken) + { + if (!stream.CanSeek) + { + // Identify consumes the stream, so the decode below needs to rewind it. Fail with the + // real reason rather than letting Position throw NotSupportedException, which the + // caller's blanket catch would report as a generic initialization failure. + throw new InvalidOperationException( + $"Remote image {uri} was returned on a non-seekable stream; IRemoteImageFetcher must " + + "return a fully buffered, seekable stream"); + } + + // MaxFrames = 1 on the IDENTIFY is not a limit, it is a workaround: a default Identify + // throws InvalidImageContentException on most APNGs — including files ImageSharp's own + // PngEncoder wrote, which Image.Load then reads back perfectly (measured: 13 of 16 shapes). + // Without this, adding the header pre-pass would silently disable every animated-PNG logo + // that worked before this change. Only Width/Height are read below, and those stay correct. + ImageInfo info = await Image.IdentifyAsync( + new DecoderOptions { MaxFrames = 1 }, + stream, + cancellationToken); + + // DIMENSIONS from the header are trustworthy; the FRAME COUNT is not, and is deliberately + // not used as a budget input. Measured on ImageSharp 3.1.12: an APNG reports + // FrameMetadataCollection.Count == 0 while the decoder happily produces 600 frames, so a + // header-derived frame budget is enforced on a number the decoder does not honor — a + // 134 KiB file decodes to ~36 GiB. (Second adversarial re-review; ersatztv#511.) + RemoteImageDecodeBudget.EnsureDimensionsAffordable(info.Width, info.Height, uri); + + int affordableFrames = RemoteImageDecodeBudget.AffordableFrames(info.Width, info.Height); + + stream.Position = 0; + + // MaxFrames is enforced BY THE DECODER, so it holds whatever the header claimed — measured + // as honored by every animated decoder here (APNG, GIF, WebP, TIFF). Ask for two more than + // the budget allows so that an animation exactly AT the limit still decodes in full, while + // anything over it is present in the decoded image for the post-decode check below to + // reject. Slop is at most two frames: MaxFrames = N yields N frames for GIF/WebP/TIFF but + // N-1 for APNG, so the exact count varies by format and only the upper bound matters. + var decoderOptions = new DecoderOptions { MaxFrames = (uint)(affordableFrames + 2) }; + + Image image = await Image.LoadAsync(decoderOptions, stream, cancellationToken); + + try + { + // re-verify against REALITY rather than against the header. this is the check that + // actually holds; everything above it only avoids decoding when we can tell in advance. + RemoteImageDecodeBudget.EnsureDecodeAffordable(image.Width, image.Height, image.Frames.Count, uri); + return image; + } + catch + { + image.Dispose(); + throw; + } + } +} diff --git a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs index 2fee5d9a7..3c9dff8cd 100644 --- a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs +++ b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs @@ -3,6 +3,7 @@ using ErsatzTV.Core.Domain; using ErsatzTV.Core.Images; using ErsatzTV.Core.Interfaces.Streaming; using ErsatzTV.FFmpeg.State; +using ErsatzTV.Infrastructure.Images; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Gif; @@ -131,61 +132,7 @@ public abstract class ImageElementBase(IRemoteImageFetcher remoteImageFetcher) : /// bytes an arbitrary host returned. (ersatztv#511) /// internal static async Task DecodeRemoteImage(Stream stream, Uri uri, CancellationToken cancellationToken) - { - if (!stream.CanSeek) - { - // Identify consumes the stream, so the decode below needs to rewind it. Fail with the - // real reason rather than letting Position throw NotSupportedException, which the - // caller's blanket catch would report as a generic initialization failure. - throw new InvalidOperationException( - $"Remote image {uri} was returned on a non-seekable stream; IRemoteImageFetcher must " - + "return a fully buffered, seekable stream"); - } - - // MaxFrames = 1 on the IDENTIFY is not a limit, it is a workaround: a default Identify - // throws InvalidImageContentException on most APNGs — including files ImageSharp's own - // PngEncoder wrote, which Image.Load then reads back perfectly (measured: 13 of 16 shapes). - // Without this, adding the header pre-pass would silently disable every animated-PNG logo - // that worked before this change. Only Width/Height are read below, and those stay correct. - ImageInfo info = await Image.IdentifyAsync( - new DecoderOptions { MaxFrames = 1 }, - stream, - cancellationToken); - - // DIMENSIONS from the header are trustworthy; the FRAME COUNT is not, and is deliberately - // not used as a budget input. Measured on ImageSharp 3.1.12: an APNG reports - // FrameMetadataCollection.Count == 0 while the decoder happily produces 600 frames, so a - // header-derived frame budget is enforced on a number the decoder does not honor — a - // 134 KiB file decodes to ~36 GiB. (Second adversarial re-review; ersatztv#511.) - RemoteImageDecodeBudget.EnsureDimensionsAffordable(info.Width, info.Height, uri); - - int affordableFrames = RemoteImageDecodeBudget.AffordableFrames(info.Width, info.Height); - - stream.Position = 0; - - // MaxFrames is enforced BY THE DECODER, so it holds whatever the header claimed — measured - // as honored by every animated decoder here (APNG, GIF, WebP, TIFF). Ask for two more than - // the budget allows so that an animation exactly AT the limit still decodes in full, while - // anything over it is present in the decoded image for the post-decode check below to - // reject. Slop is at most two frames: MaxFrames = N yields N frames for GIF/WebP/TIFF but - // N-1 for APNG, so the exact count varies by format and only the upper bound matters. - var decoderOptions = new DecoderOptions { MaxFrames = (uint)(affordableFrames + 2) }; - - Image image = await Image.LoadAsync(decoderOptions, stream, cancellationToken); - - try - { - // re-verify against REALITY rather than against the header. this is the check that - // actually holds; everything above it only avoids decoding when we can tell in advance. - RemoteImageDecodeBudget.EnsureDecodeAffordable(image.Width, image.Height, image.Frames.Count, uri); - return image; - } - catch - { - image.Dispose(); - throw; - } - } + => await RemoteImageValidator.DecodeAndValidate(stream, uri, cancellationToken); /// /// Bounds what is RETAINED after scaling. Separate from the source budget because the two diff --git a/ErsatzTV/Startup.cs b/ErsatzTV/Startup.cs index 757c746a4..1c050eacc 100644 --- a/ErsatzTV/Startup.cs +++ b/ErsatzTV/Startup.cs @@ -1101,6 +1101,7 @@ public class Startup services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped();