refactor(525): extract RemoteImageValidator; render path delegates to static

This commit is contained in:
2026-07-21 13:13:21 +02:00
parent 7ee436241a
commit 65a41dbf8d
5 changed files with 250 additions and 55 deletions
@@ -0,0 +1,13 @@
namespace ErsatzTV.Core.Interfaces.Images;
/// <summary>
/// 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)
/// </summary>
public interface IRemoteImageValidator
{
Task Validate(Stream stream, Uri uri, CancellationToken cancellationToken);
}
@@ -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<InvalidOperationException>(
() => 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<InvalidOperationException>(
() => 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<Exception>(() => 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<InvalidOperationException>(
() => validator.Validate(stream, Uri, CancellationToken.None));
}
/// <summary>A real multi-frame APNG. Small on the wire, many frames — the shape that matters.</summary>
private static MemoryStream Apng(int width, int height, int frames)
{
using var image = new Image<Rgba32>(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<byte> 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;
}
/// <summary>A real, decodable PNG.</summary>
private static async Task<MemoryStream> RealPng(int width, int height)
{
using var image = new Image<Rgba32>(width, height);
var stream = new MemoryStream();
await image.SaveAsync(stream, new PngEncoder());
stream.Position = 0;
return stream;
}
/// <summary>
/// A PNG signature plus a single valid IHDR chunk declaring <paramref name="width" /> x
/// <paramref name="height" /> 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.
/// </summary>
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;
}
}
@@ -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);
}
/// <summary>
/// Decodes a remote image only after the header says decoding it is affordable.
/// </summary>
/// <remarks>
/// 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)
/// </remarks>
public static async Task<Image> 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;
}
}
}
@@ -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)
/// </remarks>
internal static async Task<Image> 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);
/// <summary>
/// Bounds what is RETAINED after scaling. Separate from the source budget because the two
+1
View File
@@ -1101,6 +1101,7 @@ public class Startup
services.AddScoped<IExternalJsonPlayoutItemProvider, ExternalJsonPlayoutItemProvider>();
services.AddScoped<IRemoteStreamProber, HttpRemoteStreamProber>();
services.AddScoped<IRemoteImageFetcher, HttpRemoteImageFetcher>();
services.AddScoped<IRemoteImageValidator, RemoteImageValidator>();
services.AddScoped<IPlayoutBuilder, PlayoutBuilder>();
services.AddScoped<IBlockPlayoutBuilder, BlockPlayoutBuilder>();
services.AddScoped<IBlockPlayoutPreviewBuilder, BlockPlayoutPreviewBuilder>();