fix(511): budget decode by the PRODUCT, not by independent caps

Adversarial re-review of the first fix defeated its decode guard with a
measured payload: a 2500x2500 x600-frame GIF is ~60 KiB on the wire,
passes the 50 MP dimension check (6.25 MP) AND the 600-frame check
(exactly 600), and costs ~14 GiB to decode — strictly worse than the
30000x30000 PNG the guard was added to stop, at 1/60th the wire size.
Checking dimensions and frames independently never bounded the decode.

- decode budget is now width x height x frames <= 50 MP, as one product;
  a zero frame count is charged as one so an unenumerable header cannot
  zero it out
- new retention budget: frames x scaledWidth x scaledHeight <= 200 MP.
  Independent of the decode budget in both directions — a 100x100 source
  is trivial to decode but retains ~5 GB of SKBitmap once every frame is
  scaled to 1920x1080, since LoadImage clones and resizes each frame to
  output resolution and keeps them
- both budgets are pure functions (EnsureDecodeAffordable,
  EnsureScaledFramesAffordable) so the arithmetic is tested at every
  boundary without materializing multi-gigabyte images
- the frame guard had NO coverage before; it does now
- fail loudly on a non-seekable fetcher stream instead of letting
  Position throw NotSupportedException into the blanket catch
- test the copy over-read against the ACTUAL rented buffer length
  (ArrayPool.Rent(81920) returns 131072), not the requested 81920

docs/decisions.md corrected: it claimed the byte cap bounded the
decode-bomb surface and that the header check closed the class. Both
overstated. An append-only file that is confidently wrong is worse than
one with a gap.
This commit is contained in:
2026-07-21 01:04:25 +02:00
parent e132c422bb
commit 9a2096f340
4 changed files with 200 additions and 38 deletions
@@ -48,8 +48,10 @@ public class RemoteImageDecodeLimitTests
[Test]
public async Task Should_Accept_Dimensions_Exactly_At_The_Limit()
{
// 10000 x 5000 = 50,000,000 -- exactly MaxRemotePixels, so it must NOT be rejected. the
// decode then fails on the truncated body, which proves the check let it through.
// 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<Exception>(
@@ -58,6 +60,87 @@ public class RemoteImageDecodeLimitTests
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<InvalidOperationException>(
() => 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<InvalidOperationException>(
() => 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));
}
// a format Identify cannot enumerate frames for must be charged one frame, never zero --
// zero would make the product zero and wave any dimensions through
[Test]
public void Should_Charge_At_Least_One_Frame_When_The_Header_Reports_None()
{
Should.Throw<InvalidOperationException>(
() => ImageElementBase.EnsureDecodeAffordable(30000, 30000, 0, ImageUri));
}
[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<InvalidOperationException>(
() => 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));
}
// 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)
@@ -1,3 +1,4 @@
using System.Buffers;
using System.Net;
using System.Net.Http.Headers;
using ErsatzTV.Infrastructure.Streaming;
@@ -47,7 +48,7 @@ public class HttpRemoteImageFetcherTests
// 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 size + dimension caps are the real protection.
// 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)
@@ -76,7 +77,7 @@ public class HttpRemoteImageFetcherTests
// ...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 dimension/frame check in ImageElementBase, not by this.)
// 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()
{
@@ -92,7 +93,12 @@ public class HttpRemoteImageFetcherTests
// 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);
body.Position.ShouldBeLessThanOrEqualTo(HttpRemoteImageFetcher.MaxImageBytes + 81920);
// 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<byte>.Shared.Rent(81920);
ArrayPool<byte>.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
@@ -17,15 +17,30 @@ namespace ErsatzTV.Infrastructure.Streaming.Graphics;
public abstract class ImageElementBase(IRemoteImageFetcher remoteImageFetcher) : GraphicsElement, IDisposable
{
/// <summary>Decoded-pixel ceiling for a remote image. 8K is ~33 MP, so this is generous.</summary>
internal const long MaxRemotePixels = 50_000_000;
/// <summary>
/// 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.
/// </summary>
internal const long MaxRemoteDecodedPixels = 50_000_000;
/// <summary>
/// Frame ceiling for a remote animation. Every frame is scaled to frame size and retained,
/// so the real cost is frames x output resolution, not the wire size.
/// Frame ceiling for a remote animation, kept alongside the product budget as a cheap,
/// legible guard against absurd frame counts of tiny frames.
/// </summary>
internal const int MaxRemoteFrames = 600;
/// <summary>
/// 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 <see cref="SKBitmap" />. 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.
/// </summary>
internal const long MaxRemoteScaledPixels = 200_000_000;
private readonly List<double> _frameDelays = [];
private readonly List<SKBitmap> _scaledFrames = [];
private double _animatedDurationSeconds;
@@ -76,6 +91,11 @@ public abstract class ImageElementBase(IRemoteImageFetcher remoteImageFetcher) :
scaledHeight = (int)(scaledWidth * aspectRatio);
}
if (isRemoteUri)
{
EnsureScaledFramesAffordable(_sourceImage.Frames.Count, scaledWidth, scaledHeight, uriResult);
}
(int horizontalMargin, int verticalMargin) = placeWithinSourceContent
? SourceContentMargins(
squarePixelFrameSize,
@@ -117,35 +137,76 @@ public abstract class ImageElementBase(IRemoteImageFetcher remoteImageFetcher) :
/// </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 and cost ~3.6 GB to decode, and a
/// small animation can declare thousands of frames, each of which this class then scales to
/// frame size and keeps. Both are checked from the header, before the decoder allocates.
/// 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>
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");
}
ImageInfo info = await Image.IdentifyAsync(stream, cancellationToken);
long pixels = (long)info.Width * info.Height;
if (pixels > MaxRemotePixels)
{
throw new InvalidOperationException(
$"Remote image {uri} is {info.Width}x{info.Height} ({pixels} pixels), over the "
+ $"{MaxRemotePixels} pixel limit");
}
int frameCount = info.FrameMetadataCollection.Count;
if (frameCount > MaxRemoteFrames)
{
throw new InvalidOperationException(
$"Remote image {uri} has {frameCount} frames, over the {MaxRemoteFrames} frame limit");
}
EnsureDecodeAffordable(info.Width, info.Height, info.FrameMetadataCollection.Count, uri);
stream.Position = 0;
return await Image.LoadAsync(stream, cancellationToken);
}
/// <summary>
/// The decode-budget policy, kept free of I/O so the arithmetic can be tested at every
/// boundary without materializing multi-gigabyte images.
/// </summary>
internal static void EnsureDecodeAffordable(int width, int height, int frameCount, Uri uri)
{
// frames are 1-based in every format we accept; Identify reports 0 only if it could not
// enumerate them, in which case treat the image as a single frame rather than as free.
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");
}
}
/// <summary>
/// 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.
/// </summary>
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<Rgba32> rgbaImage = image.CloneAs<Rgba32>();
+24 -12
View File
@@ -2614,19 +2614,31 @@ read, because under `HttpCompletionOption.ResponseHeadersRead` the body read fal
**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 the decode-bomb surface. Both paths are covered by tests, and both were
negative-controlled (disabling the checks fails exactly those two tests).
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 is a second, separate check.** A decompression
bomb is by definition small on the wire: a 4 KB PNG can declare 30000x30000 and cost ~3.6 GB to
decode, and a small animation can declare thousands of frames, each of which the element then
scales to frame size and retains. All of that passes `Content-Length`, the content-type check and
the 10 MiB copy cap in milliseconds. `ImageElementBase.DecodeRemoteImage` therefore reads the
declared dimensions and frame count from the header (`Image.IdentifyAsync`) and rejects before
`Image.LoadAsync` allocates — 50 MP (8K is ~33 MP) and 600 frames. Local images are deliberately
exempt: those are files an operator put on disk, not bytes an arbitrary host returned. This was a
review finding against the first version of this change, which capped bytes and *claimed* that was
decode-bomb protection.
**The byte cap does not bound decoding, so there are two further budgets — and they are on
PRODUCTS, not on individual dimensions.** 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. `ImageElementBase.DecodeRemoteImage` reads dimensions and frame
count from the header (`Image.IdentifyAsync`) and rejects before `Image.LoadAsync` allocates:
- **Decode budget** — `width x height x frames <= 50 MP`, as one product. This matters more than it
looks: the *first* fix for this checked dimensions (50 MP) and frames (600) **independently**, and
the 2500x2500 x600 GIF above passes both while costing ~14 GiB. Adversarial re-review of that fix
built the payload and measured it. A frame count of zero is charged as one, so an unenumerable
header cannot zero the product.
- **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.
Both budgets are enforced by pure functions (`EnsureDecodeAffordable`, `EnsureScaledFramesAffordable`)
so the arithmetic is tested at every boundary without materializing multi-gigabyte images. 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