fix(511): bound the DECODER, not the header's frame count
Build ErsatzTV Image / CI image pin matches docker/ci (pull_request) Successful in 15s
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 13s
Build ErsatzTV Image / decisions.md append-only (pull_request) Successful in 16s
Build ErsatzTV Image / API docs in sync (OpenAPI + endpoint index) (pull_request) Successful in 17s
Build ErsatzTV Image / Formatting (changed .cs conform to .editorconfig) (pull_request) Successful in 20s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 7m34s
Build ErsatzTV Image / Functional E2E (curl contracts) (pull_request) Successful in 14m15s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 18m39s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped

Second adversarial re-review defeated the product budget too, and the
mechanism generalizes: the budget was enforced on a number the decoder
does not honor.

Measured on ImageSharp 3.1.12 (reproduced independently before fixing):

  600-frame APNG  ->  Identify: FrameMetadataCollection.Count = 0
                      Load:     Frames.Count = 600

So EnsureDecodeAffordable(w, h, 0) charged Math.Max(0,1) = 1 frame —
the most permissive possible reading. A 4000x4000 x600 APNG is ~134 KiB
on the wire, is charged 16 MP, and decodes to ~36 GiB: 2.5x worse than
the GIF the previous commit exists to stop, at half the wire size. The
retention budget could not backstop it — that runs after LoadAsync, so
the process OOMs first, killing every concurrent stream.

GIF, WebP and TIFF report honestly; PNG/APNG is the sole divergence,
which is the point: you cannot audit every format, so the header cannot
be the source of truth.

DecodeRemoteImage now:
- checks header DIMENSIONS only (trustworthy; a GIF image descriptor
  exceeding 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
  whatever the header claimed. Measured: MaxFrames = N yields N-1
  frames, so it asks for affordable + 2 — decoding one more than allowed
  is what distinguishes "at the limit" from "over it" without silently
  truncating a legitimate animation
- re-verifies the real image.Frames.Count after decoding, disposing and
  rejecting if over

Also adds wiring coverage for the retention budget (M4): deleting its
call site now fails a test — negative-controlled, build verified before
trusting the result.

docs/decisions.md records both failed attempts, because the lesson is
the generalizable part: independent caps do not compose into a budget,
and a limit the decoder does not enforce is not a limit.
This commit is contained in:
2026-07-21 01:04:25 +02:00
parent 9a2096f340
commit d4e112f1e9
4 changed files with 219 additions and 28 deletions
@@ -105,13 +105,17 @@ public class RemoteImageDecodeLimitTests
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()
public void Should_Afford_Fewer_Frames_As_Frames_Get_Larger()
{
Should.Throw<InvalidOperationException>(
() => ImageElementBase.EnsureDecodeAffordable(30000, 30000, 0, ImageUri));
// 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]
@@ -141,6 +145,59 @@ public class RemoteImageDecodeLimitTests
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<InvalidOperationException>(
() => 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);
}
/// <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)
@@ -5,6 +5,9 @@ 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;
@@ -92,17 +95,72 @@ public class WatermarkElementRemoteImageTests
element.IsFinished.ShouldBeTrue();
}
private static WatermarkOptions RemoteWatermarkOptions() =>
new(Watermark(), RemoteLogo, Option<int>.None);
private static ChannelWatermark Watermark() =>
// --- 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<ILogger>());
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<ILogger>());
await element.InitializeAsync(Context(), CancellationToken.None);
element.IsFinished.ShouldBeFalse();
}
private static IRemoteImageFetcher FetcherReturning(Stream stream)
{
var fetcher = Substitute.For<IRemoteImageFetcher>();
fetcher.Fetch(Arg.Any<Uri>(), Arg.Any<CancellationToken>()).Returns(stream);
return fetcher;
}
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;
}
private static WatermarkOptions RemoteWatermarkOptions(double widthPercent = 10) =>
new(Watermark(widthPercent), RemoteLogo, Option<int>.None);
private static ChannelWatermark Watermark(double widthPercent = 10) =>
new()
{
Name = "test",
Mode = ChannelWatermarkMode.Permanent,
Location = WatermarkLocation.BottomRight,
Size = WatermarkSize.Scaled,
WidthPercent = 10,
WidthPercent = widthPercent,
HorizontalMarginPercent = 5,
VerticalMarginPercent = 5,
Opacity = 100
@@ -157,20 +157,70 @@ public abstract class ImageElementBase(IRemoteImageFetcher remoteImageFetcher) :
ImageInfo info = await Image.IdentifyAsync(stream, cancellationToken);
EnsureDecodeAffordable(info.Width, info.Height, info.FrameMetadataCollection.Count, uri);
// 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;
return await Image.LoadAsync(stream, cancellationToken);
// MaxFrames is enforced BY THE DECODER, so it holds whatever the header claimed. Measured:
// MaxFrames = N yields N-1 frames (for N >= 2), so asking for affordableFrames + 2 decodes
// at most affordableFrames + 1 — one more than allowed, which is exactly what lets the
// post-decode check distinguish "exactly at the limit" from "over it" without truncating a
// legitimate animation by a frame.
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;
}
}
/// <summary>Rejects a single frame that cannot fit the decode budget on its own.</summary>
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");
}
}
/// <summary>
/// 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.
/// </summary>
internal static int AffordableFrames(int width, int height)
{
long perFrame = Math.Max((long)width * height, 1);
return (int)Math.Clamp(MaxRemoteDecodedPixels / perFrame, 1, MaxRemoteFrames);
}
/// <summary>
/// The decode-budget policy, kept free of I/O so the arithmetic can be tested at every
/// boundary without materializing multi-gigabyte images.
/// 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.
/// </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)
+40 -14
View File
@@ -2618,27 +2618,53 @@ actually bounds transfer and buffering. (It bounds the *wire*, not the decode
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 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:
**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.
- **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.
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. Note
`MaxFrames = N` yields `N-1` frames (measured), so the code asks for `affordable + 2` — decoding
one more than allowed is what distinguishes "exactly at the limit" from "over it" without silently
truncating a legitimate animation.
- **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.
Caveats worth knowing: the budgets are in pixels, but a 16-bit PNG decodes to `Rgba64` (8 B/px), so
the byte cost doubles there; 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.
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.
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