H1: beeldpijplijn in Core.Media (Magick.NET achter IImageProcessor), pure functies met property-tests, uploadwacht

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 15:18:02 +01:00
co-authored by Claude Sonnet 5.5
parent 259d48bd9c
commit 3a50c9750e
19 changed files with 1784 additions and 1 deletions
@@ -0,0 +1,235 @@
using FluentAssertions;
using ImageMagick;
using ImageMagick.Formats;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Media;
using SlpModularCms.Core.Media.Magick;
namespace SlpModularCms.Core.Tests.Media;
/// <summary>The real image library on small generated fixtures (no files from disk, so they run the same everywhere).</summary>
public class MagickImageProcessorTests
{
private static readonly MagickImageProcessor Processor = new(Options.Create(new MediaOptions()), NullLogger<MagickImageProcessor>.Instance);
private static byte[] Encode(MagickImage image, MagickFormat format)
{
using var stream = new MemoryStream();
image.Write(stream, format);
return stream.ToArray();
}
/// <summary>Left half red, right half blue: lets a test see which part of the picture a crop kept.</summary>
private static MagickImage TwoColours(int width, int height)
{
var image = new MagickImage(MagickColors.Red, (uint)width, (uint)height);
using var blue = new MagickImage(MagickColors.Blue, (uint)(width / 2), (uint)height);
image.Composite(blue, width - width / 2, 0, CompositeOperator.Over);
return image;
}
private static VariantSpec Spec(int w, int h, int x, int y, int cw, int ch, ImageFormat format = ImageFormat.WebP, Ratio? ratio = null)
=> new(ratio ?? Ratio.Wide, w, h, format, 80, new CropRect(x, y, cw, ch));
[Fact]
public void TheCapabilities_CoverTheCommonFormats()
{
Processor.SupportedInput.Should().Contain([ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.Gif, ImageFormat.Bmp, ImageFormat.Tiff, ImageFormat.WebP, ImageFormat.Avif]);
Processor.SupportedOutput.Should().Contain([ImageFormat.WebP, ImageFormat.Jpeg]);
}
[Fact]
public async Task TheSelfTest_Passes() => await Processor.Invoking(p => p.SelfTestAsync(CancellationToken.None)).Should().NotThrowAsync();
[Theory]
[InlineData(MagickFormat.Jpeg, ImageFormat.Jpeg)]
[InlineData(MagickFormat.Png, ImageFormat.Png)]
[InlineData(MagickFormat.Gif, ImageFormat.Gif)]
[InlineData(MagickFormat.Bmp, ImageFormat.Bmp)]
[InlineData(MagickFormat.Tiff, ImageFormat.Tiff)]
[InlineData(MagickFormat.WebP, ImageFormat.WebP)]
[InlineData(MagickFormat.Avif, ImageFormat.Avif)]
public async Task EveryCommonFormat_IsRecognisedAndInspected(MagickFormat magick, ImageFormat expected)
{
using var image = TwoColours(120, 80);
var bytes = Encode(image, magick);
var detected = ImageSignature.Detect(bytes);
detected.Should().Be(expected == ImageFormat.Avif ? ImageFormat.Avif : expected);
var info = await Processor.InspectAsync(bytes, detected, CancellationToken.None);
info.Width.Should().Be(120);
info.Height.Should().Be(80);
info.FrameCount.Should().Be(1);
}
[Fact]
public async Task ARotatedPhoto_IsReportedInItsOrientedSize()
{
using var image = new MagickImage(MagickColors.Green, 400, 200);
var exif = new ExifProfile();
image.Orientation = Orientation.RightTop; // rotate 90 degrees clockwise on display
exif.SetValue(ExifTag.Orientation, (ushort)6);
image.SetProfile(exif);
var bytes = Encode(image, MagickFormat.Jpeg);
var info = await Processor.InspectAsync(bytes, ImageFormat.Jpeg, CancellationToken.None);
(info.Width, info.Height).Should().Be((200, 400));
info.HasMetadata.Should().BeTrue();
}
[Fact]
public async Task AnAnimatedGif_ReportsItsFrames_AndRendersTheFirst()
{
using var frames = new MagickImageCollection();
frames.Add(new MagickImage(MagickColors.Red, 60, 40) { AnimationDelay = 10 });
frames.Add(new MagickImage(MagickColors.Blue, 60, 40) { AnimationDelay = 10 });
using var stream = new MemoryStream();
frames.Write(stream, MagickFormat.Gif);
var bytes = stream.ToArray();
var info = await Processor.InspectAsync(bytes, ImageFormat.Gif, CancellationToken.None);
var rendered = await Processor.RenderAsync(bytes, ImageFormat.Gif, Spec(60, 40, 0, 0, 60, 40, ImageFormat.Png), CancellationToken.None);
info.FrameCount.Should().Be(2);
using var back = new MagickImage(rendered.Bytes);
back.GetPixels().GetPixel(5, 5).ToColor()!.ToString().Should().StartWith("#FF0000");
}
[Fact]
public async Task ARender_HasTheRequestedSize_AndNoMetadata()
{
using var image = TwoColours(1600, 1067);
var exif = new ExifProfile();
exif.SetValue(ExifTag.Software, "camera firmware");
exif.SetValue(ExifTag.GPSLatitudeRef, "N");
image.SetProfile(exif);
var bytes = Encode(image, MagickFormat.Jpeg);
var rendered = await Processor.RenderAsync(bytes, ImageFormat.Jpeg, Spec(960, 640, 0, 0, 1600, 1067), CancellationToken.None);
rendered.Format.Should().Be(ImageFormat.WebP);
(rendered.Width, rendered.Height).Should().Be((960, 640));
ImageSignature.Detect(rendered.Bytes).Should().Be(ImageFormat.WebP);
using var back = new MagickImage();
back.Ping(rendered.Bytes);
back.GetExifProfile().Should().BeNull();
back.GetXmpProfile().Should().BeNull();
}
[Fact]
public async Task TheCrop_KeepsTheChosenPartOfThePicture()
{
using var image = TwoColours(1000, 500);
var bytes = Encode(image, MagickFormat.Png);
var left = FocusMath.CropFor(1000, 500, Ratio.Tall, new FocusSetting(0.0, 0.5, 1));
var right = FocusMath.CropFor(1000, 500, Ratio.Tall, new FocusSetting(1.0, 0.5, 1));
var leftImage = await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(200, 250, left.X, left.Y, left.Width, left.Height, ImageFormat.Png, Ratio.Tall), CancellationToken.None);
var rightImage = await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(200, 250, right.X, right.Y, right.Width, right.Height, ImageFormat.Png, Ratio.Tall), CancellationToken.None);
using var l = new MagickImage(leftImage.Bytes);
using var r = new MagickImage(rightImage.Bytes);
l.GetPixels().GetPixel(100, 125).ToColor()!.ToString().Should().StartWith("#FF0000"); // red
r.GetPixels().GetPixel(100, 125).ToColor()!.ToString().Should().StartWith("#0000FF"); // blue
}
[Fact]
public async Task ARotatedPhoto_IsCroppedInItsOrientedSize()
{
using var image = TwoColours(400, 200);
var exif = new ExifProfile();
image.Orientation = Orientation.RightTop;
exif.SetValue(ExifTag.Orientation, (ushort)6);
image.SetProfile(exif);
var bytes = Encode(image, MagickFormat.Jpeg);
var rendered = await Processor.RenderAsync(bytes, ImageFormat.Jpeg, Spec(100, 200, 0, 0, 200, 400, ImageFormat.Jpeg, Ratio.Tall), CancellationToken.None);
(rendered.Width, rendered.Height).Should().Be((100, 200));
}
[Fact]
public async Task AvifOutput_IsWrittenWhenSupported()
{
Processor.SupportedOutput.Should().Contain(ImageFormat.Avif);
using var image = TwoColours(640, 427);
var bytes = Encode(image, MagickFormat.Png);
var rendered = await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(320, 213, 0, 0, 640, 427, ImageFormat.Avif), CancellationToken.None);
ImageSignature.Detect(rendered.Bytes).Should().Be(ImageFormat.Avif);
}
[Fact]
public async Task ATruncatedFile_IsRejectedAsCorrupt()
{
using var image = TwoColours(800, 600);
var bytes = Encode(image, MagickFormat.Jpeg);
var truncated = bytes.AsMemory(0, bytes.Length / 3);
var act = async () => await Processor.RenderAsync(truncated, ImageFormat.Jpeg, Spec(100, 67, 0, 0, 800, 534), CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Reason.Should().Be(ImageRejection.Corrupt);
}
[Fact]
public async Task AFileWithAJpegHeaderAndGarbage_IsRejectedAsCorrupt()
{
var garbage = new byte[2000];
new Random(7).NextBytes(garbage);
garbage[0] = 0xFF;
garbage[1] = 0xD8;
garbage[2] = 0xFF;
var act = async () => await Processor.InspectAsync(garbage, ImageFormat.Jpeg, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Reason.Should().Be(ImageRejection.Corrupt);
}
[Fact]
public async Task AFileThatClaimsAnotherFormat_IsRejected()
{
using var image = TwoColours(50, 50);
var png = Encode(image, MagickFormat.Png);
var act = async () => await Processor.InspectAsync(png, ImageFormat.Tiff, CancellationToken.None);
await act.Should().ThrowAsync<ImageRejectedException>();
}
[Fact]
public async Task StrippingMetadata_RemovesTheProfiles_AndKeepsTheSize()
{
using var image = TwoColours(300, 200);
var exif = new ExifProfile();
exif.SetValue(ExifTag.Software, "camera");
image.SetProfile(exif);
var withExif = Encode(image, MagickFormat.Jpeg);
using var plain = TwoColours(300, 200);
var withoutExif = Encode(plain, MagickFormat.Jpeg);
var stripped = await Processor.StripMetadataAsync(withExif, ImageFormat.Jpeg, CancellationToken.None);
var untouched = await Processor.StripMetadataAsync(withoutExif, ImageFormat.Jpeg, CancellationToken.None);
untouched.Should().BeNull();
stripped.Should().NotBeNull();
using var back = new MagickImage();
back.Ping(stripped!);
back.GetExifProfile().Should().BeNull();
(back.Width, back.Height).Should().Be((300u, 200u));
}
[Fact]
public async Task APlannedCrop_ThatDoesNotFit_IsRefused()
{
using var image = TwoColours(100, 100);
var bytes = Encode(image, MagickFormat.Png);
var act = async () => await Processor.RenderAsync(bytes, ImageFormat.Png, Spec(50, 33, 50, 50, 100, 100), CancellationToken.None);
await act.Should().ThrowAsync<ImageRejectedException>();
}
}
@@ -0,0 +1,290 @@
using FluentAssertions;
using FsCheck;
using FsCheck.Fluent;
using SlpModularCms.Core.Media;
namespace SlpModularCms.Core.Tests.Media;
public class FocusMathTests
{
private static Arbitrary<(int W, int H, FocusSetting Focus, Ratio Ratio)> Cases() =>
(from w in Gen.Choose(1, 9000)
from h in Gen.Choose(1, 9000)
from fx in Gen.Choose(0, 1000)
from fy in Gen.Choose(0, 1000)
from zoom in Gen.Choose(1000, 4000)
from tall in Gen.Elements(true, false)
select (w, h, new FocusSetting(fx / 1000.0, fy / 1000.0, zoom / 1000.0), tall ? Ratio.Tall : Ratio.Wide)).ToArbitrary();
private static void ForAllCases(Action<(int W, int H, FocusSetting Focus, Ratio Ratio)> check) =>
Prop.ForAll(Cases(), c => { check(c); return true; }).Check(Config.QuickThrowOnFailure.WithMaxTest(2000));
[Fact]
public void TheCrop_IsAlwaysInsideTheImage() => ForAllCases(c =>
{
var crop = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus);
crop.Width.Should().BeInRange(1, c.W);
crop.Height.Should().BeInRange(1, c.H);
crop.X.Should().BeGreaterThanOrEqualTo(0);
crop.Y.Should().BeGreaterThanOrEqualTo(0);
(crop.X + crop.Width).Should().BeLessThanOrEqualTo(c.W);
(crop.Y + crop.Height).Should().BeLessThanOrEqualTo(c.H);
});
[Fact]
public void TheFocusPoint_IsInsideTheCrop() => ForAllCases(c =>
{
var crop = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus);
var px = c.Focus.X * c.W;
var py = c.Focus.Y * c.H;
px.Should().BeInRange(crop.X - 1, crop.X + crop.Width + 1);
py.Should().BeInRange(crop.Y - 1, crop.Y + crop.Height + 1);
});
[Fact]
public void TheCrop_HasTheRatio_WithinOnePixel() => ForAllCases(c =>
{
// Only meaningful when the crop is big enough for one pixel not to matter.
var crop = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus);
if (crop.Width >= 50 && crop.Height >= 50)
{
var expectedHeight = crop.Width * (double)c.Ratio.Denominator / c.Ratio.Numerator;
Math.Abs(crop.Height - expectedHeight).Should().BeLessThanOrEqualTo(1.0);
}
});
[Fact]
public void MoreZoom_NeverGivesABiggerCrop() => ForAllCases(c =>
{
var plain = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus with { Zoom = 1 });
var zoomed = FocusMath.CropFor(c.W, c.H, c.Ratio, c.Focus);
zoomed.Width.Should().BeLessThanOrEqualTo(plain.Width);
});
[Fact]
public void InvalidFocusValues_AreClamped_NotFatal()
{
var crop = FocusMath.CropFor(1600, 1067, Ratio.Tall, new FocusSetting(double.NaN, double.PositiveInfinity, double.NegativeInfinity));
crop.X.Should().BeGreaterThanOrEqualTo(0);
(crop.X + crop.Width).Should().BeLessThanOrEqualTo(1600);
}
// Shared vectors: the admin's TypeScript twin has the same cases (frontend/src/features/hero/focusMath.test.ts).
[Theory]
[InlineData(1600, 1067, "wide", 0.5, 0.5, 1.0, 0, 0, 1600, 1067)]
[InlineData(1600, 1067, "tall", 0.5, 0.5, 1.0, 374, 1, 853, 1066)]
[InlineData(1600, 1067, "tall", 0.0, 0.5, 1.0, 0, 1, 853, 1066)]
[InlineData(1600, 1067, "tall", 1.0, 0.5, 1.0, 747, 1, 853, 1066)]
[InlineData(1600, 1067, "wide", 0.45, 0.35, 2.0, 320, 107, 800, 533)]
[InlineData(2560, 1702, "tall", 0.55, 0.6, 1.0, 728, 1, 1361, 1701)]
[InlineData(1000, 2000, "wide", 0.5, 0.5, 1.0, 0, 667, 1000, 667)]
public void KnownVectors(int w, int h, string ratio, double fx, double fy, double zoom, int x, int y, int cw, int ch)
{
var crop = FocusMath.CropFor(w, h, ratio == "tall" ? Ratio.Tall : Ratio.Wide, new FocusSetting(fx, fy, zoom));
crop.Should().Be(new CropRect(x, y, cw, ch));
}
}
public class VariantPlannerTests
{
private static readonly IReadOnlySet<ImageFormat> WebPAndAvif = new HashSet<ImageFormat> { ImageFormat.WebP, ImageFormat.Avif };
private static readonly IReadOnlySet<ImageFormat> WebPOnly = new HashSet<ImageFormat> { ImageFormat.WebP };
private static RatioPlan[] Plans() =>
[
new(Ratio.Wide, FocusSetting.Centre, VariantPlanner.DefaultWidths(Ratio.Wide)),
new(Ratio.Tall, FocusSetting.Centre, VariantPlanner.DefaultWidths(Ratio.Tall)),
];
[Fact]
public void ASmallSource_IsNeverScaledUp()
{
var plan = VariantPlanner.Plan(1600, 1067, Plans(), WebPAndAvif);
plan.Should().OnlyContain(v => v.Width <= v.Crop.Width);
plan.Where(v => v.Ratio.Name == "wide").Select(v => v.Width).Distinct().Should().Equal(640, 960, 1280, 1600);
plan.Where(v => v.Ratio.Name == "tall").Select(v => v.Width).Distinct().Should().Equal(480, 640); // the tall crop of a 1600x1067 image is 853 wide
}
[Fact]
public void ALargeSource_GetsTheWholeLadder()
{
var plan = VariantPlanner.Plan(6000, 4000, Plans(), WebPAndAvif);
plan.Where(v => v.Ratio.Name == "wide").Select(v => v.Width).Distinct().Should().Equal(640, 960, 1280, 1600, 2560);
plan.Where(v => v.Ratio.Name == "tall").Select(v => v.Width).Distinct().Should().Equal(480, 640, 960, 1280);
}
[Fact]
public void ATinySource_StillGetsOneVariantPerRatio()
{
var plan = VariantPlanner.Plan(300, 200, Plans(), WebPOnly);
plan.Where(v => v.Ratio.Name == "wide").Should().ContainSingle().Which.Width.Should().Be(300);
plan.Where(v => v.Ratio.Name == "tall").Should().ContainSingle().Which.Width.Should().Be(160);
}
[Fact]
public void WebPIsAlwaysPlanned_AvifOnlyWhenTheProcessorCan()
{
VariantPlanner.Plan(2000, 1500, Plans(), WebPOnly).Select(v => v.Format).Distinct().Should().Equal(ImageFormat.WebP);
VariantPlanner.Plan(2000, 1500, Plans(), WebPAndAvif).Select(v => v.Format).Distinct().Should().BeEquivalentTo([ImageFormat.WebP, ImageFormat.Avif]);
}
[Fact]
public void WithoutAWebPEncoder_TheFallbackIsJpeg()
{
var onlyAvif = new HashSet<ImageFormat> { ImageFormat.Avif };
VariantPlanner.Plan(2000, 1500, Plans(), onlyAvif).Select(v => v.Format).Distinct().Should().BeEquivalentTo([ImageFormat.Jpeg, ImageFormat.Avif]);
}
[Fact]
public void Widths_AreAscendingPerRatio_AndHeightsKeepTheRatio()
{
Prop.ForAll(Gen.Choose(50, 9000).SelectMany(w => Gen.Choose(50, 9000).Select(h => (w, h))).ToArbitrary(), size =>
{
var plan = VariantPlanner.Plan(size.w, size.h, Plans(), WebPAndAvif);
foreach (var group in plan.GroupBy(v => v.Ratio.Name))
{
var widths = group.Where(v => v.Format == ImageFormat.WebP).Select(v => v.Width).ToList();
widths.Should().BeInAscendingOrder().And.OnlyHaveUniqueItems();
widths.Should().NotBeEmpty();
foreach (var v in group)
{
Math.Abs(v.Height - v.Width * (double)v.Ratio.Denominator / v.Ratio.Numerator).Should().BeLessThanOrEqualTo(0.5);
}
}
return true;
}).Check(Config.QuickThrowOnFailure.WithMaxTest(500));
}
}
public class MediaPathsTests
{
private const string Sha = "0f8c6d3e2a1b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5";
[Fact]
public void TheSetHash_IsStable_AndChangesWhenTheFocusChanges()
{
var a = MediaPaths.SetHash(Sha, [("wide", FocusSetting.Centre), ("tall", FocusSetting.Centre)]);
var again = MediaPaths.SetHash(Sha, [("tall", FocusSetting.Centre), ("wide", FocusSetting.Centre)]);
var moved = MediaPaths.SetHash(Sha, [("wide", FocusSetting.Centre), ("tall", new FocusSetting(0.4, 0.5, 1))]);
var other = MediaPaths.SetHash(Sha.Replace('0', '1'), [("wide", FocusSetting.Centre), ("tall", FocusSetting.Centre)]);
a.Should().MatchRegex("^[0-9a-f]{16}$");
again.Should().Be(a);
moved.Should().NotBe(a);
other.Should().NotBe(a);
}
[Fact]
public void SmallDifferences_BelowTheCanonicalPrecision_GiveTheSameSet()
=> MediaPaths.SetHash(Sha, [("wide", new FocusSetting(0.50001, 0.5, 1))])
.Should().Be(MediaPaths.SetHash(Sha, [("wide", new FocusSetting(0.5, 0.5, 1))]));
[Fact]
public void AnAddress_RoundTrips()
{
var hash = MediaPaths.SetHash(Sha, [("wide", FocusSetting.Centre)]);
var name = MediaPaths.FileName("wide", 1600, ImageFormat.WebP);
var url = MediaPaths.Url("hero", hash, name);
url.Should().Be($"/media/hero/{hash}/wide-1600.webp");
MediaPaths.TryParse(url[MediaPaths.UrlPrefix.Length..], out var address).Should().BeTrue();
address.Should().Be(new MediaAddress("hero", hash, "wide-1600.webp"));
MediaPaths.TryParseName(name, out var ratio, out var width, out var format).Should().BeTrue();
(ratio, width, format).Should().Be(("wide", 1600, ImageFormat.WebP));
}
[Theory]
[InlineData("")]
[InlineData("hero/0123456789abcdef/wide-1600.png")]
[InlineData("hero/0123456789abcde/wide-1600.webp")]
[InlineData("hero/0123456789ABCDEF/wide-1600.webp")]
[InlineData("hero/0123456789abcdef/../wide-1600.webp")]
[InlineData("../hero/0123456789abcdef/wide-1600.webp")]
[InlineData("hero//0123456789abcdef/wide-1600.webp")]
[InlineData("hero/0123456789abcdef/wide-1600.webp/")]
[InlineData("hero\\0123456789abcdef\\wide-1600.webp")]
[InlineData("hero/0123456789abcdef/wide-16.webp ")]
[InlineData("hero/0123456789abcdef/WIDE-1600.webp")]
[InlineData("hero/0123456789abcdef/original.jpg")]
[InlineData("originals/0123456789abcdef/wide-1600.webp.exe")]
public void AnythingElse_IsNotAnAddress(string path) => MediaPaths.TryParse(path, out _).Should().BeFalse();
}
public class ImageSignatureTests
{
private static byte[] Padded(params byte[] head) => head.Concat(new byte[32 - head.Length]).ToArray();
[Fact]
public void KnownSignatures_AreRecognised()
{
ImageSignature.Detect(Padded(0xFF, 0xD8, 0xFF, 0xE0)).Should().Be(ImageFormat.Jpeg);
ImageSignature.Detect(Padded(0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)).Should().Be(ImageFormat.Png);
ImageSignature.Detect("GIF89a"u8.ToArray().Concat(new byte[26]).ToArray()).Should().Be(ImageFormat.Gif);
ImageSignature.Detect(Padded(0x49, 0x49, 0x2A, 0x00)).Should().Be(ImageFormat.Tiff);
ImageSignature.Detect(Padded(0x4D, 0x4D, 0x00, 0x2A)).Should().Be(ImageFormat.Tiff);
ImageSignature.Detect(Riff("WEBP")).Should().Be(ImageFormat.WebP);
ImageSignature.Detect(Ftyp("avif")).Should().Be(ImageFormat.Avif);
ImageSignature.Detect(Ftyp("heic")).Should().Be(ImageFormat.Heic);
ImageSignature.Detect(Bmp(40)).Should().Be(ImageFormat.Bmp);
}
[Theory]
[InlineData("<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>")]
[InlineData("<?xml version=\"1.0\"?><svg/>")]
[InlineData("%PDF-1.7 and more text here to fill")]
[InlineData("MZ\u0090\u0000\u0003 an executable header")]
[InlineData("<html><script>alert(1)</script></html>")]
[InlineData("PK\u0003\u0004 a zip archive of something")]
[InlineData("")]
public void NotAnImage_IsUnknown(string text)
=> ImageSignature.Detect(System.Text.Encoding.Latin1.GetBytes(text)).Should().Be(ImageFormat.Unknown);
[Fact]
public void ARiffThatIsNotWebP_IsUnknown() => ImageSignature.Detect(Riff("WAVE")).Should().Be(ImageFormat.Unknown);
[Fact]
public void AnIsoFileWithAnotherBrand_IsUnknown() => ImageSignature.Detect(Ftyp("mp42")).Should().Be(ImageFormat.Unknown);
[Fact]
public void ABmThatIsNoBitmap_IsUnknown() => ImageSignature.Detect(Bmp(7)).Should().Be(ImageFormat.Unknown);
[Fact]
public void ARandomHead_NeverThrows()
=> Prop.ForAll(Gen.Choose(0, 255).Select(i => (byte)i).ArrayOf().ToArbitrary(), bytes =>
{
var act = () => ImageSignature.Detect(bytes);
act.Should().NotThrow();
return true;
}).Check(Config.QuickThrowOnFailure.WithMaxTest(1000));
private static byte[] Riff(string kind)
{
var b = new byte[32];
"RIFF"u8.CopyTo(b);
System.Text.Encoding.ASCII.GetBytes(kind).CopyTo(b, 8);
return b;
}
private static byte[] Ftyp(string brand)
{
var b = new byte[32];
b[3] = 0x1C;
"ftyp"u8.CopyTo(b.AsSpan(4));
System.Text.Encoding.ASCII.GetBytes(brand).CopyTo(b, 8);
return b;
}
private static byte[] Bmp(int headerSize)
{
var b = new byte[32];
b[0] = (byte)'B';
b[1] = (byte)'M';
b[14] = (byte)headerSize;
return b;
}
}
@@ -0,0 +1,157 @@
using FluentAssertions;
using Microsoft.Extensions.Options;
using NSubstitute;
using SlpModularCms.Core.Media;
namespace SlpModularCms.Core.Tests.Media;
public class MediaUploadGuardTests
{
private static readonly byte[] Png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 1, 2, 3, 4, 5, 6, 7, 8];
private sealed class Rig
{
public MediaOptions Options { get; } = new() { MaxUploadBytes = 1000, MaxPixels = 1_000_000, MaxSide = 5000, MaxParallelJobs = 1, BusyWaitSeconds = 0 };
public IImageProcessor Processor { get; } = Substitute.For<IImageProcessor>();
public MediaStatus Status { get; } = new();
public MediaProcessingGate Gate { get; }
public MediaUploadGuard Guard { get; }
public Rig(bool available = true)
{
Gate = new MediaProcessingGate(Microsoft.Extensions.Options.Options.Create(Options));
Processor.SupportedInput.Returns(new HashSet<ImageFormat> { ImageFormat.Jpeg, ImageFormat.Png, ImageFormat.WebP });
Processor.InspectAsync(default, default, default).ReturnsForAnyArgs(new ImageInfo(ImageFormat.Png, 800, 600, 1, false));
Status.SetProcessor(available, Processor.SupportedInput, new HashSet<ImageFormat> { ImageFormat.WebP });
Status.SetDirectory(true);
Guard = new MediaUploadGuard(Processor, Gate, Status, Microsoft.Extensions.Options.Options.Create(Options));
}
}
private static MemoryStream Stream(byte[] bytes) => new(bytes);
[Fact]
public async Task AValidImage_IsAdmitted_WithItsInfo()
{
var rig = new Rig();
using var upload = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
upload.Bytes.Should().Equal(Png);
upload.Info.Width.Should().Be(800);
}
[Fact]
public async Task ADeclaredLength_AboveTheLimit_IsRefusedBeforeReading()
{
var rig = new Rig();
var act = async () => await rig.Guard.AdmitAsync(Stream(Png), 5000, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("too_large");
}
[Fact]
public async Task AnUpload_LongerThanItsDeclaredLength_IsStillStopped()
{
var rig = new Rig();
var big = new byte[2000];
Png.CopyTo(big, 0);
var act = async () => await rig.Guard.AdmitAsync(Stream(big), 10, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("too_large");
}
[Theory]
[InlineData("<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>")]
[InlineData("%PDF-1.4 not an image")]
[InlineData("GIF89a is not in the accepted list of this rig but the processor lacks it")]
public async Task NotAnAcceptedImage_IsRefused(string text)
{
var rig = new Rig();
var bytes = System.Text.Encoding.ASCII.GetBytes(text);
var act = async () => await rig.Guard.AdmitAsync(Stream(bytes), bytes.Length, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("unsupported_format");
}
[Fact]
public async Task AnEmptyUpload_IsCorrupt()
{
var rig = new Rig();
var act = async () => await rig.Guard.AdmitAsync(Stream([]), 0, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("corrupt");
}
[Theory]
[InlineData(2000, 2000)] // 4 MP, above the 1 MP ceiling
[InlineData(6000, 10)] // a side above the limit
public async Task ATooBigPicture_IsRefused(int width, int height)
{
var rig = new Rig();
rig.Processor.InspectAsync(default, default, default).ReturnsForAnyArgs(new ImageInfo(ImageFormat.Png, width, height, 1, false));
var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("too_many_pixels");
}
[Fact]
public async Task WhenTheLibraryIsNotAvailable_NothingIsAccepted()
{
var rig = new Rig(available: false);
var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("unavailable");
}
[Fact]
public async Task WhenTheDirectoryIsNotWritable_NothingIsAccepted()
{
var rig = new Rig();
rig.Status.SetDirectory(false);
var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("unavailable");
}
[Fact]
public async Task WhenAllSlotsAreTaken_TheAnswerIsBusy_AndAFreedSlotWorksAgain()
{
var rig = new Rig();
var first = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
var act = async () => await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
(await act.Should().ThrowAsync<ImageRejectedException>()).Which.Code.Should().Be("busy");
first.Dispose();
using var second = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
second.Info.Should().NotBeNull();
}
[Fact]
public async Task ARefusal_ReleasesTheSlot()
{
var rig = new Rig();
var bad = System.Text.Encoding.ASCII.GetBytes("not an image at all");
for (var i = 0; i < 3; i++)
{
var act = async () => await rig.Guard.AdmitAsync(Stream(bad), bad.Length, CancellationToken.None);
await act.Should().ThrowAsync<ImageRejectedException>();
}
using var ok = await rig.Guard.AdmitAsync(Stream(Png), Png.Length, CancellationToken.None);
ok.Should().NotBeNull();
}
}
@@ -36,6 +36,7 @@
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
<ProjectReference Include="..\SlpModularCms.Core.Media.Magick\SlpModularCms.Core.Media.Magick.csproj" />
</ItemGroup>
<!--