diff --git a/.claude/plans/2026-11-15-issue-1482-update-net11.md b/.claude/plans/2026-11-15-issue-1482-update-net11.md new file mode 100644 index 00000000..578e9c09 --- /dev/null +++ b/.claude/plans/2026-11-15-issue-1482-update-net11.md @@ -0,0 +1,72 @@ +# Issue #1482 — Update to net11 + +https://github.com/DevBetterCom/DevBetterWeb/issues/1482 + +Issue body: "And update all packages". No comments, labels, or linked items. + +## Assumptions + +- Target `net11.0` for every project; SDK 11.0.100 is installed locally. +- "Update all packages" = bump every `PackageVersion` in `Directory.Packages.props` to its latest + stable release, **except** packages pinned with an explicit reason in the file + (`Stripe.net` webhook API version). That one stays pinned. +- Prereleases are not adopted. +- Aspire is not on `main` (it exists only on the old `ShadyNagy/outboxserver` branch). Adding it is + tracked separately in #1484 (requested by the user during this work). + +## Phase 1 — Framework + +- [x] `global.json` SDK `11.*` +- [x] All `.csproj` `TargetFramework` → `net11.0` +- [x] Both Dockerfiles (root and `src/DevBetterWeb.Web`) base/sdk images → `11.0` +- [x] GitHub workflows `dotnet-version` → `11.0.x`, step names updated +- [x] `.vscode/launch.json` program path → `net11.0` +- [x] README prerequisite → .NET 11 SDK + +## Phase 2 — Packages + +- [x] Compared each `PackageVersion` to latest stable on NuGet +- [x] Bumped Microsoft 10.x → 11.0.0, others to latest stable (AutoMapper 17.0.0 also clears + GHSA-6vhm-j9h7-f9gh / GHSA-gpwp-5797-mjff) +- [x] `SixLabors.ImageSharp` 2.1.13 has 5 unpatched advisories (fixes only in commercially licensed + 3.2+/4.1.2+). User chose to replace it with SkiaSharp (MIT) → `AvatarImageResizer` +- [x] Removed `NETStandard.Library` and `System.ComponentModel.Annotations` from Core (NU1510) +- [x] Removed `AddRazorRuntimeCompilation` and its package (ASPDEPR003, obsolete in net11) +- [x] Removed 21 `PackageVersion` entries no project referenced (FastEndpoints, OpenTelemetry/Aspire + leftovers, SQLite, etc.) instead of bumping dead entries + +## Phase 3 — Tests + +- [x] `AvatarImageResizerTests` (unit): output size/format for several inputs, center crop (wide + tall), + transparency → white, all 8 EXIF orientations, EXIF stripped, oversize rejection, invalid data, null +- [x] `AutoMapperConfigurationTests` (unit): all Web profiles load and compile under AutoMapper 17 +- [x] Existing unit, integration, and functional suites pass on net11 + +## Phase 4 — Independent review + +- [x] Separate agent reviewed full diff +- [x] Fixed: EXIF orientation regression; missed `src/DevBetterWeb.Web/Dockerfile`; decompression-bomb + cap (10k px/side, 40 MP) + codec downsampling on decode; mipmapped sampling for large + reductions; friendly ModelState error for bad/missing uploads (was a 500); stale .NET 10 refs; + unused packages; resized stream now disposed; null checks on Skia results +- [x] Accessibility: label now bound to the file input, `accept` filter, error span tied via + `aria-describedby` with `role="alert"` + +### Not addressed (with reasons) + +- **Transitive `Microsoft.AspNetCore.WebUtilities` 9.0.4 advisory** via `NimblePros.Vimeo` → + `NimblePros.ApiClient 2.1.2`: already on main; Web resolves the framework copy at runtime. Better + fixed by bumping NimblePros.Vimeo upstream than by turning on transitive pinning here. +- **Swagger functional test**: Swagger is only mapped in Development; functional tests run in + `Testing`, so a test would need app-startup changes beyond this issue. +- **Strict `AssertConfigurationIsValid`**: profiles have many existing unmapped members (unrelated to + the upgrade); fixing them is a separate cleanup. +- **Identity UI Bootstrap 4 obsolete warning**: a build warning, not an error; moving to Bootstrap 5 is a + UI change for another issue. + +## Phase 5 — Verification + +- [x] `dotnet build` clean, `dotnet test` all green +- [x] `dotnet format --verify-no-changes`: main already has ~11k pre-existing violations (whitespace, + imports, file-scoped namespace in old migrations) under both SDK 10 and 11. This branch adds none: + new files pass on their own, and the repo total went down slightly. diff --git a/.claude/settings.json b/.claude/settings.json index 34b0215b..52b5e5bb 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,5 +1,7 @@ { "enabledPlugins": { - "codex@openai-codex": true + "codex@openai-codex": true, + "workflow@nimblepros": true, + "dotnet@nimblepros": true } } diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 9ec2b35f..d8565c45 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -15,10 +15,10 @@ jobs: id: checkout_repo uses: actions/checkout@v7.0.0 - - name: Install .NET 10 + - name: Install .NET 11 uses: actions/setup-dotnet@v6 with: - dotnet-version: 10.0.x + dotnet-version: 11.0.x - name: Initialize CodeQL id: init_codeql diff --git a/.github/workflows/dotnetcore.yml b/.github/workflows/dotnetcore.yml index 69508141..db5e1a63 100644 --- a/.github/workflows/dotnetcore.yml +++ b/.github/workflows/dotnetcore.yml @@ -14,7 +14,7 @@ jobs: - name: Setup .NET Core uses: actions/setup-dotnet@v6 with: - dotnet-version: '10.0.x' + dotnet-version: '11.0.x' include-prerelease: true - name: Build and Test with dotnet run: dotnet test DevBetterWeb.slnx --filter FullyQualifiedName!~Vimeo.Tests --configuration Release diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c292cc72..75c4efea 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -18,10 +18,10 @@ jobs: - name: Checkout repo uses: actions/checkout@v7.0.0 - - name: Setup .NET 10 SDK + - name: Setup .NET 11 SDK uses: actions/setup-dotnet@v6 with: - dotnet-version: '10.0.x' + dotnet-version: '11.0.x' - name: Restore dependencies run: dotnet restore DevBetterWeb.slnx diff --git a/.github/workflows/repro-bug.yml b/.github/workflows/repro-bug.yml index ea0c19ab..64b70b32 100644 --- a/.github/workflows/repro-bug.yml +++ b/.github/workflows/repro-bug.yml @@ -32,7 +32,7 @@ defaults: shell: bash env: - DOTNET_VERSION: 10.0.x + DOTNET_VERSION: 11.0.x DOTNET_CONFIGURATION: Release # Set one or both. diff --git a/.vscode/launch.json b/.vscode/launch.json index 433eb280..68ce6d87 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -10,7 +10,7 @@ "request": "launch", "preLaunchTask": "build", // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/src/DevBetterWeb.Web/bin/Debug/net10.0/DevBetterWeb.Web.dll", + "program": "${workspaceFolder}/src/DevBetterWeb.Web/bin/Debug/net11.0/DevBetterWeb.Web.dll", "args": [], "cwd": "${workspaceFolder}/src/DevBetterWeb.Web", "stopAtEntry": false, diff --git a/Directory.Packages.props b/Directory.Packages.props index 9f00f1f7..62240741 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -5,18 +5,16 @@ - - - + runtime; build; native; contentfiles; analyzers @@ -24,77 +22,55 @@ - - - - - - - + - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + - - + - - - - + + - - - - + + - + all runtime; build; native; contentfiles; analyzers; buildtransitive - + \ No newline at end of file diff --git a/Dockerfile b/Dockerfile index b231e794..4d2a014d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,9 +1,9 @@ -FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS base +FROM mcr.microsoft.com/dotnet/aspnet:11.0 AS base WORKDIR /app EXPOSE 80 EXPOSE 443 -FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:11.0 AS build ARG BUILD_CONFIGURATION=Debug COPY *.slnx . COPY . . diff --git a/README.md b/README.md index 66c42502..371d1e18 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Head over to [devBetter.com](https://devbetter.com) to see the live site. Scroll ### Prerequisite -- [.NET 10 SDK](https://dotnet.microsoft.com/en-us/download) +- [.NET 11 SDK](https://dotnet.microsoft.com/en-us/download) - [The command-line interface (CLI) tools for Entity Framework Core](https://docs.microsoft.com/en-us/ef/core/cli/dotnet) ### Building and Running the App Locally diff --git a/global.json b/global.json index 8c3f2d6e..a0d0005e 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "10.*", + "version": "11.*", "rollForward": "latestFeature" } } \ No newline at end of file diff --git a/src/DevBetterWeb.Core/DevBetterWeb.Core.csproj b/src/DevBetterWeb.Core/DevBetterWeb.Core.csproj index 58f6a066..a08d7f28 100644 --- a/src/DevBetterWeb.Core/DevBetterWeb.Core.csproj +++ b/src/DevBetterWeb.Core/DevBetterWeb.Core.csproj @@ -1,7 +1,7 @@ - net10.0 + net11.0 DevBetterWeb.Core DevBetterWeb.Core latest @@ -23,8 +23,6 @@ - - diff --git a/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj b/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj index 6aa3cfc5..d9e28272 100644 --- a/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj +++ b/src/DevBetterWeb.Infrastructure/DevBetterWeb.Infrastructure.csproj @@ -1,6 +1,6 @@ - net10.0 + net11.0 DevBetterWeb.Infrastructure DevBetterWeb.Infrastructure latest diff --git a/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj b/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj index 5d7dc784..126eff12 100644 --- a/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj +++ b/src/DevBetterWeb.Web/DevBetterWeb.Web.csproj @@ -1,6 +1,6 @@ - net10.0 + net11.0 true DevBetterWeb.Web Exe @@ -27,7 +27,6 @@ - @@ -49,7 +48,8 @@ - + + diff --git a/src/DevBetterWeb.Web/Dockerfile b/src/DevBetterWeb.Web/Dockerfile index 76ba95f4..2152d0c8 100644 --- a/src/DevBetterWeb.Web/Dockerfile +++ b/src/DevBetterWeb.Web/Dockerfile @@ -3,7 +3,7 @@ # # RUN COMMAND # docker run --name devbetterweb --rm -it -p 5000:80 web -FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:11.0 AS build WORKDIR /app COPY *.slnx . @@ -13,7 +13,7 @@ RUN dotnet restore RUN dotnet publish -c Release -o out -FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime +FROM mcr.microsoft.com/dotnet/aspnet:11.0 AS runtime WORKDIR /app COPY --from=build /app/src/DevBetterWeb.Web/out ./ diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml b/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml index dd4fcba8..0984c304 100644 --- a/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml @@ -20,8 +20,9 @@
- - + + +
diff --git a/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml.cs b/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml.cs index 6d951619..9cb181fd 100644 --- a/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml.cs +++ b/src/DevBetterWeb.Web/Pages/User/MyProfile/EditAvatar.cshtml.cs @@ -9,6 +9,7 @@ using DevBetterWeb.Core.Interfaces; using DevBetterWeb.Core.Specs; using DevBetterWeb.Infrastructure.Identity.Data; +using DevBetterWeb.Web.Services; using Mediator; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; @@ -19,9 +20,6 @@ using Microsoft.Extensions.Logging; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; -using SixLabors.ImageSharp; -using SixLabors.ImageSharp.Formats.Jpeg; -using SixLabors.ImageSharp.Processing; namespace DevBetterWeb.Web.Pages.User; @@ -67,24 +65,39 @@ public async Task OnGetAsync() public async Task OnPostAsync() { - if (!ModelState.IsValid) - { - return Page(); - } - var currentUserName = User.Identity!.Name; var applicationUser = await _userManager.FindByNameAsync(currentUserName!); AvatarUrl = string.Format(Constants.AVATAR_IMGURL_FORMAT_STRING, applicationUser!.Id); + if (ImageFile is null || ImageFile.Length == 0) + { + ModelState.AddModelError(nameof(ImageFile), "Please choose an image file."); + } + + if (!ModelState.IsValid) + { + return Page(); + } + string fileName = applicationUser.Id + ".jpg"; - using (var stream = ImageFile.OpenReadStream()) + MemoryStream resizedImage; + try { - string extension = ImageFile.FileName.Split(".").Last(); - // TODO: validate if extension is correct + using var uploadStream = ImageFile!.OpenReadStream(); + resizedImage = AvatarImageResizer.ResizeToJpeg(uploadStream); + } + catch (InvalidImageException ex) + { + _logger.LogWarning(ex, "Rejected avatar upload for user {UserId}.", applicationUser.Id); + ModelState.AddModelError(nameof(ImageFile), "Please upload a JPG or PNG image no larger than 10,000 pixels on a side."); + return Page(); + } - var uploadSuccess = await UploadToBlob(fileName, stream); + using (resizedImage) + { + var uploadSuccess = await UploadToBlob(fileName, resizedImage); if (uploadSuccess) { @@ -123,19 +136,8 @@ private async Task UploadToBlob(string filename, // Get a reference to the blob address, then upload the file to the blob. CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(filename); - if (stream != null) - { - var modifiedImageStream = ResizeStream(stream); - - // OPTION B: pass in memory stream directly - _logger.LogInformation($"Uploading from Stream."); - await cloudBlockBlob.UploadFromStreamAsync(modifiedImageStream); - } - else - { - _logger.LogWarning($"Stream is null."); - return false; - } + _logger.LogInformation($"Uploading from Stream."); + await cloudBlockBlob.UploadFromStreamAsync(stream); return true; } @@ -145,23 +147,4 @@ private async Task UploadToBlob(string filename, throw new Exception("Error uploading file.", ex); } } - - private Stream ResizeStream(Stream stream) - { - // see: https://stackoverflow.com/a/55395009/13729 - var cloneStream = new MemoryStream(); - stream.Position = 0; - var image = Image.Load(stream); - _logger.LogWarning($"Resizing image. {image.Width} x {image.Height}"); - - var jpegEncoder = new JpegEncoder { Quality = 80 }; - var clone = image.Clone(context => context.Resize(new ResizeOptions - { - Mode = ResizeMode.Crop, - Size = new Size(500, 500) - })); - clone.Save(cloneStream, jpegEncoder); - cloneStream.Position = 0; - return cloneStream; - } } diff --git a/src/DevBetterWeb.Web/Program.cs b/src/DevBetterWeb.Web/Program.cs index cc36ac48..2da240f4 100644 --- a/src/DevBetterWeb.Web/Program.cs +++ b/src/DevBetterWeb.Web/Program.cs @@ -159,8 +159,7 @@ builder.Services.AddHealthChecks(); builder.Services.AddMvc() - .AddControllersAsServices() - .AddRazorRuntimeCompilation(); + .AddControllersAsServices(); builder.Services.AddSwaggerGen(c => { diff --git a/src/DevBetterWeb.Web/Services/AvatarImageResizer.cs b/src/DevBetterWeb.Web/Services/AvatarImageResizer.cs new file mode 100644 index 00000000..e7377b4c --- /dev/null +++ b/src/DevBetterWeb.Web/Services/AvatarImageResizer.cs @@ -0,0 +1,145 @@ +using System; +using System.IO; +using SkiaSharp; + +namespace DevBetterWeb.Web.Services; + +/// +/// Converts an uploaded image into a square JPEG avatar. +/// +public static class AvatarImageResizer +{ + public const int AvatarSize = 500; + public const int JpegQuality = 80; + + /// Largest accepted source width or height, in pixels. + public const int MaxSourceDimension = 10_000; + + /// Largest accepted source pixel count (40 megapixels). + public const long MaxSourcePixels = 40_000_000; + + /// + /// Applies EXIF orientation, center-crops the image to a square, and scales it to + /// x JPEG. Output carries no metadata. + /// + /// The stream is not a decodable image or is too large. + public static MemoryStream ResizeToJpeg(Stream input) + { + ArgumentNullException.ThrowIfNull(input); + + using var codec = SKCodec.Create(input) + ?? throw new InvalidImageException("Uploaded file is not a supported image."); + + var info = codec.Info; + if (info.Width <= 0 || info.Height <= 0 + || info.Width > MaxSourceDimension || info.Height > MaxSourceDimension + || (long)info.Width * info.Height > MaxSourcePixels) + { + throw new InvalidImageException("Uploaded image is too large."); + } + + using var source = Decode(codec); + using var oriented = ApplyOrientation(source, codec.EncodedOrigin); + oriented.SetImmutable(); + + int side = Math.Min(oriented.Width, oriented.Height); + var sourceRect = SKRect.Create((oriented.Width - side) / 2f, (oriented.Height - side) / 2f, side, side); + + using var surface = SKSurface.Create(new SKImageInfo(AvatarSize, AvatarSize)) + ?? throw new InvalidOperationException("Unable to allocate avatar surface."); + surface.Canvas.Clear(SKColors.White); + using var image = SKImage.FromBitmap(oriented); + surface.Canvas.DrawImage(image, sourceRect, SKRect.Create(AvatarSize, AvatarSize), + new SKSamplingOptions(SKFilterMode.Linear, SKMipmapMode.Linear)); + + using var resized = surface.Snapshot(); + using var data = resized.Encode(SKEncodedImageFormat.Jpeg, JpegQuality) + ?? throw new InvalidOperationException("Unable to encode avatar."); + + var output = new MemoryStream(); + data.SaveTo(output); + output.Position = 0; + return output; + } + + private static SKBitmap Decode(SKCodec codec) + { + // Let the codec downsample during decode (cheap for JPEG) while keeping enough detail for the avatar. + var info = codec.Info; + float scale = Math.Min(1f, (float)AvatarSize * 2 / Math.Min(info.Width, info.Height)); + var size = codec.GetScaledDimensions(scale); + var decodeInfo = new SKImageInfo(size.Width, size.Height, SKColorType.Rgba8888, SKAlphaType.Premul); + + var bitmap = new SKBitmap(decodeInfo); + var result = codec.GetPixels(decodeInfo, bitmap.GetPixels()); + if (result != SKCodecResult.Success && result != SKCodecResult.IncompleteInput) + { + // The codec cannot scale to that size; decode at full size instead. + bitmap.Dispose(); + decodeInfo = info.WithColorType(SKColorType.Rgba8888).WithAlphaType(SKAlphaType.Premul); + bitmap = new SKBitmap(decodeInfo); + result = codec.GetPixels(decodeInfo, bitmap.GetPixels()); + } + + if (result != SKCodecResult.Success && result != SKCodecResult.IncompleteInput) + { + bitmap.Dispose(); + throw new InvalidImageException("Uploaded file is not a supported image."); + } + + return bitmap; + } + + private static SKBitmap ApplyOrientation(SKBitmap source, SKEncodedOrigin origin) + { + if (origin == SKEncodedOrigin.TopLeft) + { + return source.Copy(); + } + + bool swapsAxes = origin is SKEncodedOrigin.LeftTop or SKEncodedOrigin.RightTop + or SKEncodedOrigin.RightBottom or SKEncodedOrigin.LeftBottom; + int width = swapsAxes ? source.Height : source.Width; + int height = swapsAxes ? source.Width : source.Height; + + var rotated = new SKBitmap(new SKImageInfo(width, height, source.ColorType, source.AlphaType)); + using var canvas = new SKCanvas(rotated); + switch (origin) + { + case SKEncodedOrigin.TopRight: + canvas.Scale(-1, 1, width / 2f, 0); + break; + case SKEncodedOrigin.BottomRight: + canvas.RotateDegrees(180, width / 2f, height / 2f); + break; + case SKEncodedOrigin.BottomLeft: + canvas.Scale(1, -1, 0, height / 2f); + break; + case SKEncodedOrigin.LeftTop: // transpose + canvas.Translate(width, 0); + canvas.RotateDegrees(90); + canvas.Translate(0, source.Height); + canvas.Scale(1, -1); + break; + case SKEncodedOrigin.RightTop: // rotate 90 clockwise + canvas.Translate(width, 0); + canvas.RotateDegrees(90); + break; + case SKEncodedOrigin.RightBottom: // transverse + canvas.Translate(width, 0); + canvas.RotateDegrees(90); + canvas.Translate(source.Width, 0); + canvas.Scale(-1, 1); + break; + case SKEncodedOrigin.LeftBottom: // rotate 270 clockwise + canvas.Translate(0, height); + canvas.RotateDegrees(270); + break; + } + canvas.DrawBitmap(source, 0, 0, new SKSamplingOptions(SKFilterMode.Nearest)); + return rotated; + } +} + +/// Thrown when an uploaded image cannot be used as an avatar. +public class InvalidImageException(string message) : Exception(message); diff --git a/tests/DevBetterWeb.FunctionalTests/DevBetterWeb.FunctionalTests.csproj b/tests/DevBetterWeb.FunctionalTests/DevBetterWeb.FunctionalTests.csproj index 93d93e18..f8792779 100644 --- a/tests/DevBetterWeb.FunctionalTests/DevBetterWeb.FunctionalTests.csproj +++ b/tests/DevBetterWeb.FunctionalTests/DevBetterWeb.FunctionalTests.csproj @@ -1,7 +1,7 @@ - net10.0 + net11.0 false diff --git a/tests/DevBetterWeb.Tests/DevBetterWeb.Tests.csproj b/tests/DevBetterWeb.Tests/DevBetterWeb.Tests.csproj index ee26f188..9dbcb199 100644 --- a/tests/DevBetterWeb.Tests/DevBetterWeb.Tests.csproj +++ b/tests/DevBetterWeb.Tests/DevBetterWeb.Tests.csproj @@ -1,6 +1,6 @@ - net10.0 + net11.0 true latest enable diff --git a/tests/DevBetterWeb.UnitTests/DevBetterWeb.UnitTests.csproj b/tests/DevBetterWeb.UnitTests/DevBetterWeb.UnitTests.csproj index 066749cb..3ff7781d 100644 --- a/tests/DevBetterWeb.UnitTests/DevBetterWeb.UnitTests.csproj +++ b/tests/DevBetterWeb.UnitTests/DevBetterWeb.UnitTests.csproj @@ -1,6 +1,6 @@ - net10.0 + net11.0 enable false diff --git a/tests/DevBetterWeb.UnitTests/Web/MappingProfiles/AutoMapperConfigurationTests.cs b/tests/DevBetterWeb.UnitTests/Web/MappingProfiles/AutoMapperConfigurationTests.cs new file mode 100644 index 00000000..ed530669 --- /dev/null +++ b/tests/DevBetterWeb.UnitTests/Web/MappingProfiles/AutoMapperConfigurationTests.cs @@ -0,0 +1,23 @@ +using AutoMapper; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace DevBetterWeb.UnitTests.Web.MappingProfiles; + +public class AutoMapperConfigurationTests +{ + [Fact] + public void Web_Mapping_Profiles_Load_And_Compile() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddAutoMapper(cfg => cfg.AddMaps(typeof(Program).Assembly)); + using var provider = services.BuildServiceProvider(); + + var mapper = provider.GetRequiredService(); + + // Profiles have known unmapped destination members, so AssertConfigurationIsValid is too strict. + // Compiling every map still catches expression/configuration breaks from AutoMapper upgrades. + mapper.ConfigurationProvider.CompileMappings(); + } +} diff --git a/tests/DevBetterWeb.UnitTests/Web/Services/AvatarImageResizerTests.cs b/tests/DevBetterWeb.UnitTests/Web/Services/AvatarImageResizerTests.cs new file mode 100644 index 00000000..4473ba75 --- /dev/null +++ b/tests/DevBetterWeb.UnitTests/Web/Services/AvatarImageResizerTests.cs @@ -0,0 +1,246 @@ +using System; +using System.IO; +using System.Linq; +using DevBetterWeb.Web.Services; +using Shouldly; +using SkiaSharp; +using Xunit; + +namespace DevBetterWeb.UnitTests.Web.Services; + +public class AvatarImageResizerTests +{ + private const int Mid = AvatarImageResizer.AvatarSize / 2; + private const int Quarter = AvatarImageResizer.AvatarSize / 4; + private const int ThreeQuarters = AvatarImageResizer.AvatarSize * 3 / 4; + + [Theory] + [InlineData(1200, 800, SKEncodedImageFormat.Png)] + [InlineData(300, 900, SKEncodedImageFormat.Jpeg)] + [InlineData(500, 500, SKEncodedImageFormat.Png)] + [InlineData(50, 50, SKEncodedImageFormat.Jpeg)] + [InlineData(4000, 3000, SKEncodedImageFormat.Jpeg)] + public void ResizeToJpeg_Returns_Square_Jpeg_Of_Avatar_Size(int width, int height, SKEncodedImageFormat inputFormat) + { + using var input = Encode(Solid(width, height, SKColors.Red), inputFormat); + + using var output = AvatarImageResizer.ResizeToJpeg(input); + + output.Position.ShouldBe(0); + using var codec = SKCodec.Create(output); + codec.ShouldNotBeNull(); + codec.EncodedFormat.ShouldBe(SKEncodedImageFormat.Jpeg); + codec.Info.Width.ShouldBe(AvatarImageResizer.AvatarSize); + codec.Info.Height.ShouldBe(AvatarImageResizer.AvatarSize); + } + + [Fact] + public void ResizeToJpeg_Center_Crops_Wide_Image() + { + // 300x100: blue | red | blue. Center crop keeps only red. + using var bitmap = Solid(300, 100, SKColors.Blue); + Fill(bitmap, SKRect.Create(100, 0, 100, 100), SKColors.Red); + + using var result = Resize(Encode(bitmap, SKEncodedImageFormat.Png)); + + AssertColor(result.GetPixel(10, Mid), SKColors.Red); + AssertColor(result.GetPixel(Mid, Mid), SKColors.Red); + AssertColor(result.GetPixel(AvatarImageResizer.AvatarSize - 10, Mid), SKColors.Red); + } + + [Fact] + public void ResizeToJpeg_Center_Crops_Tall_Image() + { + // 100x300: blue / red / blue. Center crop keeps only red. + using var bitmap = Solid(100, 300, SKColors.Blue); + Fill(bitmap, SKRect.Create(0, 100, 100, 100), SKColors.Red); + + using var result = Resize(Encode(bitmap, SKEncodedImageFormat.Png)); + + AssertColor(result.GetPixel(Mid, 10), SKColors.Red); + AssertColor(result.GetPixel(Mid, AvatarImageResizer.AvatarSize - 10), SKColors.Red); + } + + [Fact] + public void ResizeToJpeg_Fills_Transparent_Areas_With_White() + { + using var bitmap = Solid(200, 200, SKColors.Transparent); + + using var result = Resize(Encode(bitmap, SKEncodedImageFormat.Png)); + + AssertColor(result.GetPixel(Mid, Mid), SKColors.White); + } + + // Stored image quadrants: top-left green, top-right red, bottom half blue. + // Each EXIF orientation must place green and red in the quadrants a viewer would see. + [Theory] + [InlineData(1, "TL", "TR")] + [InlineData(2, "TR", "TL")] + [InlineData(3, "BR", "BL")] + [InlineData(4, "BL", "BR")] + [InlineData(5, "TL", "BL")] + [InlineData(6, "TR", "BR")] + [InlineData(7, "BR", "TR")] + [InlineData(8, "BL", "TL")] + public void ResizeToJpeg_Applies_Exif_Orientation(ushort orientation, string greenQuadrant, string redQuadrant) + { + using var bitmap = Solid(400, 400, SKColors.Blue); + Fill(bitmap, SKRect.Create(0, 0, 200, 200), SKColors.Lime); + Fill(bitmap, SKRect.Create(200, 0, 200, 200), SKColors.Red); + var jpeg = WithExifOrientation(EncodeBytes(bitmap, SKEncodedImageFormat.Jpeg), orientation); + + using var result = Resize(new MemoryStream(jpeg)); + + AssertColor(PixelAt(result, greenQuadrant), SKColors.Lime); + AssertColor(PixelAt(result, redQuadrant), SKColors.Red); + } + + [Fact] + public void ResizeToJpeg_Strips_Exif_Metadata() + { + var jpeg = WithExifOrientation(EncodeBytes(Solid(100, 100, SKColors.Red), SKEncodedImageFormat.Jpeg), 6); + + using var output = AvatarImageResizer.ResizeToJpeg(new MemoryStream(jpeg)); + + ContainsExifSegment(output.ToArray()).ShouldBeFalse(); + } + + [Fact] + public void ResizeToJpeg_Rejects_Image_With_Oversized_Dimensions() + { + // Header-only PNG claiming 20000x20000 pixels: must be rejected before any pixels are allocated. + using var input = new MemoryStream(PngHeader(20_000, 20_000)); + + Should.Throw(() => AvatarImageResizer.ResizeToJpeg(input)); + } + + [Fact] + public void ResizeToJpeg_Throws_For_Non_Image_Data() + { + using var input = new MemoryStream("not an image"u8.ToArray()); + + Should.Throw(() => AvatarImageResizer.ResizeToJpeg(input)); + } + + [Fact] + public void ResizeToJpeg_Throws_For_Null_Stream() + { + Should.Throw(() => AvatarImageResizer.ResizeToJpeg(null!)); + } + + private static SKBitmap Resize(Stream input) + { + using (input) + using (var output = AvatarImageResizer.ResizeToJpeg(input)) + { + return SKBitmap.Decode(output); + } + } + + private static SKColor PixelAt(SKBitmap bitmap, string quadrant) => quadrant switch + { + "TL" => bitmap.GetPixel(Quarter, Quarter), + "TR" => bitmap.GetPixel(ThreeQuarters, Quarter), + "BL" => bitmap.GetPixel(Quarter, ThreeQuarters), + "BR" => bitmap.GetPixel(ThreeQuarters, ThreeQuarters), + _ => throw new ArgumentOutOfRangeException(nameof(quadrant)), + }; + + private static void AssertColor(SKColor actual, SKColor expected) + { + // JPEG is lossy, so allow some tolerance per channel. + Math.Abs(actual.Red - expected.Red).ShouldBeLessThan(40, $"red channel of {actual}"); + Math.Abs(actual.Green - expected.Green).ShouldBeLessThan(40, $"green channel of {actual}"); + Math.Abs(actual.Blue - expected.Blue).ShouldBeLessThan(40, $"blue channel of {actual}"); + } + + private static SKBitmap Solid(int width, int height, SKColor color) + { + var bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Rgba8888, SKAlphaType.Premul)); + bitmap.Erase(color); + return bitmap; + } + + private static void Fill(SKBitmap bitmap, SKRect rect, SKColor color) + { + using var canvas = new SKCanvas(bitmap); + using var paint = new SKPaint { Color = color }; + canvas.DrawRect(rect, paint); + } + + private static MemoryStream Encode(SKBitmap bitmap, SKEncodedImageFormat format) + { + var stream = new MemoryStream(EncodeBytes(bitmap, format)); + bitmap.Dispose(); + return stream; + } + + private static byte[] EncodeBytes(SKBitmap bitmap, SKEncodedImageFormat format) + { + using var stream = new MemoryStream(); + bitmap.Encode(stream, format, 95).ShouldBeTrue(); + return stream.ToArray(); + } + + /// Inserts a minimal big-endian EXIF APP1 segment with the given orientation right after SOI. + private static byte[] WithExifOrientation(byte[] jpeg, ushort orientation) + { + byte[] exif = + [ + (byte)'E', (byte)'x', (byte)'i', (byte)'f', 0, 0, + (byte)'M', (byte)'M', 0, 42, 0, 0, 0, 8, // TIFF header, IFD0 at offset 8 + 0, 1, // one entry + 0x01, 0x12, 0, 3, 0, 0, 0, 1, (byte)(orientation >> 8), (byte)orientation, 0, 0, // Orientation, SHORT, 1 + 0, 0, 0, 0, // no next IFD + ]; + int length = exif.Length + 2; + byte[] segment = [0xFF, 0xE1, (byte)(length >> 8), (byte)length, .. exif]; + return [.. jpeg.Take(2), .. segment, .. jpeg.Skip(2)]; + } + + private static bool ContainsExifSegment(byte[] jpeg) + { + for (int i = 0; i + 9 < jpeg.Length; i++) + { + if (jpeg[i] == 0xFF && jpeg[i + 1] == 0xE1 && jpeg[i + 4] == 'E' && jpeg[i + 5] == 'x' + && jpeg[i + 6] == 'i' && jpeg[i + 7] == 'f') + { + return true; + } + } + return false; + } + + /// PNG signature plus an IHDR chunk only. Enough for a codec to read dimensions. + private static byte[] PngHeader(int width, int height) + { + byte[] ihdrData = + [ + (byte)'I', (byte)'H', (byte)'D', (byte)'R', + (byte)(width >> 24), (byte)(width >> 16), (byte)(width >> 8), (byte)width, + (byte)(height >> 24), (byte)(height >> 16), (byte)(height >> 8), (byte)height, + 8, 2, 0, 0, 0, // 8-bit RGB + ]; + uint crc = Crc32(ihdrData); + return + [ + 0x89, (byte)'P', (byte)'N', (byte)'G', 0x0D, 0x0A, 0x1A, 0x0A, + 0, 0, 0, 13, .. ihdrData, + (byte)(crc >> 24), (byte)(crc >> 16), (byte)(crc >> 8), (byte)crc, + ]; + } + + private static uint Crc32(byte[] data) + { + uint crc = 0xFFFFFFFF; + foreach (byte b in data) + { + crc ^= b; + for (int k = 0; k < 8; k++) + { + crc = (crc & 1) != 0 ? (crc >> 1) ^ 0xEDB88320 : crc >> 1; + } + } + return ~crc; + } +}