diff --git a/ErsatzTV.Core/Interfaces/Streaming/IRemoteImageFetcher.cs b/ErsatzTV.Core/Interfaces/Streaming/IRemoteImageFetcher.cs new file mode 100644 index 000000000..996f801c6 --- /dev/null +++ b/ErsatzTV.Core/Interfaces/Streaming/IRemoteImageFetcher.cs @@ -0,0 +1,24 @@ +namespace ErsatzTV.Core.Interfaces.Streaming; + +/// +/// Fetches a remote (http/https) image for the graphics engine, under a bounded timeout and a +/// bounded response size. +/// +public interface IRemoteImageFetcher +{ + /// + /// Fetches fully into memory. + /// + /// + /// A seekable, fully-buffered stream positioned at zero. The caller owns and must dispose it. + /// + /// + /// Throws rather than returning a failure value: every call site already wraps element + /// initialization in a catch that disables the element, so a throw degrades to "no watermark" + /// rather than a killed stream. An implementation's own deadline should surface as + /// and caller cancellation as + /// — though note the current call sites catch both + /// alike, so today the distinction only sharpens the log message. + /// + Task Fetch(Uri uri, CancellationToken cancellationToken); +} diff --git a/ErsatzTV.Infrastructure.Tests/Streaming/Graphics/RemoteImageDecodeLimitTests.cs b/ErsatzTV.Infrastructure.Tests/Streaming/Graphics/RemoteImageDecodeLimitTests.cs new file mode 100644 index 000000000..6154b62e3 --- /dev/null +++ b/ErsatzTV.Infrastructure.Tests/Streaming/Graphics/RemoteImageDecodeLimitTests.cs @@ -0,0 +1,284 @@ +using System.Buffers.Binary; +using ErsatzTV.Infrastructure.Streaming.Graphics; +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.Streaming.Graphics; + +/// +/// The byte cap in HttpRemoteImageFetcher does not bound decoding: a decompression bomb +/// is tiny on the wire and enormous in memory. These pin the header-first check that does. +/// (ersatztv#511) +/// +[TestFixture] +public class RemoteImageDecodeLimitTests +{ + private static readonly Uri ImageUri = new("https://example.com/logo.png"); + + [Test] + public async Task Should_Decode_A_Normal_Image() + { + await using MemoryStream stream = await RealPng(64, 32); + + using Image image = await ImageElementBase.DecodeRemoteImage(stream, ImageUri, CancellationToken.None); + + image.Width.ShouldBe(64); + image.Height.ShouldBe(32); + } + + // the bomb: a few dozen bytes on the wire, ~3.6 GB if decoded. it sails through the byte cap, + // the content-type check and the Content-Length reject -- only the header dimensions catch it. + [Test] + public async Task Should_Reject_An_Image_Whose_Declared_Dimensions_Are_A_Decompression_Bomb() + { + await using MemoryStream stream = PngHeaderDeclaring(30000, 30000); + + stream.Length.ShouldBeLessThan(100, "the point is that this is tiny on the wire"); + + InvalidOperationException ex = await Should.ThrowAsync( + () => ImageElementBase.DecodeRemoteImage(stream, ImageUri, CancellationToken.None)); + + ex.Message.ShouldContain("pixel limit"); + } + + [Test] + public async Task Should_Accept_Dimensions_Exactly_At_The_Limit() + { + // 10000 x 5000 = 50,000,000 -- exactly the budget, so it must NOT be rejected. the decode + // then fails on the truncated body, which proves the check let it through. NOTE this test + // would also pass with the guard deleted entirely; deletion is covered by the bomb test + // above, and the boundary arithmetic by EnsureDecodeAffordable's own tests. + await using MemoryStream stream = PngHeaderDeclaring(10000, 5000); + + Exception ex = await Should.ThrowAsync( + () => ImageElementBase.DecodeRemoteImage(stream, ImageUri, CancellationToken.None)); + + ex.Message.ShouldNotContain("pixel limit"); + } + + // --- the budget policy itself, tested as arithmetic so no multi-GB image is ever allocated --- + + // THE bomb the first fix missed: 2500x2500 x600 frames is ~60 KiB on the wire, passes a + // dimensions-only check (6.25 MP) AND a frames-only check (exactly 600), and costs ~14 GiB to + // decode. Only the PRODUCT catches it. (Found by adversarial re-review; ersatztv#511.) + [Test] + public void Should_Reject_Dimensions_And_Frames_That_Are_Affordable_Alone_But_Not_Together() + { + const int Width = 2500; + const int Height = 2500; + const int Frames = 600; + + // each guard, in isolation, says yes + ((long)Width * Height).ShouldBeLessThanOrEqualTo(ImageElementBase.MaxRemoteDecodedPixels); + Frames.ShouldBeLessThanOrEqualTo(ImageElementBase.MaxRemoteFrames); + + InvalidOperationException ex = Should.Throw( + () => ImageElementBase.EnsureDecodeAffordable(Width, Height, Frames, ImageUri)); + + ex.Message.ShouldContain("pixel limit"); + } + + // M1: the frame guard had no coverage at all in the first fix + [Test] + public void Should_Reject_Too_Many_Frames_Even_When_Each_Is_Tiny() + { + InvalidOperationException ex = Should.Throw( + () => ImageElementBase.EnsureDecodeAffordable(8, 8, ImageElementBase.MaxRemoteFrames + 1, ImageUri)); + + ex.Message.ShouldContain("frame limit"); + } + + [Test] + public void Should_Allow_A_Single_Large_Still_Within_Budget() + { + // 8K is ~33 MP -- must keep working + Should.NotThrow(() => ImageElementBase.EnsureDecodeAffordable(7680, 4320, 1, ImageUri)); + } + + [Test] + public void Should_Allow_A_Typical_Animated_Logo() + { + Should.NotThrow(() => ImageElementBase.EnsureDecodeAffordable(288, 288, 600, ImageUri)); + } + + [Test] + public void Should_Afford_Fewer_Frames_As_Frames_Get_Larger() + { + // tiny frames are capped by the frame guard, not the pixel budget + ImageElementBase.AffordableFrames(8, 8).ShouldBe(ImageElementBase.MaxRemoteFrames); + + // 1000x1000 -> 50M / 1M = 50 frames + ImageElementBase.AffordableFrames(1000, 1000).ShouldBe(50); + + // a frame so large only one fits + ImageElementBase.AffordableFrames(7000, 7000).ShouldBe(1); + } + + [Test] + public void Should_Allow_A_Product_Exactly_At_The_Budget() + { + // 10000 x 5000 x 1 == MaxRemoteDecodedPixels exactly + Should.NotThrow(() => ImageElementBase.EnsureDecodeAffordable(10000, 5000, 1, ImageUri)); + } + + // the retained-frame budget is INDEPENDENT of the decode budget: this source is trivial to + // decode (6 MP total) but retains ~5 GB of SKBitmap once every frame is scaled to 1080p + [Test] + public void Should_Reject_Cheap_Frames_That_Are_Expensive_Once_Scaled() + { + Should.NotThrow(() => ImageElementBase.EnsureDecodeAffordable(100, 100, 600, ImageUri)); + + InvalidOperationException ex = Should.Throw( + () => ImageElementBase.EnsureScaledFramesAffordable(600, 1920, 1080, ImageUri)); + + ex.Message.ShouldContain("pixel limit"); + } + + [Test] + public void Should_Allow_A_Scaled_Watermark_Sized_Animation() + { + // a 10%-width logo on a 1080p frame, animated + Should.NotThrow(() => ImageElementBase.EnsureScaledFramesAffordable(600, 192, 108, ImageUri)); + } + + + // --- B1 regression: the header's frame count is a LIE for APNG --- + + // ImageSharp 3.1.12 reports FrameMetadataCollection.Count == 0 for an APNG while the decoder + // produces every frame. A budget derived from that header count is enforced on a number the + // decoder does not honor — this exact payload shape, at 4000x4000, is ~134 KiB on the wire and + // ~36 GiB decoded. The bound therefore has to be imposed ON THE DECODER (DecoderOptions. + // MaxFrames) and re-verified against the real frame count. (ersatztv#511, second re-review.) + [Test] + public async Task Should_Reject_An_Animation_Whose_Header_Under_Reports_Its_Frames() + { + await using MemoryStream stream = Apng(64, 64, ImageElementBase.MaxRemoteFrames + 100); + + // the premise: the header really does under-report, so a header-derived budget waves it through + stream.Position = 0; + ImageInfo info = await Image.IdentifyAsync(stream); + info.FrameMetadataCollection.Count.ShouldBe(0, "the APNG header under-reports; that is the whole point"); + Should.NotThrow(() => ImageElementBase.EnsureDecodeAffordable(64, 64, info.FrameMetadataCollection.Count, ImageUri)); + + stream.Position = 0; + InvalidOperationException ex = await Should.ThrowAsync( + () => ImageElementBase.DecodeRemoteImage(stream, ImageUri, CancellationToken.None)); + + ex.Message.ShouldContain("frame limit"); + } + + // ...and an animation within budget still decodes IN FULL -- the decoder cap must not silently + // truncate legitimate content by a frame + [Test] + public async Task Should_Decode_An_Animation_Within_Budget_Without_Truncating_It() + { + await using MemoryStream stream = Apng(64, 64, 300); + + using Image image = await ImageElementBase.DecodeRemoteImage(stream, ImageUri, CancellationToken.None); + + image.Frames.Count.ShouldBe(300); + } + + + // H2 regression: a default `Image.Identify` throws InvalidImageContentException on most APNGs + // (measured: 13 of 16 shapes, including ones ImageSharp's own encoder wrote) even though + // `Image.Load` reads them back perfectly. 288x288 is one of the throwing shapes; 64x64 x300 -- + // used by the tests above -- happens NOT to be, which is exactly why they could not see this. + // Without the MaxFrames=1 workaround on the Identify, every animated-PNG logo that worked + // before this change would be silently disabled. (ersatztv#511, fourth re-review.) + [Test] + public async Task Should_Decode_An_Apng_That_A_Default_Identify_Cannot_Read() + { + await using MemoryStream stream = Apng(288, 288, 60); + + // the premise: a default Identify really does fail on this file + stream.Position = 0; + await Should.ThrowAsync(() => Image.IdentifyAsync(stream)); + + stream.Position = 0; + using Image image = await ImageElementBase.DecodeRemoteImage(stream, ImageUri, CancellationToken.None); + + image.Width.ShouldBe(288); + image.Height.ShouldBe(288); + image.Frames.Count.ShouldBe(60); + } + + /// 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.Tests/Streaming/Graphics/WatermarkElementRemoteImageTests.cs b/ErsatzTV.Infrastructure.Tests/Streaming/Graphics/WatermarkElementRemoteImageTests.cs new file mode 100644 index 000000000..d51990f1c --- /dev/null +++ b/ErsatzTV.Infrastructure.Tests/Streaming/Graphics/WatermarkElementRemoteImageTests.cs @@ -0,0 +1,183 @@ +using ErsatzTV.Core.Domain; +using ErsatzTV.Core.FFmpeg; +using ErsatzTV.Core.Interfaces.Streaming; +using ErsatzTV.FFmpeg; +using ErsatzTV.FFmpeg.State; +using ErsatzTV.Infrastructure.Streaming.Graphics; +using LanguageExt; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Png; +using SixLabors.ImageSharp.PixelFormats; +using Microsoft.Extensions.Logging; +using NSubstitute; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Infrastructure.Tests.Streaming.Graphics; + +/// +/// The degradation contract for a remote watermark image: whatever the fetcher throws, the +/// element disables itself and the stream survives. (ersatztv#511) +/// +[TestFixture] +public class WatermarkElementRemoteImageTests +{ + private const string RemoteLogo = "https://example.com/logo.png"; + + private static readonly Exception[] FetchFailures = + [ + new TimeoutException("timed out fetching remote image"), + new InvalidOperationException("remote image exceeds the byte limit"), + new HttpRequestException("no route to host") + ]; + + [TestCaseSource(nameof(FetchFailures))] + public async Task Should_Disable_The_Watermark_When_The_Fetch_Fails(Exception failure) + { + var fetcher = Substitute.For(); + fetcher.Fetch(Arg.Any(), Arg.Any()).Returns>(_ => throw failure); + + var element = new WatermarkElement( + RemoteWatermarkOptions(), + fetcher, + Substitute.For()); + + // must not throw -- a killed graphics element must never propagate into the stream + await element.InitializeAsync(Context(), CancellationToken.None); + + element.IsFinished.ShouldBeTrue(); + } + + // the counterpart: caller cancellation is not a fetch failure, but it must still not escape + // into the streaming pipeline as an unhandled exception + [Test] + public async Task Should_Disable_The_Watermark_When_The_Caller_Cancels() + { + var fetcher = Substitute.For(); + fetcher.Fetch(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new OperationCanceledException()); + + var element = new WatermarkElement(RemoteWatermarkOptions(), fetcher, Substitute.For()); + + await element.InitializeAsync(Context(), CancellationToken.None); + + element.IsFinished.ShouldBeTrue(); + } + + // a remote path really does route to the fetcher -- without this the tests above would pass + // even if LoadImage stopped recognising http(s) urls + [Test] + public async Task Should_Route_A_Remote_Path_Through_The_Fetcher() + { + var fetcher = Substitute.For(); + fetcher.Fetch(Arg.Any(), Arg.Any()) + .Returns>(_ => throw new TimeoutException()); + + var element = new WatermarkElement(RemoteWatermarkOptions(), fetcher, Substitute.For()); + + await element.InitializeAsync(Context(), CancellationToken.None); + + await fetcher.Received(1).Fetch(new Uri(RemoteLogo), Arg.Any()); + } + + // ...and a local path must not touch the network at all + [Test] + public async Task Should_Not_Use_The_Fetcher_For_A_Local_Path() + { + var fetcher = Substitute.For(); + + var options = new WatermarkOptions(Watermark(), "/no/such/logo.png", Option.None); + var element = new WatermarkElement(options, fetcher, Substitute.For()); + + await element.InitializeAsync(Context(), CancellationToken.None); + + await fetcher.DidNotReceive().Fetch(Arg.Any(), Arg.Any()); + element.IsFinished.ShouldBeTrue(); + } + + + // --- the RETENTION budget is wired in, and is remote-only (M4 from re-review) --- + // + // These two differ ONLY in the scale percent, so together they detect deletion of the + // `if (isRemoteUri) EnsureScaledFramesAffordable(...)` call site: without it the first case + // would succeed. The source is trivial to decode (300 x 64x64 = 1.2 MP, well inside the decode + // budget) but retains ~2.5 GB of SKBitmap once every frame is scaled to 1080p. + + [Test] + public async Task Should_Disable_The_Watermark_When_Scaled_Frames_Blow_The_Retention_Budget() + { + var element = new WatermarkElement( + RemoteWatermarkOptions(widthPercent: 100), + FetcherReturning(Apng(64, 64, 300)), + Substitute.For()); + + await element.InitializeAsync(Context(), CancellationToken.None); + + element.IsFinished.ShouldBeTrue(); + } + + [Test] + public async Task Should_Keep_The_Watermark_When_The_Same_Animation_Is_Scaled_Small() + { + var element = new WatermarkElement( + RemoteWatermarkOptions(widthPercent: 10), + FetcherReturning(Apng(64, 64, 300)), + Substitute.For()); + + await element.InitializeAsync(Context(), CancellationToken.None); + + element.IsFinished.ShouldBeFalse(); + } + + private static IRemoteImageFetcher FetcherReturning(Stream stream) + { + var fetcher = Substitute.For(); + fetcher.Fetch(Arg.Any(), Arg.Any()).Returns(stream); + return fetcher; + } + + 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; + } + + private static WatermarkOptions RemoteWatermarkOptions(double widthPercent = 10) => + new(Watermark(widthPercent), RemoteLogo, Option.None); + + private static ChannelWatermark Watermark(double widthPercent = 10) => + new() + { + Name = "test", + Mode = ChannelWatermarkMode.Permanent, + Location = WatermarkLocation.BottomRight, + Size = WatermarkSize.Scaled, + WidthPercent = widthPercent, + HorizontalMarginPercent = 5, + VerticalMarginPercent = 5, + Opacity = 100 + }; + + private static GraphicsEngineContext Context() => + new( + "1", + null, + [], + [], + new Resolution { Width = 1920, Height = 1080 }, + new Resolution { Width = 1920, Height = 1080 }, + new FrameRate("30"), + DateTimeOffset.UnixEpoch, + DateTimeOffset.UnixEpoch, + TimeSpan.Zero, + TimeSpan.FromMinutes(1), + TimeSpan.FromMinutes(1)); +} diff --git a/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteImageFetcherTests.cs b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteImageFetcherTests.cs new file mode 100644 index 000000000..1778ffe5a --- /dev/null +++ b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteImageFetcherTests.cs @@ -0,0 +1,179 @@ +using System.Buffers; +using System.Net; +using System.Net.Http.Headers; +using ErsatzTV.Infrastructure.Streaming; +using Microsoft.Extensions.Logging; +using Microsoft.IO; +using NSubstitute; +using NUnit.Framework; +using Shouldly; + +namespace ErsatzTV.Infrastructure.Tests.Streaming; + +[TestFixture] +public class HttpRemoteImageFetcherTests +{ + private static readonly Uri ImageUri = new("https://example.com/logo.png"); + + [Test] + public async Task Should_Return_The_Buffered_Body_On_Success() + { + byte[] payload = [1, 2, 3, 4, 5]; + HttpRemoteImageFetcher fetcher = FetcherReturning(Ok(payload, "image/png")); + + await using Stream result = await fetcher.Fetch(ImageUri, CancellationToken.None); + + result.Position.ShouldBe(0); + var read = new byte[payload.Length]; + await result.ReadExactlyAsync(read); + read.ShouldBe(payload); + } + + [Test] + public async Task Should_Throw_On_An_Error_Status() + { + HttpRemoteImageFetcher fetcher = FetcherReturning(new HttpResponseMessage(HttpStatusCode.NotFound)); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, CancellationToken.None)); + } + + // an html error page served with a 200 must never reach the decoder + [Test] + public async Task Should_Reject_A_Non_Image_Content_Type() + { + HttpRemoteImageFetcher fetcher = FetcherReturning(Ok([1, 2, 3], "text/html")); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, CancellationToken.None)); + } + + // hosts that omit the header, and static file servers that default to octet-stream, are common + // enough that rejecting them would break working logos for no security gain -- ImageSharp + // decodes by magic bytes, and the wire-size + decode-budget caps are the real protection. + [TestCase(null)] + [TestCase("application/octet-stream")] + public async Task Should_Accept_A_Missing_Or_Generic_Content_Type(string mediaType) + { + HttpRemoteImageFetcher fetcher = FetcherReturning(Ok([1, 2, 3], mediaType)); + + await using Stream result = await fetcher.Fetch(ImageUri, CancellationToken.None); + + result.Length.ShouldBe(3); + } + + // the advertised length is the cheap reject: the body must not be pulled at all + [Test] + public async Task Should_Reject_An_Oversized_Content_Length_Without_Reading_The_Body() + { + var body = new TrackingStream(HttpRemoteImageFetcher.MaxImageBytes + 1); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(body) }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); + response.Content.Headers.ContentLength = HttpRemoteImageFetcher.MaxImageBytes + 1; + + HttpRemoteImageFetcher fetcher = FetcherReturning(response); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, CancellationToken.None)); + body.BytesRead.ShouldBe(0); + } + + // ...and a host that lies about (or omits) Content-Length is still capped, because the copy + // itself counts bytes. (the DECODE bomb -- small on the wire, huge in memory -- is a different + // problem, bounded by the decode/retention budgets in ImageElementBase, not by this.) + [Test] + public async Task Should_Cap_A_Body_That_Does_Not_Advertise_Its_Length() + { + var body = new ChunkedZeroStream(HttpRemoteImageFetcher.MaxImageBytes * 2); + var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(body) }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); + response.Content.Headers.ContentLength = null; + + HttpRemoteImageFetcher fetcher = FetcherReturning(response); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, CancellationToken.None)); + + // proves this went through the COPY cap and not the Content-Length early reject: the body + // really was read, and it stopped at the limit rather than draining all 20 MiB. + body.Position.ShouldBeGreaterThan(0); + + // the over-read bound is ONE RENTED BUFFER, and ArrayPool.Rent(81920) actually hands back + // 131072 -- deriving it keeps this honest if the request size or the pool bucketing changes. + byte[] rented = ArrayPool.Shared.Rent(81920); + ArrayPool.Shared.Return(rented); + body.Position.ShouldBeLessThanOrEqualTo(HttpRemoteImageFetcher.MaxImageBytes + rented.Length); + } + + // a host that accepts the connection and then hangs must not stall stream startup forever + [Test] + public async Task Should_Time_Out_A_Hanging_Host() + { + var fetcher = new HttpRemoteImageFetcher( + new StubHttpClientFactory(new HangingHttpMessageHandler()), + new RecyclableMemoryStreamManager(), + Substitute.For>(), + TimeSpan.FromMilliseconds(100)); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, CancellationToken.None)); + } + + + // THE headline claim: under ResponseHeadersRead the body read falls outside HttpClient.Timeout, + // so a host that returns headers promptly and then drips the body must still hit our deadline. + // the hanging-host test above only covers the pre-headers case, which a plain HttpClient.Timeout + // would already bound -- this is the one that pins the actual design. + [Test] + public async Task Should_Time_Out_A_Slow_Drip_Body() + { + var response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StreamContent(new SlowDripStream()) + }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png"); + + var fetcher = new HttpRemoteImageFetcher( + new StubHttpClientFactory(new FixedResponseHttpMessageHandler(response)), + new RecyclableMemoryStreamManager(), + Substitute.For>(), + TimeSpan.FromMilliseconds(200)); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, CancellationToken.None)); + } + + [Test] + public async Task Should_Throw_On_Transport_Failure() + { + var fetcher = new HttpRemoteImageFetcher( + new StubHttpClientFactory(new ThrowingHttpMessageHandler(new HttpRequestException("no route to host"))), + new RecyclableMemoryStreamManager(), + Substitute.For>()); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, CancellationToken.None)); + } + + // caller cancellation (shutdown / client disconnect) is a genuine signal and must stay an + // OperationCanceledException rather than being relabelled as our timeout + [Test] + public async Task Should_Propagate_Caller_Cancellation() + { + var fetcher = new HttpRemoteImageFetcher( + new StubHttpClientFactory(new HangingHttpMessageHandler()), + new RecyclableMemoryStreamManager(), + Substitute.For>()); + + using var cts = new CancellationTokenSource(); + await cts.CancelAsync(); + + await Should.ThrowAsync(() => fetcher.Fetch(ImageUri, cts.Token)); + } + + private static HttpResponseMessage Ok(byte[] payload, string mediaType) + { + var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(payload) }; + response.Content.Headers.ContentType = mediaType is null ? null : new MediaTypeHeaderValue(mediaType); + return response; + } + + private static HttpRemoteImageFetcher FetcherReturning(HttpResponseMessage response) => + new( + new StubHttpClientFactory(new FixedResponseHttpMessageHandler(response)), + new RecyclableMemoryStreamManager(), + Substitute.For>()); +} diff --git a/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs index 563e09446..2bd78b655 100644 --- a/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs +++ b/ErsatzTV.Infrastructure.Tests/Streaming/HttpRemoteStreamProberTests.cs @@ -161,87 +161,4 @@ public class HttpRemoteStreamProberTests new( new StubHttpClientFactory(new StatusCodeHttpMessageHandler(statusCode, finalUri)), Substitute.For>()); - - private sealed class StubHttpClientFactory(HttpMessageHandler handler) : IHttpClientFactory - { - public HttpClient CreateClient(string name) => new(handler, disposeHandler: false); - } - - private sealed class StatusCodeHttpMessageHandler(HttpStatusCode statusCode, string finalUri = null) - : HttpMessageHandler - { - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - - // HttpClient rewrites RequestMessage.RequestUri to the final hop when it follows a - // redirect; finalUri lets a test stand in for "the media server answered this". - if (finalUri is not null) - { - request.RequestUri = new Uri(finalUri); - } - - return Task.FromResult(new HttpResponseMessage(statusCode) { RequestMessage = request }); - } - } - - private sealed class FixedResponseHttpMessageHandler(HttpResponseMessage response) : HttpMessageHandler - { - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) - { - cancellationToken.ThrowIfCancellationRequested(); - response.RequestMessage = request; - return Task.FromResult(response); - } - } - - /// A readable stream that records how many bytes were actually pulled from it. - private sealed class TrackingStream(long length) : Stream - { - public int BytesRead { get; private set; } - - public override bool CanRead => true; - public override bool CanSeek => false; - public override bool CanWrite => false; - public override long Length => length; - - public override long Position - { - get => BytesRead; - set => throw new NotSupportedException(); - } - - public override int Read(byte[] buffer, int offset, int count) - { - if (BytesRead >= length) - { - return 0; - } - - int toRead = (int)Math.Min(count, length - BytesRead); - Array.Clear(buffer, offset, toRead); - BytesRead += toRead; - return toRead; - } - - public override void Flush() - { - } - - public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); - public override void SetLength(long value) => throw new NotSupportedException(); - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - } - - private sealed class ThrowingHttpMessageHandler(Exception exception) : HttpMessageHandler - { - protected override Task SendAsync( - HttpRequestMessage request, - CancellationToken cancellationToken) => - Task.FromException(exception); - } } diff --git a/ErsatzTV.Infrastructure.Tests/Streaming/HttpTestDoubles.cs b/ErsatzTV.Infrastructure.Tests/Streaming/HttpTestDoubles.cs new file mode 100644 index 000000000..3738b8fcb --- /dev/null +++ b/ErsatzTV.Infrastructure.Tests/Streaming/HttpTestDoubles.cs @@ -0,0 +1,186 @@ +using System.Diagnostics; +using System.Net; + +namespace ErsatzTV.Infrastructure.Tests.Streaming; + +/// +/// Shared fakes for the HTTP-backed streaming services. Extracted from +/// when +/// needed the same harness. (ersatztv#511) +/// +internal sealed class StubHttpClientFactory(HttpMessageHandler handler) : IHttpClientFactory +{ + public HttpClient CreateClient(string name) => new(handler, disposeHandler: false); +} + +internal sealed class StatusCodeHttpMessageHandler(HttpStatusCode statusCode, string finalUri = null) + : HttpMessageHandler +{ + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + + // HttpClient rewrites RequestMessage.RequestUri to the final hop when it follows a + // redirect; finalUri lets a test stand in for "the media server answered this". + if (finalUri is not null) + { + request.RequestUri = new Uri(finalUri); + } + + return Task.FromResult(new HttpResponseMessage(statusCode) { RequestMessage = request }); + } +} + +internal sealed class FixedResponseHttpMessageHandler(HttpResponseMessage response) : HttpMessageHandler +{ + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + response.RequestMessage = request; + return Task.FromResult(response); + } +} + +/// A readable stream that records how many bytes were actually pulled from it. +internal sealed class TrackingStream(long length) : Stream +{ + public int BytesRead { get; private set; } + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => length; + + public override long Position + { + get => BytesRead; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (BytesRead >= length) + { + return 0; + } + + int toRead = (int)Math.Min(count, length - BytesRead); + Array.Clear(buffer, offset, toRead); + BytesRead += toRead; + return toRead; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} + +/// +/// A readable stream that returns headers-worth of data instantly and then drips forever — +/// the case that leaves outside +/// . +/// +internal sealed class SlowDripStream : Stream +{ + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => 0; + set => throw new NotSupportedException(); + } + + public override async ValueTask ReadAsync( + Memory buffer, + CancellationToken cancellationToken = default) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + throw new UnreachableException(); + } + + public override int Read(byte[] buffer, int offset, int count) => + ReadAsync(buffer.AsMemory(offset, count), CancellationToken.None).AsTask().GetAwaiter().GetResult(); + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} + +internal sealed class ThrowingHttpMessageHandler(Exception exception) : HttpMessageHandler +{ + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) => + Task.FromException(exception); +} + +/// +/// A handler that never completes until the request is cancelled — stands in for a host that +/// accepts the connection and then hangs. +/// +internal sealed class HangingHttpMessageHandler : HttpMessageHandler +{ + protected override async Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken) + { + await Task.Delay(Timeout.Infinite, cancellationToken); + throw new UnreachableException(); + } +} + +/// +/// A readable stream that yields bytes but only ever a little at a +/// time, so a size cap has to be enforced during the copy rather than from Content-Length. +/// +internal sealed class ChunkedZeroStream(long length, int chunkSize = 4096) : Stream +{ + private long _position; + + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => false; + public override long Length => length; + + public override long Position + { + get => _position; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + if (_position >= length) + { + return 0; + } + + int toRead = (int)Math.Min(Math.Min(count, chunkSize), length - _position); + Array.Clear(buffer, offset, toRead); + _position += toRead; + return toRead; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/ErsatzTV.Infrastructure/Streaming/Graphics/GraphicsEngine.cs b/ErsatzTV.Infrastructure/Streaming/Graphics/GraphicsEngine.cs index 47af8670e..fe8667a9d 100644 --- a/ErsatzTV.Infrastructure/Streaming/Graphics/GraphicsEngine.cs +++ b/ErsatzTV.Infrastructure/Streaming/Graphics/GraphicsEngine.cs @@ -16,6 +16,7 @@ public class GraphicsEngine( ITempFilePool tempFilePool, IConfigElementRepository configElementRepository, ILocalStatisticsProvider localStatisticsProvider, + IRemoteImageFetcher remoteImageFetcher, ILogger logger) : IGraphicsEngine { @@ -33,7 +34,10 @@ public class GraphicsEngine( switch (element) { case WatermarkElementContext watermarkElementContext: - var watermark = new WatermarkElement(watermarkElementContext.Options, logger); + var watermark = new WatermarkElement( + watermarkElementContext.Options, + remoteImageFetcher, + logger); if (watermark.IsValid) { elements.Add(watermark); @@ -42,7 +46,8 @@ public class GraphicsEngine( break; case ImageElementContext imageElementContext: - elements.Add(new ImageElement(imageElementContext.ImageElement, logger)); + elements.Add( + new ImageElement(imageElementContext.ImageElement, remoteImageFetcher, logger)); break; case TextElementDataContext textElementContext: @@ -63,23 +68,23 @@ public class GraphicsEngine( break; case SubtitleElementDataContext subtitleElementContext: - { - var variables = context.TemplateVariables.ToDictionary(); - foreach (KeyValuePair variable in subtitleElementContext.Variables) { - variables.Add(variable.Key, variable.Value); + var variables = context.TemplateVariables.ToDictionary(); + foreach (KeyValuePair variable in subtitleElementContext.Variables) + { + variables.Add(variable.Key, variable.Value); + } + + var subtitleElement = new SubtitleElement( + templateFunctions, + tempFilePool, + subtitleElementContext.SubtitleElement, + variables, + logger); + + elements.Add(subtitleElement); + break; } - - var subtitleElement = new SubtitleElement( - templateFunctions, - tempFilePool, - subtitleElementContext.SubtitleElement, - variables, - logger); - - elements.Add(subtitleElement); - break; - } } } diff --git a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElement.cs b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElement.cs index 1a8d3bb82..9cc71272a 100644 --- a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElement.cs +++ b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElement.cs @@ -6,7 +6,10 @@ using SkiaSharp; namespace ErsatzTV.Infrastructure.Streaming.Graphics; -public class ImageElement(ImageGraphicsElement imageGraphicsElement, ILogger logger) : ImageElementBase +public class ImageElement( + ImageGraphicsElement imageGraphicsElement, + IRemoteImageFetcher remoteImageFetcher, + ILogger logger) : ImageElementBase(remoteImageFetcher) { private Option _maybeOpacityExpression; private float _opacity; diff --git a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs index f8dacfc35..d323027d4 100644 --- a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs +++ b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/ImageElementBase.cs @@ -1,5 +1,6 @@ using System.Runtime.InteropServices; using ErsatzTV.Core.Domain; +using ErsatzTV.Core.Interfaces.Streaming; using ErsatzTV.FFmpeg.State; using SixLabors.ImageSharp; using SixLabors.ImageSharp.Formats; @@ -14,8 +15,32 @@ using Image = SixLabors.ImageSharp.Image; namespace ErsatzTV.Infrastructure.Streaming.Graphics; -public abstract class ImageElementBase : GraphicsElement, IDisposable +public abstract class ImageElementBase(IRemoteImageFetcher remoteImageFetcher) : GraphicsElement, IDisposable { + /// + /// Ceiling on TOTAL decoded pixels for a remote image — width x height x frames, as one + /// product. Checking dimensions and frame count independently does not bound the decode: + /// 2500x2500 x 600 frames is 60 KiB on the wire, passes a 50 MP dimension check and a 600 + /// frame check, and costs ~14 GiB to decode. Only the product catches that. + /// 8K is ~33 MP, so a single large still fits comfortably. + /// + internal const long MaxRemoteDecodedPixels = 50_000_000; + + /// + /// Frame ceiling for a remote animation, kept alongside the product budget as a cheap, + /// legible guard against absurd frame counts of tiny frames. + /// + internal const int MaxRemoteFrames = 600; + + /// + /// Ceiling on total pixels RETAINED after scaling — frames x scaled width x scaled height. + /// Independent of the source budget above: a 100x100 source is trivial to decode but, at 600 + /// frames scaled to 1920x1080, retains ~5 GB of . At 4 bytes per + /// pixel this bounds retention at ~800 MB, which still allows ~96 full-frame 1080p frames + /// (~3s at 30fps) or 600 frames of a 577x577 logo. + /// + internal const long MaxRemoteScaledPixels = 200_000_000; + private readonly List _frameDelays = []; private readonly List _scaledFrames = []; private double _animatedDurationSeconds; @@ -49,9 +74,8 @@ public abstract class ImageElementBase : GraphicsElement, IDisposable if (isRemoteUri) { - using var client = new HttpClient(); - await using Stream imageStream = await client.GetStreamAsync(uriResult, cancellationToken); - _sourceImage = await Image.LoadAsync(imageStream, cancellationToken); + await using Stream imageStream = await remoteImageFetcher.Fetch(uriResult, cancellationToken); + _sourceImage = await DecodeRemoteImage(imageStream, uriResult, cancellationToken); } else { @@ -67,6 +91,11 @@ public abstract class ImageElementBase : GraphicsElement, IDisposable scaledHeight = (int)(scaledWidth * aspectRatio); } + if (isRemoteUri) + { + EnsureScaledFramesAffordable(_sourceImage.Frames.Count, scaledWidth, scaledHeight, uriResult); + } + (int horizontalMargin, int verticalMargin) = placeWithinSourceContent ? SourceContentMargins( squarePixelFrameSize, @@ -103,6 +132,140 @@ public abstract class ImageElementBase : GraphicsElement, IDisposable } } + /// + /// 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) + /// + 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.) + EnsureDimensionsAffordable(info.Width, info.Height, uri); + + int affordableFrames = 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. + EnsureDecodeAffordable(image.Width, image.Height, image.Frames.Count, uri); + return image; + } + catch + { + image.Dispose(); + throw; + } + } + + /// Rejects a single frame that cannot fit the decode budget on its own. + internal static void EnsureDimensionsAffordable(int width, int height, Uri uri) + { + long pixels = (long)width * height; + if (pixels > MaxRemoteDecodedPixels) + { + throw new InvalidOperationException( + $"Remote image {uri} is {width}x{height} ({pixels} pixels), over the " + + $"{MaxRemoteDecodedPixels} pixel limit"); + } + } + + /// + /// How many frames of this size the decode budget affords. Used to cap the DECODER, so the + /// bound does not depend on the header's frame count being honest. + /// + internal static int AffordableFrames(int width, int height) + { + long perFrame = Math.Max((long)width * height, 1); + return (int)Math.Clamp(MaxRemoteDecodedPixels / perFrame, 1, MaxRemoteFrames); + } + + /// + /// The decode-budget policy, kept free of I/O so the arithmetic can be tested at every + /// boundary without materializing multi-gigabyte images. Call this with the number of frames + /// the decoder ACTUALLY produced — never with a header-reported count, which can be zero for + /// an animation the decoder then expands to hundreds of frames. + /// + internal static void EnsureDecodeAffordable(int width, int height, int frameCount, Uri uri) + { + int frames = Math.Max(frameCount, 1); + + if (frames > MaxRemoteFrames) + { + throw new InvalidOperationException( + $"Remote image {uri} has {frames} frames, over the {MaxRemoteFrames} frame limit"); + } + + // THE PRODUCT is the real bound. Checking dimensions and frames separately lets a 60 KiB + // 2500x2500 x600 GIF through at a ~14 GiB decode cost. (Found by adversarial re-review of + // the first fix for this, which checked them independently.) + long totalPixels = (long)width * height * frames; + if (totalPixels > MaxRemoteDecodedPixels) + { + throw new InvalidOperationException( + $"Remote image {uri} decodes to {width}x{height} x{frames} frames " + + $"({totalPixels} pixels), over the {MaxRemoteDecodedPixels} pixel limit"); + } + } + + /// + /// Bounds what is RETAINED after scaling. Separate from the source budget because the two + /// are independent: a cheap-to-decode 100x100 source scaled to 1920x1080 across 600 frames + /// retains ~5 GB. Only applied to remote images, matching the rest of this guard. + /// + internal static void EnsureScaledFramesAffordable(int frameCount, int scaledWidth, int scaledHeight, Uri uri) + { + long retainedPixels = (long)Math.Max(frameCount, 1) * scaledWidth * scaledHeight; + if (retainedPixels > MaxRemoteScaledPixels) + { + throw new InvalidOperationException( + $"Remote image {uri} scales to {frameCount} frames of {scaledWidth}x{scaledHeight} " + + $"({retainedPixels} pixels), over the {MaxRemoteScaledPixels} pixel limit"); + } + } + protected static SKBitmap ToSkiaBitmap(Image image) { using Image rgbaImage = image.CloneAs(); diff --git a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/WatermarkElement.cs b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/WatermarkElement.cs index e32e6ef2e..e7b339aaf 100644 --- a/ErsatzTV.Infrastructure/Streaming/Graphics/Image/WatermarkElement.cs +++ b/ErsatzTV.Infrastructure/Streaming/Graphics/Image/WatermarkElement.cs @@ -17,7 +17,8 @@ public class WatermarkElement : ImageElementBase private Option _maybeOpacityExpression; private float _opacity; - public WatermarkElement(WatermarkOptions watermarkOptions, ILogger logger) + public WatermarkElement(WatermarkOptions watermarkOptions, IRemoteImageFetcher remoteImageFetcher, ILogger logger) + : base(remoteImageFetcher) { _logger = logger; // TODO: better model coming in here? diff --git a/ErsatzTV.Infrastructure/Streaming/HttpRemoteImageFetcher.cs b/ErsatzTV.Infrastructure/Streaming/HttpRemoteImageFetcher.cs new file mode 100644 index 000000000..42da7073c --- /dev/null +++ b/ErsatzTV.Infrastructure/Streaming/HttpRemoteImageFetcher.cs @@ -0,0 +1,157 @@ +using System.Buffers; +using ErsatzTV.Core.Interfaces.Streaming; +using Microsoft.Extensions.Logging; +using Microsoft.IO; + +namespace ErsatzTV.Infrastructure.Streaming; + +/// +/// Fetches a remote graphics-engine image over HTTP with a bounded timeout and a bounded size. +/// +/// +/// This runs during graphics-engine element initialization, which happens inside stream startup +/// while ffmpeg waits on the pipe — so an unbounded fetch stalls the tune. Every failure here is +/// surfaced as an exception and the calling element disables itself. (ersatztv#511) +/// +public class HttpRemoteImageFetcher : IRemoteImageFetcher +{ + /// Named configured with the redirect cap in Startup. + public const string HttpClientName = "RemoteImage"; + + /// + /// Covers the whole exchange — connect, headers AND body — because the body read happens + /// outside under , + /// so a slow-drip host would otherwise hang forever. (docs/decisions.md, #289) + /// + internal static readonly TimeSpan DefaultFetchTimeout = TimeSpan.FromSeconds(10); + + /// + /// Wire-size cap. A channel logo or overlay is orders of magnitude smaller than this. + /// This bounds transfer and buffering only — it is NOT decode-bomb protection, since a bomb + /// is by definition small on the wire. That check lives in + /// ImageElementBase.DecodeRemoteImage, which reads the declared dimensions and frame + /// count from the header before the decoder allocates. + /// + internal const long MaxImageBytes = 10 * 1024 * 1024; + + private readonly TimeSpan _fetchTimeout; + private readonly IHttpClientFactory _httpClientFactory; + private readonly ILogger _logger; + private readonly RecyclableMemoryStreamManager _memoryStreamManager; + + public HttpRemoteImageFetcher( + IHttpClientFactory httpClientFactory, + RecyclableMemoryStreamManager memoryStreamManager, + ILogger logger) + : this(httpClientFactory, memoryStreamManager, logger, DefaultFetchTimeout) + { + } + + // the timeout is only parameterized so a test can prove the deadline fires without waiting the + // real ten seconds; production always goes through the constructor above. + internal HttpRemoteImageFetcher( + IHttpClientFactory httpClientFactory, + RecyclableMemoryStreamManager memoryStreamManager, + ILogger logger, + TimeSpan fetchTimeout) + { + _httpClientFactory = httpClientFactory; + _memoryStreamManager = memoryStreamManager; + _logger = logger; + _fetchTimeout = fetchTimeout; + } + + public async Task Fetch(Uri uri, CancellationToken cancellationToken) + { + using var timeoutCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeoutCts.CancelAfter(_fetchTimeout); + + try + { + using HttpClient client = _httpClientFactory.CreateClient(HttpClientName); + + // set here, not only in the DI registration, so the deadline cannot silently widen to + // HttpClient's 100s default if that registration is ever dropped or reordered. the + // factory hands back a fresh wrapper each call, so mutating it is safe. + client.Timeout = Timeout.InfiniteTimeSpan; + using HttpResponseMessage response = await client.GetAsync( + uri, + HttpCompletionOption.ResponseHeadersRead, + timeoutCts.Token); + + response.EnsureSuccessStatusCode(); + + string mediaType = response.Content.Headers.ContentType?.MediaType; + if (!IsAcceptableMediaType(mediaType)) + { + throw new InvalidOperationException( + $"Remote image {uri} returned content type '{mediaType}', which is not an image"); + } + + // the advertised length is a cheap early reject; it is not trusted, because it can be + // absent or a lie. the copy below is what actually enforces the cap. + long? contentLength = response.Content.Headers.ContentLength; + if (contentLength > MaxImageBytes) + { + throw new InvalidOperationException( + $"Remote image {uri} advertises {contentLength} bytes, over the {MaxImageBytes} byte limit"); + } + + await using Stream source = await response.Content.ReadAsStreamAsync(timeoutCts.Token); + return await CopyCapped(source, uri, timeoutCts.Token); + } + catch (OperationCanceledException canceled) when (!cancellationToken.IsCancellationRequested) + { + // OUR deadline fired, not the caller's. re-thrown as a TimeoutException so the element's + // warning names the real cause; caller cancellation (shutdown / client disconnect) still + // propagates as OperationCanceledException. + _logger.LogWarning( + "Timed out after {Seconds}s fetching remote image {Uri}", + _fetchTimeout.TotalSeconds, + uri); + + throw new TimeoutException($"Timed out fetching remote image {uri}", canceled); + } + } + + // a missing content type is allowed (some hosts omit it) and octet-stream is allowed (a common + // default for statically served files). anything else that is positively NOT an image -- an html + // error page, say -- is rejected before it reaches the decoder. + private static bool IsAcceptableMediaType(string mediaType) => + string.IsNullOrWhiteSpace(mediaType) + || mediaType.StartsWith("image/", StringComparison.OrdinalIgnoreCase) + || mediaType.Equals("application/octet-stream", StringComparison.OrdinalIgnoreCase); + + private async Task CopyCapped(Stream source, Uri uri, CancellationToken cancellationToken) + { + MemoryStream buffer = _memoryStreamManager.GetStream(nameof(HttpRemoteImageFetcher)); + byte[] chunk = ArrayPool.Shared.Rent(81920); + + try + { + int read; + while ((read = await source.ReadAsync(chunk.AsMemory(), cancellationToken)) > 0) + { + if (buffer.Length + read > MaxImageBytes) + { + throw new InvalidOperationException( + $"Remote image {uri} exceeds the {MaxImageBytes} byte limit"); + } + + await buffer.WriteAsync(chunk.AsMemory(0, read), cancellationToken); + } + } + catch + { + await buffer.DisposeAsync(); + throw; + } + finally + { + ArrayPool.Shared.Return(chunk); + } + + buffer.Position = 0; + return buffer; + } +} diff --git a/ErsatzTV/Startup.cs b/ErsatzTV/Startup.cs index a26e1fe5a..757c746a4 100644 --- a/ErsatzTV/Startup.cs +++ b/ErsatzTV/Startup.cs @@ -686,6 +686,21 @@ public class Startup services.AddHttpClient("RefitCustomClient").AddHttpMessageHandler(); + // graphics-engine remote images (channel-logo watermarks and image elements). the client + // timeout is INFINITE on purpose: under ResponseHeadersRead the body read falls outside + // HttpClient.Timeout, so HttpRemoteImageFetcher owns the deadline with a linked CTS that + // covers headers AND body. the fetcher re-asserts that on the client it gets, so losing + // this line widens nothing; what is ONLY configurable here is the redirect cap, since it + // lives on the handler. redirects stay enabled (logo hosts and CDNs use them) but are + // capped well below the default 50 hops. (ersatztv#511) + services.AddHttpClient(HttpRemoteImageFetcher.HttpClientName) + .ConfigureHttpClient(c => c.Timeout = Timeout.InfiniteTimeSpan) + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler + { + AllowAutoRedirect = true, + MaxAutomaticRedirections = 3 + }); + services.Configure(Configuration.GetSection("Trakt")); services.AddResponseCompression(options => { options.EnableForHttps = true; }); @@ -1085,6 +1100,7 @@ public class Startup services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); services.AddScoped(); services.AddScoped(); services.AddScoped(); diff --git a/docs/decisions.md b/docs/decisions.md index ff65bf807..c36b173fc 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -103,6 +103,7 @@ in-file entries. - [2026-07-19 — Health-check results are TTL-cached; `?refresh=true` forces a fresh run (#431)](#2026-07-19--health-check-results-are-ttl-cached-refreshtrue-forces-a-fresh-run-431) - [2026-07-19 — CI `test` job reports a sampled true peak-anon, not cache-inflated `memory.peak` (#412)](#2026-07-19--ci-test-job-reports-a-sampled-true-peak-anon-not-cache-inflated-memorypeak-412) - [2026-07-20 — External-URL channel logos pass through to the graphics engine; never `File.Exists`-gated, never ffmpeg-native (#502)](#2026-07-20--external-url-channel-logos-pass-through-to-the-graphics-engine-never-fileexists-gated-never-ffmpeg-native-502) +- [2026-07-20 — Remote graphics-engine images are fetched through a bounded, pooled `IRemoteImageFetcher`; re-fetched per element init, not cached (#511)](#2026-07-20--remote-graphics-engine-images-are-fetched-through-a-bounded-pooled-iremoteimagefetcher-re-fetched-per-element-init-not-cached-511) --- @@ -2593,3 +2594,136 @@ read-only PR #76 rather than rebasing it. Full doc: `docs/mcp.md`. Decisions fro values discoverable. **Deferred as too-large for a cautious v0.1** (not a contract gap): the ~40-field schedule-item / playout replace-list writes. Redesign workflow tools (#63–#68) stay deferred until their backend endpoints exist. No `/api` endpoint was added, so no OpenAPI regen. +## 2026-07-20 — Remote graphics-engine images are fetched through a bounded, pooled `IRemoteImageFetcher`; re-fetched per element init, not cached (#511) + +`ImageElementBase.LoadImage` fetched `http(s)` images with a throwaway `new HttpClient()` and +`GetStreamAsync`. That is unbounded in three directions at once — no timeout override (the 100s +`HttpClient` default), no response size cap, and a new connection pool per element — and it runs +*inside stream startup*, while ffmpeg waits on the pipe. #502 routed ordinary channel-logo +watermarks onto that path, which is what made a pre-existing weakness worth hardening. + +The fetch now lives behind **`IRemoteImageFetcher`** (`HttpRemoteImageFetcher`), deliberately +modelled on the neighbouring `IRemoteStreamProber`: a Core interface, an Infrastructure +implementation over `IHttpClientFactory`, and a `CancellationTokenSource.CreateLinkedTokenSource` + +`CancelAfter` deadline. + +**The deadline covers the body, not just the headers.** The named client is registered with +`Timeout = InfiniteTimeSpan` and the linked token is threaded into `GetAsync` *and* every stream +read, because under `HttpCompletionOption.ResponseHeadersRead` the body read falls outside +`HttpClient.Timeout` — a slow-drip host would otherwise hang forever. Same mechanic as #289. + +**The size cap is enforced during the copy, not from `Content-Length`.** The advertised length is +only a cheap early reject; it can be absent or a lie, so the byte counter in the copy loop is what +actually bounds transfer and buffering. (It bounds the *wire*, not the decode — see below.) Both +paths are covered by tests, and both were negative-controlled (disabling the checks fails exactly +those two tests). + +**The byte cap does not bound decoding, so there are two further budgets — and the decode bound is +imposed on the DECODER, not read from the header.** A decompression bomb is by definition small on +the wire: a 4 KB PNG can declare 30000x30000 (~3.6 GB to decode), and a 60 KiB GIF can declare +2500x2500 across 600 frames (~14 GiB). All of that passes `Content-Length`, the content-type check +and the 10 MiB copy cap in milliseconds. + +Getting this right took three attempts, and the two failures are the interesting part: + +1. The first version checked dimensions (50 MP) and frame count (600) **independently**. The + 2500x2500 x600 GIF above passes both while costing ~14 GiB. *Independent caps do not compose + into a budget* — the bound has to be on the PRODUCT. +2. The second version checked the product, but sourced the frame count from + `Image.IdentifyAsync`. **Measured on ImageSharp 3.1.12: an APNG reports + `FrameMetadataCollection.Count == 0` while the decoder produces every frame.** A 4000x4000 x600 + APNG is ~134 KiB on the wire, is charged as ONE frame (16 MP, comfortably inside the budget) and + decodes to ~36 GiB — 2.5x worse than the bomb that version was written to stop. Header-derived + limits are advisory; a limit the decoder does not enforce is not a limit. (GIF, WebP and TIFF + report honestly; PNG/APNG is the sole divergence, which is exactly why trusting the header is + untenable — you cannot audit every format.) + +So `DecodeRemoteImage` now: checks the header **dimensions** (which are trustworthy — a GIF whose +image descriptor exceeds its logical screen is clamped by the decoder, verified); derives how many +frames of that size the budget affords; passes that to **`DecoderOptions.MaxFrames`**, which the +decoder enforces regardless of what the header claimed; and then **re-verifies the real +`image.Frames.Count`** after decoding, disposing and rejecting if it is over. `MaxFrames` was +measured as honored by every animated decoder in play (APNG, GIF, WebP, TIFF), which is what makes +it a real bound rather than another advisory one. The code asks for `affordable + 2` so an +animation exactly at the limit still decodes in full while anything over it is visible to the +post-decode check; the slop is at most two frames, since `MaxFrames = N` yields `N` frames for +GIF/WebP/TIFF but `N-1` for APNG — the exact count varies by format, so only the upper bound is +relied on. + +- **Decode budget** — `width x height x frames <= 50 MP`, verified against the decoded image. +- **Retention budget** — `frames x scaledWidth x scaledHeight <= 200 MP` (~800 MB at 4 bytes/px), + checked once the scale is known. Independent of the decode budget in both directions: a 100x100 + source is trivial to decode but retains ~5 GB of `SKBitmap` at 600 frames scaled to 1920x1080, + because `LoadImage` clones and resizes every frame to output resolution and keeps them. + +**The enforced peak is up to 3x the nominal decode budget, and that is deliberate.** Detecting +"over the limit" requires actually decoding more frames than the limit allows, so the ceiling is +`(affordable + 2) x perFrame`. In the pathological case — one frame that alone fills the budget, +so `affordable = 1` — that is 150 MP (~600 MB at Rgba32, ~1.2 GB for a 16-bit TIFF at Rgba64) +rather than 50 MP. Bounded and survivable, against the ~36 GiB it replaces, and the alternative +(tightening the single-frame allowance to budget/3) would reject legitimate 8K stills at 33 MP. +Stated here because the previous three versions of this entry each claimed a bound the code did +not actually enforce. + +Other caveats: the budgets are in pixels, but a 16-bit PNG decodes to `Rgba64` (8 B/px), so the +byte cost doubles; the retention budget is per element, with no global ceiling across concurrent +streams; and 200 MP caps a full-frame 1080p animated overlay at ~96 frames (~3.2s at 30fps), which +is the one limit here that could plausibly bite a legitimate user rather than an attacker. + +**A workaround rides along with the header pre-pass.** `Image.IdentifyAsync` is called with +`MaxFrames = 1` — not as a limit, but because a *default* `Identify` throws +`InvalidImageContentException` on most APNGs (measured: 13 of 16 shapes, including files +ImageSharp's own `PngEncoder` wrote) that `Image.Load` reads back perfectly. Adding the pre-pass +without it would have silently disabled every animated-PNG logo that worked before this change — +a functional regression introduced *by* a hardening change, caught only because the reviewer swept +shapes rather than trusting the one the tests happened to use. + +Both budgets are enforced by pure functions (`EnsureDecodeAffordable`, `EnsureScaledFramesAffordable`) +so the arithmetic is tested at every boundary without materializing multi-gigabyte images, and both +call sites have wiring coverage (deleting either one fails a test). The APNG case is pinned by a +regression test that asserts the header under-reports *and* that the decode is rejected anyway. +Local images are deliberately exempt: those are files an operator put on disk, not bytes an +arbitrary host returned. + +**Content type is checked permissively.** A positively-not-an-image type (an HTML error page) is +rejected before the decoder sees it, but a *missing* type and `application/octet-stream` are +allowed — hosts omit the header and static file servers default to octet-stream often enough that +strictness would break working logos, while buying little: ImageSharp decodes by magic bytes, so +the size and dimension caps are what actually protect the decoder. + +**Redirects stay enabled but capped at 3** (the default is 50). Logo hosts and CDNs legitimately +redirect, so disabling them would break real configurations. + +**Not cached — re-fetched on each element initialization, i.e. per playout item.** #502's entry +noted that a fetch-once-into-the-image-cache design would also erase its per-frame cost asymmetry, +so caching was considered here and rejected *for now*: with pooling, a 10s ceiling and a 10 MiB cap, +one small GET per item transition is not a cost worth a cache's invalidation policy (when does an +admin's logo change take effect?) and lifetime questions. It also keeps the codebase-wide +"external artwork passes through, it is not downloaded into the image cache" convention #502 +established intact. Revisit only with a measurement showing the re-fetch actually costs something. + +**SSRF is accepted, not mitigated.** `ChannelValidations.ValidateLogo` still only checks the scheme, +so an admin-set logo URL remains a request origin inside the container's network, and the redirect +cap bounds hop count, not destination — an approved host can still redirect hop three to +`169.254.169.254` or `127.0.0.1:`. This is deliberate, and the load-bearing reason is that +the primitive is **blind**: the response body is never returned to any user, only decoded and +composited into a video frame, and failures surface only as a log line. Combined with the +capability being admin-only — and with LAN-hosted logos being a legitimate, common setup here, so a +private-IP denylist would break working installs — the exposure does not justify the breakage. +Revisit if logo URLs ever become settable through a lower-privilege path, or if any fetch result +becomes readable by a caller; note that "admin-only" is the weaker half of this argument and +blindness is the stronger. + +Failures are surfaced as exceptions rather than a failure value, because both call sites +(`WatermarkElement`, `ImageElement`) already wrap initialization in a catch that sets +`IsFinished` — so a dead, slow or oversized URL degrades to "element disabled" and never kills the +stream. `WatermarkElementRemoteImageTests` pins that contract, including that a local path never +touches the fetcher. + +The fetcher distinguishes its own deadline (rethrown as `TimeoutException`) from caller +cancellation (propagated as `OperationCanceledException`) via an exception filter on +`cancellationToken.IsCancellationRequested`. Be aware this distinction is currently **observationally +inert**: the elements' pre-existing blanket `catch (Exception)` swallows both one frame up, so a +shutdown mid-tune logs a spurious per-element warning. The filter is kept because it makes the +fetcher correct on its own terms and the log message names the real cause; making the elements +re-throw cancellation is a separate, pre-existing concern.