diff --git a/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs b/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs
index b794f3b0..5f3af176 100644
--- a/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs
+++ b/src/Nemera.Presentation.Web/Common/Http/HttpContextItemKeys.cs
@@ -29,4 +29,9 @@ public static class HttpContextItemKeys
/// The Cache-Control value chosen by the endpoint, restored when the response starts.
///
public const string CACHE_CONTROL = "CacheControl";
+
+ ///
+ /// The key under which the flag indicating that the endpoint bound its request and started executing is stored.
+ ///
+ public const string ENDPOINT_STARTED = "EndpointStarted";
}
diff --git a/src/Nemera.Presentation.Web/Common/Http/JsonBindingFailureClientErrorMetadata.cs b/src/Nemera.Presentation.Web/Common/Http/JsonBindingFailureClientErrorMetadata.cs
new file mode 100644
index 00000000..6762b105
--- /dev/null
+++ b/src/Nemera.Presentation.Web/Common/Http/JsonBindingFailureClientErrorMetadata.cs
@@ -0,0 +1,8 @@
+namespace Nemera.Presentation.Web.Common.Http;
+
+///
+/// Marks an endpoint whose malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope.
+///
+public sealed class JsonBindingFailureClientErrorMetadata
+{
+}
diff --git a/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs b/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs
index e3929f49..77b85bbc 100644
--- a/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs
+++ b/src/Nemera.Presentation.Web/Common/Middlewares/ExceptionHandlingMiddleware.cs
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.Exceptions;
+using Nemera.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using System;
+using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
@@ -61,6 +63,11 @@ public class ExceptionHandlingMiddleware
{
await HandleApiExceptionAsync(context, apiException);
}
+ catch (JsonException jsonException) when (IsOptedInJsonBindingFailure(context, jsonException))
+ {
+ // The JSON request body failed to bind before the endpoint ran, so the caller sent a body that does not match the request contract.
+ await HandleJsonBindingExceptionAsync(context, jsonException);
+ }
catch (Exception ex) // Other cases.
{
if (_logger.IsEnabled(LogLevel.Error))
@@ -100,6 +107,63 @@ public class ExceptionHandlingMiddleware
}
}
+ ///
+ /// Determines whether a JSON exception is a request body binding failure of an endpoint that opted into client error responses.
+ ///
+ /// The for the current request.
+ /// The JSON exception thrown while processing the request.
+ /// when the exception is a JSON body binding failure that should be reported as a client error.
+ private static bool IsOptedInJsonBindingFailure(HttpContext context, JsonException jsonException)
+ {
+ return jsonException is not FastEndpoints.JsonBindException
+ && !context.Items.ContainsKey(HttpContextItemKeys.ENDPOINT_STARTED)
+ && context.GetEndpoint()?.Metadata.GetMetadata() is not null;
+ }
+
+ ///
+ /// Handles a JSON request body that could not be deserialized into the request contract.
+ ///
+ /// The for the current request.
+ /// The exception thrown while binding the request body.
+ private async Task HandleJsonBindingExceptionAsync(HttpContext context, JsonException jsonException)
+ {
+ if (_logger.IsEnabled(LogLevel.Warning))
+ _logger.LogWarning(jsonException, "The JSON request body could not be deserialized: {Message}", jsonException.Message);
+
+ // Once the response has started, its status and headers are already on the wire, so they can no longer be replaced.
+ if (context.Response.HasStarted)
+ {
+ context.Abort();
+ return;
+ }
+
+ string errorMessage = _stringLocalizer["OneOrMoreValidationErrorsOccurred"].Value;
+ string? trimmedPath = jsonException.Path?.TrimStart('$', '.');
+ string fieldName = string.IsNullOrWhiteSpace(trimmedPath) ? "request" : trimmedPath;
+ if (IsJsonRequest(context))
+ {
+ context.Response.StatusCode = StatusCodes.Status400BadRequest;
+ await context.Response.WriteAsJsonAsync(
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.1",
+ title = "General.Validation",
+ status = StatusCodes.Status400BadRequest,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = context.Request.Path.ToString(),
+ errors = new Dictionary { [fieldName] = [errorMessage] },
+ errorMessage
+ },
+ options: null,
+ contentType: "application/problem+json",
+ cancellationToken: context.RequestAborted).ConfigureAwait(false);
+ }
+ else if (IsNavigationRequest(context))
+ await WriteHtmlErrorResponseAsync(context, StatusCodes.Status400BadRequest, errorMessage).ConfigureAwait(false);
+ else
+ await WriteStatusOnlyResponseAsync(context, StatusCodes.Status400BadRequest).ConfigureAwait(false);
+ }
+
///
/// Handles exceptions specific to the API, including problem details.
///
diff --git a/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs b/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs
index 413638a5..8947363a 100644
--- a/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs
+++ b/src/Nemera.Presentation.Web/Core/Endpoints/Common/BaseEndpoint.cs
@@ -3,6 +3,8 @@ using FastEndpoints;
using Nemera.Presentation.Web.Common.Http;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
#endregion
namespace Nemera.Presentation.Web.Core.Endpoints.Common;
@@ -31,6 +33,25 @@ public abstract class BaseEndpoint : Endpoint
+ /// Marks the endpoint so that malformed JSON request bodies are answered with a client error ProblemDetails instead of the default JSON error envelope.
+ ///
+ protected void ReportJsonBindingFailuresAsClientErrors()
+ {
+ Metadata(new JsonBindingFailureClientErrorMetadata());
+ }
+
+ ///
+ /// Marks the request as past request binding, so that JSON binding failures can be told apart from JSON failures thrown while the endpoint runs.
+ ///
+ /// The request bound from the incoming request.
+ /// Cancellation token that can be used to stop the execution.
+ public override Task OnBeforeHandleAsync(TRequest request, CancellationToken cancellationToken)
+ {
+ HttpContext.Items[HttpContextItemKeys.ENDPOINT_STARTED] = true;
+ return Task.CompletedTask;
+ }
+
///
/// Sets the Cache-Control header, and remembers the chosen value so that it can be restored after later components overwrite it.
///
diff --git a/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs b/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs
index 25c79ed0..05fa33c4 100644
--- a/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs
+++ b/src/Nemera.Presentation.Web/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpoint.cs
@@ -41,6 +41,7 @@ public class SaveBookEndpoint : BaseEndpoint
DontAutoTag();
Options(options => options.WithTags("Books"));
EnableAntiforgery();
+ ReportJsonBindingFailuresAsClientErrors();
}
///
diff --git a/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs
index 476475fa..e61dd826 100644
--- a/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs
+++ b/tests/IntegrationTests/Nemera.Presentation.Web.IntegrationTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs
@@ -6,9 +6,11 @@ using Nemera.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibr
using Nemera.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Nemera.Presentation.Web.Fixtures.Common.TestHelpers;
using Nemera.Presentation.Web.IntegrationTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
+using System.Text;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
@@ -124,6 +126,80 @@ public class SaveBookEndpointTests : IClassFixture
Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
}
+ [Fact]
+ public async Task SaveBook_WhenLibraryIdIsNotAGuid_ShouldReturnClientError()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid bookId = Guid.NewGuid();
+ Guid libraryId = Guid.NewGuid();
+ UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
+ string payload = JsonSerializer.Serialize(request, JsonSerializerOptions.Web);
+ payload = payload.Replace(libraryId.ToString(), "not-a-guid");
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book")
+ {
+ Content = new StringContent(payload, Encoding.UTF8, "application/json")
+ };
+ saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
+ using JsonDocument json = JsonDocument.Parse(content);
+ JsonElement problemDetails = json.RootElement;
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
+ Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
+ Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
+ Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
+ Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
+ Assert.True(problemDetails.GetProperty("errors").TryGetProperty("libraryId", out JsonElement fieldErrors));
+ Assert.Equal("One or more validation errors occurred", fieldErrors[0].GetString());
+ Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
+ }
+
+ [Fact]
+ public async Task SaveBook_WhenBodyIsMalformedJson_ShouldReturnClientError()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid bookId = Guid.NewGuid();
+ const string PAYLOAD = "{\"contributors\": [";
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book")
+ {
+ Content = new StringContent(PAYLOAD, Encoding.UTF8, "application/json")
+ };
+ saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
+ using JsonDocument json = JsonDocument.Parse(content);
+ JsonElement problemDetails = json.RootElement;
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
+ Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
+ Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
+ Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
+ Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
+ Assert.NotEmpty(problemDetails.GetProperty("errors").EnumerateObject());
+ Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
+ Assert.DoesNotContain(PAYLOAD, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
///
/// Builds the save request that PUTs the given to the book identified by .
///
diff --git a/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs b/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs
index 90a818e2..05b69787 100644
--- a/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs
+++ b/tests/SecurityTests/Nemera.Presentation.Web.SecurityTests/Core/Endpoints/Library/WrittenContentLibrary/BookLibrary/Books/SaveBook/SaveBookEndpointTests.cs
@@ -6,12 +6,14 @@ using Nemera.Presentation.Web.Fixtures.Common.DTO.WrittenContentLibrary.BookLibr
using Nemera.Presentation.Web.Fixtures.Common.Requests.Library.WrittenContentLibrary.BookLibrary.Books;
using Nemera.Presentation.Web.Fixtures.Common.TestHelpers;
using Nemera.Presentation.Web.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
+using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
@@ -97,6 +99,79 @@ public class SaveBookEndpointTests : IClassFixture
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == $"libraries/{libraryId}/books/{bookId}" && putRequest.Data is UpdateBookRequest forwarded && forwarded.Metadata!.Title == maliciousTitle);
}
+ [Fact]
+ public async Task SaveBook_WhenLibraryIdIsNotAGuid_ShouldReturnClientErrorWithoutLeakingInternals()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid bookId = Guid.NewGuid();
+ Guid libraryId = Guid.NewGuid();
+ UpdateBookRequest request = _updateBookRequestFixture.Create(id: bookId, libraryId: libraryId);
+ string maliciousLibraryId = "'; DROP TABLE Libraries--";
+ string payload = JsonSerializer.Serialize(request, JsonSerializerOptions.Web);
+ payload = payload.Replace(libraryId.ToString(), maliciousLibraryId);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage saveRequest = CreateRawSaveRequest(bookId.ToString(), payload);
+ saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
+ using JsonDocument json = JsonDocument.Parse(content);
+ JsonElement problemDetails = json.RootElement;
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
+ Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
+ Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
+ Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
+ Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
+ Assert.True(problemDetails.GetProperty("errors").TryGetProperty("libraryId", out JsonElement fieldErrors));
+ Assert.Equal("One or more validation errors occurred", fieldErrors[0].GetString());
+ Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task SaveBook_WhenBodyIsMalformedJson_ShouldReturnClientErrorWithoutLeakingInternals()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid bookId = Guid.NewGuid();
+ const string PAYLOAD = "{\"contributors\": [";
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage saveRequest = CreateRawSaveRequest(bookId.ToString(), PAYLOAD);
+ saveRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(saveRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType!.MediaType);
+ using JsonDocument json = JsonDocument.Parse(content);
+ JsonElement problemDetails = json.RootElement;
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
+ Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
+ Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
+ Assert.Equal($"/en-us/library/written-content-library/books-library/books/{bookId}/api-save-book", problemDetails.GetProperty("instance").GetString());
+ Assert.Equal("One or more validation errors occurred", problemDetails.GetProperty("errorMessage").GetString());
+ Assert.NotEmpty(problemDetails.GetProperty("errors").EnumerateObject());
+ Assert.Empty(_apiFactory.ApiClientStub.PutRequests);
+ Assert.DoesNotContain(PAYLOAD, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("at Nemera", content, StringComparison.OrdinalIgnoreCase);
+ }
+
[Fact]
public async Task SaveBook_WhenCalledWithoutAuthentication_ShouldRedirectToLogin()
{
@@ -129,4 +204,20 @@ public class SaveBookEndpointTests : IClassFixture
saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return saveRequest;
}
+
+ ///
+ /// Builds a save request that sends the given raw JSON body to the book identified by .
+ ///
+ /// The route Id of the book to save.
+ /// The raw JSON body to send.
+ /// The configured save request.
+ private static HttpRequestMessage CreateRawSaveRequest(string bookId, string jsonBody)
+ {
+ HttpRequestMessage saveRequest = new(HttpMethod.Put, $"/en-us/library/written-content-library/books-library/books/{Uri.EscapeDataString(bookId)}/api-save-book")
+ {
+ Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
+ };
+ saveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ return saveRequest;
+ }
}
diff --git a/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs
index d777786f..ee583f6c 100644
--- a/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs
+++ b/tests/UnitTests/Nemera.Presentation.Web.UnitTests/Common/Middlewares/ExceptionHandlingMiddlewareTests.cs
@@ -1,11 +1,13 @@
#region ========================================================================= USING =====================================================================================
using Nemera.Presentation.Web.Common.DTO.Common;
using Nemera.Presentation.Web.Common.Exceptions;
+using Nemera.Presentation.Web.Common.Http;
using Nemera.Presentation.Web.Common.Middlewares;
using Nemera.Presentation.Web.Fixtures.Common.DTO.Common;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
@@ -17,6 +19,7 @@ using System.Net;
using System.Security.Claims;
using System.Text;
using System.Text.Json;
+using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -172,6 +175,170 @@ public class ExceptionHandlingMiddlewareTests
Assert.Equal(0, httpContext.Response.Body.Length);
}
+ [Fact]
+ public async Task InvokeAsync_WhenRequestBindingThrowsJsonExceptionAndApiRequest_ShouldWriteBadRequestProblemDetails()
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
+ httpContext.Request.Path = "/books/1";
+ ConfigureJsonBindingFailureEndpoint(httpContext);
+ _nextDelegate = _ => throw new JsonException("The JSON value could not be converted to System.Guid.", "$.contributors[0].contributorId", 0, 10);
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode);
+ Assert.Equal("application/problem+json", httpContext.Response.ContentType);
+ string body = await ReadResponseBodyAsync(httpContext);
+ using JsonDocument jsonDocument = JsonDocument.Parse(body);
+ JsonElement problemDetails = jsonDocument.RootElement;
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.1", problemDetails.GetProperty("type").GetString());
+ Assert.Equal("General.Validation", problemDetails.GetProperty("title").GetString());
+ Assert.Equal(StatusCodes.Status400BadRequest, problemDetails.GetProperty("status").GetInt32());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("detail").GetString());
+ Assert.Equal("/books/1", problemDetails.GetProperty("instance").GetString());
+ Assert.Equal("localized:OneOrMoreValidationErrorsOccurred", problemDetails.GetProperty("errorMessage").GetString());
+ Assert.True(problemDetails.GetProperty("errors").TryGetProperty("contributors[0].contributorId", out JsonElement fieldErrors));
+ Assert.Equal("localized:OneOrMoreValidationErrorsOccurred", fieldErrors[0].GetString());
+ }
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData(" ")]
+ [InlineData("$")]
+ public async Task InvokeAsync_WhenJsonExceptionHasNoFieldPath_ShouldReportTheRequestAsTheErrorField(string? path)
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
+ ConfigureJsonBindingFailureEndpoint(httpContext);
+ _nextDelegate = _ => throw new JsonException("The JSON body is malformed.", path, 0, 10);
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ string body = await ReadResponseBodyAsync(httpContext);
+ using JsonDocument jsonDocument = JsonDocument.Parse(body);
+ Assert.True(jsonDocument.RootElement.GetProperty("errors").TryGetProperty("request", out JsonElement fieldErrors));
+ Assert.Equal("localized:OneOrMoreValidationErrorsOccurred", fieldErrors[0].GetString());
+ }
+
+ [Fact]
+ public async Task InvokeAsync_WhenJsonBindExceptionOccursOnAnOptedInEndpoint_ShouldKeepTheJsonErrorEnvelope()
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
+ ConfigureJsonBindingFailureEndpoint(httpContext);
+ _nextDelegate = _ => throw new FastEndpoints.JsonBindException(
+ "value",
+ "Value is not valid.",
+ new JsonException("The JSON value could not be converted.", "$.value", 0, 10));
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ Assert.Equal(StatusCodes.Status200OK, httpContext.Response.StatusCode);
+ string body = await ReadResponseBodyAsync(httpContext);
+ using JsonDocument jsonDocument = JsonDocument.Parse(body);
+ Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
+ Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
+ }
+
+ [Fact]
+ public async Task InvokeAsync_WhenJsonBindingExceptionOccursAfterResponseStarted_ShouldAbortWithoutWritingProblemDetails()
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
+ ConfigureJsonBindingFailureEndpoint(httpContext);
+ RecordingRequestLifetimeFeature lifetimeFeature = new();
+ httpContext.Features.Set(lifetimeFeature);
+ httpContext.Features.Set(new StartedHttpResponseFeature());
+ _nextDelegate = _ => throw new JsonException("The JSON body is malformed.", "$.contributors", 0, 10);
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ Assert.True(httpContext.Response.HasStarted);
+ Assert.True(lifetimeFeature.WasAborted);
+ Assert.Equal(0, httpContext.Response.Body.Length);
+ }
+
+ [Fact]
+ public async Task InvokeAsync_WhenRequestBindingThrowsJsonExceptionAndRawRequest_ShouldWriteBadRequestWithoutBody()
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext();
+ httpContext.Request.Headers.Accept = "audio/mpeg";
+ ConfigureJsonBindingFailureEndpoint(httpContext);
+ _nextDelegate = _ => throw new JsonException("The JSON body is malformed.", "$.id", 0, 10);
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode);
+ Assert.Equal(0, httpContext.Response.Body.Length);
+ }
+
+ [Fact]
+ public async Task InvokeAsync_WhenRequestBindingThrowsJsonExceptionAndPageRequest_ShouldWriteBadRequestHtmlPage()
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext();
+ httpContext.Request.Headers.Accept = "text/html";
+ ConfigureJsonBindingFailureEndpoint(httpContext);
+ _nextDelegate = _ => throw new JsonException("The JSON value could not be converted to System.Guid.", "$.contributors[0].contributorId", 0, 10);
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ Assert.Equal(StatusCodes.Status400BadRequest, httpContext.Response.StatusCode);
+ Assert.Contains("text/html", httpContext.Response.ContentType);
+ Assert.Contains("localized:OneOrMoreValidationErrorsOccurred", await ReadResponseBodyAsync(httpContext));
+ }
+
+ [Fact]
+ public async Task InvokeAsync_WhenJsonExceptionOccursAfterEndpointStarted_ShouldTreatItAsAnUnexpectedError()
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
+ ConfigureJsonBindingFailureEndpoint(httpContext);
+ httpContext.Items[HttpContextItemKeys.ENDPOINT_STARTED] = true;
+ _nextDelegate = _ => throw new JsonException("Malformed API response.", "$.id", 0, 10);
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ string body = await ReadResponseBodyAsync(httpContext);
+ using JsonDocument jsonDocument = JsonDocument.Parse(body);
+ Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
+ Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
+ }
+
+ [Fact]
+ public async Task InvokeAsync_WhenJsonExceptionOccursOnAnEndpointThatDidNotOptIn_ShouldKeepTheJsonErrorEnvelope()
+ {
+ // Arrange
+ DefaultHttpContext httpContext = CreateHttpContext(isApiRequest: true);
+ httpContext.SetEndpoint(new Endpoint(requestDelegate: null, new EndpointMetadataCollection(), displayName: "TestEndpoint"));
+ _nextDelegate = _ => throw new JsonException("The JSON value could not be converted to System.Guid.", "$.contributors[0].contributorId", 0, 10);
+
+ // Act
+ await _sut.InvokeAsync(httpContext);
+
+ // Assert
+ string body = await ReadResponseBodyAsync(httpContext);
+ using JsonDocument jsonDocument = JsonDocument.Parse(body);
+ Assert.False(jsonDocument.RootElement.GetProperty("success").GetBoolean());
+ Assert.Equal("localized:InternalServerError", jsonDocument.RootElement.GetProperty("errorMessage").GetString());
+ }
+
[Fact]
public async Task InvokeAsync_WhenApiExceptionUnauthorizedAndApiRequest_ShouldSignOutAndWriteUnauthorizedJson()
{
@@ -464,6 +631,18 @@ public class ExceptionHandlingMiddlewareTests
return httpContext;
}
+ ///
+ /// Marks the endpoint of the provided HTTP context as one that reports JSON binding failures as client errors.
+ ///
+ /// The HTTP context whose endpoint is marked.
+ private static void ConfigureJsonBindingFailureEndpoint(DefaultHttpContext httpContext)
+ {
+ httpContext.SetEndpoint(new Endpoint(
+ requestDelegate: null,
+ new EndpointMetadataCollection(new JsonBindingFailureClientErrorMetadata()),
+ displayName: "TestEndpoint"));
+ }
+
///
/// Creates a service provider that resolves the mocked .
///
@@ -527,4 +706,79 @@ public class ExceptionHandlingMiddlewareTests
""";
return JsonSerializer.Deserialize(problemDetailsJson)!;
}
+
+ ///
+ /// Response feature that reports the response as already started, so tests can exercise the abort branch of the middleware.
+ ///
+ [ExcludeFromCodeCoverage]
+ private sealed class StartedHttpResponseFeature : IHttpResponseFeature
+ {
+ ///
+ /// Gets or sets the status code of the response.
+ ///
+ public int StatusCode { get; set; } = StatusCodes.Status200OK;
+
+ ///
+ /// Gets or sets the reason phrase of the response.
+ ///
+ public string? ReasonPhrase { get; set; }
+
+ ///
+ /// Gets or sets the response headers.
+ ///
+ public IHeaderDictionary Headers { get; set; } = new HeaderDictionary();
+
+ ///
+ /// Gets or sets the response body.
+ ///
+ public Stream Body { get; set; } = new MemoryStream();
+
+ ///
+ /// Gets a value indicating whether the response has started.
+ ///
+ public bool HasStarted => true;
+
+ ///
+ /// Registers a callback invoked before the response starts.
+ ///
+ /// The callback to invoke.
+ /// The state passed to the callback.
+ public void OnStarting(Func